PackageManagerService.java revision 30dc2a08667d56fdd3eecdcb70abec1b28d821f4
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 94import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 96import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 97import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 98import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 101import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 104 105import android.Manifest; 106import android.annotation.NonNull; 107import android.annotation.Nullable; 108import android.app.ActivityManager; 109import android.app.AppOpsManager; 110import android.app.IActivityManager; 111import android.app.ResourcesManager; 112import android.app.admin.IDevicePolicyManager; 113import android.app.admin.SecurityLog; 114import android.app.backup.IBackupManager; 115import android.content.BroadcastReceiver; 116import android.content.ComponentName; 117import android.content.ContentResolver; 118import android.content.Context; 119import android.content.IIntentReceiver; 120import android.content.Intent; 121import android.content.IntentFilter; 122import android.content.IntentSender; 123import android.content.IntentSender.SendIntentException; 124import android.content.ServiceConnection; 125import android.content.pm.ActivityInfo; 126import android.content.pm.ApplicationInfo; 127import android.content.pm.AppsQueryHelper; 128import android.content.pm.ChangedPackages; 129import android.content.pm.ComponentInfo; 130import android.content.pm.InstantAppRequest; 131import android.content.pm.AuxiliaryResolveInfo; 132import android.content.pm.FallbackCategoryProvider; 133import android.content.pm.FeatureInfo; 134import android.content.pm.IOnPermissionsChangeListener; 135import android.content.pm.IPackageDataObserver; 136import android.content.pm.IPackageDeleteObserver; 137import android.content.pm.IPackageDeleteObserver2; 138import android.content.pm.IPackageInstallObserver2; 139import android.content.pm.IPackageInstaller; 140import android.content.pm.IPackageManager; 141import android.content.pm.IPackageMoveObserver; 142import android.content.pm.IPackageStatsObserver; 143import android.content.pm.InstantAppInfo; 144import android.content.pm.InstantAppResolveInfo; 145import android.content.pm.InstrumentationInfo; 146import android.content.pm.IntentFilterVerificationInfo; 147import android.content.pm.KeySet; 148import android.content.pm.PackageCleanItem; 149import android.content.pm.PackageInfo; 150import android.content.pm.PackageInfoLite; 151import android.content.pm.PackageInstaller; 152import android.content.pm.PackageManager; 153import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 154import android.content.pm.PackageManagerInternal; 155import android.content.pm.PackageParser; 156import android.content.pm.PackageParser.ActivityIntentInfo; 157import android.content.pm.PackageParser.PackageLite; 158import android.content.pm.PackageParser.PackageParserException; 159import android.content.pm.PackageStats; 160import android.content.pm.PackageUserState; 161import android.content.pm.ParceledListSlice; 162import android.content.pm.PermissionGroupInfo; 163import android.content.pm.PermissionInfo; 164import android.content.pm.ProviderInfo; 165import android.content.pm.ResolveInfo; 166import android.content.pm.ServiceInfo; 167import android.content.pm.SharedLibraryInfo; 168import android.content.pm.Signature; 169import android.content.pm.UserInfo; 170import android.content.pm.VerifierDeviceIdentity; 171import android.content.pm.VerifierInfo; 172import android.content.pm.VersionedPackage; 173import android.content.res.Resources; 174import android.database.ContentObserver; 175import android.graphics.Bitmap; 176import android.hardware.display.DisplayManager; 177import android.net.Uri; 178import android.os.Binder; 179import android.os.Build; 180import android.os.Bundle; 181import android.os.Debug; 182import android.os.Environment; 183import android.os.Environment.UserEnvironment; 184import android.os.FileUtils; 185import android.os.Handler; 186import android.os.IBinder; 187import android.os.Looper; 188import android.os.Message; 189import android.os.Parcel; 190import android.os.ParcelFileDescriptor; 191import android.os.PatternMatcher; 192import android.os.Process; 193import android.os.RemoteCallbackList; 194import android.os.RemoteException; 195import android.os.ResultReceiver; 196import android.os.SELinux; 197import android.os.ServiceManager; 198import android.os.ShellCallback; 199import android.os.SystemClock; 200import android.os.SystemProperties; 201import android.os.Trace; 202import android.os.UserHandle; 203import android.os.UserManager; 204import android.os.UserManagerInternal; 205import android.os.storage.IStorageManager; 206import android.os.storage.StorageEventListener; 207import android.os.storage.StorageManager; 208import android.os.storage.StorageManagerInternal; 209import android.os.storage.VolumeInfo; 210import android.os.storage.VolumeRecord; 211import android.provider.Settings.Global; 212import android.provider.Settings.Secure; 213import android.security.KeyStore; 214import android.security.SystemKeyStore; 215import android.service.pm.PackageServiceDumpProto; 216import android.system.ErrnoException; 217import android.system.Os; 218import android.text.TextUtils; 219import android.text.format.DateUtils; 220import android.util.ArrayMap; 221import android.util.ArraySet; 222import android.util.Base64; 223import android.util.BootTimingsTraceLog; 224import android.util.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.DumpUtils; 258import com.android.internal.util.FastPrintWriter; 259import com.android.internal.util.FastXmlSerializer; 260import com.android.internal.util.IndentingPrintWriter; 261import com.android.internal.util.Preconditions; 262import com.android.internal.util.XmlUtils; 263import com.android.server.AttributeCache; 264import com.android.server.DeviceIdleController; 265import com.android.server.EventLogTags; 266import com.android.server.FgThread; 267import com.android.server.IntentResolver; 268import com.android.server.LocalServices; 269import com.android.server.LockGuard; 270import com.android.server.ServiceThread; 271import com.android.server.SystemConfig; 272import com.android.server.SystemServerInitThreadPool; 273import com.android.server.Watchdog; 274import com.android.server.net.NetworkPolicyManagerInternal; 275import com.android.server.pm.Installer.InstallerException; 276import com.android.server.pm.PermissionsState.PermissionState; 277import com.android.server.pm.Settings.DatabaseVersion; 278import com.android.server.pm.Settings.VersionInfo; 279import com.android.server.pm.dex.DexManager; 280import com.android.server.storage.DeviceStorageMonitorInternal; 281 282import dalvik.system.CloseGuard; 283import dalvik.system.DexFile; 284import dalvik.system.VMRuntime; 285 286import libcore.io.IoUtils; 287import libcore.util.EmptyArray; 288 289import org.xmlpull.v1.XmlPullParser; 290import org.xmlpull.v1.XmlPullParserException; 291import org.xmlpull.v1.XmlSerializer; 292 293import java.io.BufferedOutputStream; 294import java.io.BufferedReader; 295import java.io.ByteArrayInputStream; 296import java.io.ByteArrayOutputStream; 297import java.io.File; 298import java.io.FileDescriptor; 299import java.io.FileInputStream; 300import java.io.FileOutputStream; 301import java.io.FileReader; 302import java.io.FilenameFilter; 303import java.io.IOException; 304import java.io.PrintWriter; 305import java.nio.charset.StandardCharsets; 306import java.security.DigestInputStream; 307import java.security.MessageDigest; 308import java.security.NoSuchAlgorithmException; 309import java.security.PublicKey; 310import java.security.SecureRandom; 311import java.security.cert.Certificate; 312import java.security.cert.CertificateEncodingException; 313import java.security.cert.CertificateException; 314import java.text.SimpleDateFormat; 315import java.util.ArrayList; 316import java.util.Arrays; 317import java.util.Collection; 318import java.util.Collections; 319import java.util.Comparator; 320import java.util.Date; 321import java.util.HashMap; 322import java.util.HashSet; 323import java.util.Iterator; 324import java.util.List; 325import java.util.Map; 326import java.util.Objects; 327import java.util.Set; 328import java.util.concurrent.CountDownLatch; 329import java.util.concurrent.Future; 330import java.util.concurrent.TimeUnit; 331import java.util.concurrent.atomic.AtomicBoolean; 332import java.util.concurrent.atomic.AtomicInteger; 333 334/** 335 * Keep track of all those APKs everywhere. 336 * <p> 337 * Internally there are two important locks: 338 * <ul> 339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 340 * and other related state. It is a fine-grained lock that should only be held 341 * momentarily, as it's one of the most contended locks in the system. 342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 343 * operations typically involve heavy lifting of application data on disk. Since 344 * {@code installd} is single-threaded, and it's operations can often be slow, 345 * this lock should never be acquired while already holding {@link #mPackages}. 346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 347 * holding {@link #mInstallLock}. 348 * </ul> 349 * Many internal methods rely on the caller to hold the appropriate locks, and 350 * this contract is expressed through method name suffixes: 351 * <ul> 352 * <li>fooLI(): the caller must hold {@link #mInstallLock} 353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 354 * being modified must be frozen 355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 357 * </ul> 358 * <p> 359 * Because this class is very central to the platform's security; please run all 360 * CTS and unit tests whenever making modifications: 361 * 362 * <pre> 363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 365 * </pre> 366 */ 367public class PackageManagerService extends IPackageManager.Stub 368 implements PackageSender { 369 static final String TAG = "PackageManager"; 370 static final boolean DEBUG_SETTINGS = false; 371 static final boolean DEBUG_PREFERRED = false; 372 static final boolean DEBUG_UPGRADE = false; 373 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 374 private static final boolean DEBUG_BACKUP = false; 375 private static final boolean DEBUG_INSTALL = false; 376 private static final boolean DEBUG_REMOVE = false; 377 private static final boolean DEBUG_BROADCASTS = false; 378 private static final boolean DEBUG_SHOW_INFO = false; 379 private static final boolean DEBUG_PACKAGE_INFO = false; 380 private static final boolean DEBUG_INTENT_MATCHING = false; 381 private static final boolean DEBUG_PACKAGE_SCANNING = false; 382 private static final boolean DEBUG_VERIFY = false; 383 private static final boolean DEBUG_FILTERS = false; 384 385 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 386 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 387 // user, but by default initialize to this. 388 public static final boolean DEBUG_DEXOPT = false; 389 390 private static final boolean DEBUG_ABI_SELECTION = false; 391 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 392 private static final boolean DEBUG_TRIAGED_MISSING = false; 393 private static final boolean DEBUG_APP_DATA = false; 394 395 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 396 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 397 398 private static final boolean HIDE_EPHEMERAL_APIS = false; 399 400 private static final boolean ENABLE_FREE_CACHE_V2 = 401 SystemProperties.getBoolean("fw.free_cache_v2", true); 402 403 private static final int RADIO_UID = Process.PHONE_UID; 404 private static final int LOG_UID = Process.LOG_UID; 405 private static final int NFC_UID = Process.NFC_UID; 406 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 407 private static final int SHELL_UID = Process.SHELL_UID; 408 409 // Cap the size of permission trees that 3rd party apps can define 410 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 411 412 // Suffix used during package installation when copying/moving 413 // package apks to install directory. 414 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 415 416 static final int SCAN_NO_DEX = 1<<1; 417 static final int SCAN_FORCE_DEX = 1<<2; 418 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 419 static final int SCAN_NEW_INSTALL = 1<<4; 420 static final int SCAN_UPDATE_TIME = 1<<5; 421 static final int SCAN_BOOTING = 1<<6; 422 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 423 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 424 static final int SCAN_REPLACING = 1<<9; 425 static final int SCAN_REQUIRE_KNOWN = 1<<10; 426 static final int SCAN_MOVE = 1<<11; 427 static final int SCAN_INITIAL = 1<<12; 428 static final int SCAN_CHECK_ONLY = 1<<13; 429 static final int SCAN_DONT_KILL_APP = 1<<14; 430 static final int SCAN_IGNORE_FROZEN = 1<<15; 431 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 432 static final int SCAN_AS_INSTANT_APP = 1<<17; 433 static final int SCAN_AS_FULL_APP = 1<<18; 434 /** Should not be with the scan flags */ 435 static final int FLAGS_REMOVE_CHATTY = 1<<31; 436 437 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 438 439 private static final int[] EMPTY_INT_ARRAY = new int[0]; 440 441 /** 442 * Timeout (in milliseconds) after which the watchdog should declare that 443 * our handler thread is wedged. The usual default for such things is one 444 * minute but we sometimes do very lengthy I/O operations on this thread, 445 * such as installing multi-gigabyte applications, so ours needs to be longer. 446 */ 447 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 448 449 /** 450 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 451 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 452 * settings entry if available, otherwise we use the hardcoded default. If it's been 453 * more than this long since the last fstrim, we force one during the boot sequence. 454 * 455 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 456 * one gets run at the next available charging+idle time. This final mandatory 457 * no-fstrim check kicks in only of the other scheduling criteria is never met. 458 */ 459 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 460 461 /** 462 * Whether verification is enabled by default. 463 */ 464 private static final boolean DEFAULT_VERIFY_ENABLE = true; 465 466 /** 467 * The default maximum time to wait for the verification agent to return in 468 * milliseconds. 469 */ 470 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 471 472 /** 473 * The default response for package verification timeout. 474 * 475 * This can be either PackageManager.VERIFICATION_ALLOW or 476 * PackageManager.VERIFICATION_REJECT. 477 */ 478 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 479 480 static final String PLATFORM_PACKAGE_NAME = "android"; 481 482 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 483 484 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 485 DEFAULT_CONTAINER_PACKAGE, 486 "com.android.defcontainer.DefaultContainerService"); 487 488 private static final String KILL_APP_REASON_GIDS_CHANGED = 489 "permission grant or revoke changed gids"; 490 491 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 492 "permissions revoked"; 493 494 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 495 496 private static final String PACKAGE_SCHEME = "package"; 497 498 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 499 500 /** Permission grant: not grant the permission. */ 501 private static final int GRANT_DENIED = 1; 502 503 /** Permission grant: grant the permission as an install permission. */ 504 private static final int GRANT_INSTALL = 2; 505 506 /** Permission grant: grant the permission as a runtime one. */ 507 private static final int GRANT_RUNTIME = 3; 508 509 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 510 private static final int GRANT_UPGRADE = 4; 511 512 /** Canonical intent used to identify what counts as a "web browser" app */ 513 private static final Intent sBrowserIntent; 514 static { 515 sBrowserIntent = new Intent(); 516 sBrowserIntent.setAction(Intent.ACTION_VIEW); 517 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 518 sBrowserIntent.setData(Uri.parse("http:")); 519 } 520 521 /** 522 * The set of all protected actions [i.e. those actions for which a high priority 523 * intent filter is disallowed]. 524 */ 525 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 526 static { 527 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 528 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 530 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 531 } 532 533 // Compilation reasons. 534 public static final int REASON_FIRST_BOOT = 0; 535 public static final int REASON_BOOT = 1; 536 public static final int REASON_INSTALL = 2; 537 public static final int REASON_BACKGROUND_DEXOPT = 3; 538 public static final int REASON_AB_OTA = 4; 539 540 public static final int REASON_LAST = REASON_AB_OTA; 541 542 /** All dangerous permission names in the same order as the events in MetricsEvent */ 543 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 544 Manifest.permission.READ_CALENDAR, 545 Manifest.permission.WRITE_CALENDAR, 546 Manifest.permission.CAMERA, 547 Manifest.permission.READ_CONTACTS, 548 Manifest.permission.WRITE_CONTACTS, 549 Manifest.permission.GET_ACCOUNTS, 550 Manifest.permission.ACCESS_FINE_LOCATION, 551 Manifest.permission.ACCESS_COARSE_LOCATION, 552 Manifest.permission.RECORD_AUDIO, 553 Manifest.permission.READ_PHONE_STATE, 554 Manifest.permission.CALL_PHONE, 555 Manifest.permission.READ_CALL_LOG, 556 Manifest.permission.WRITE_CALL_LOG, 557 Manifest.permission.ADD_VOICEMAIL, 558 Manifest.permission.USE_SIP, 559 Manifest.permission.PROCESS_OUTGOING_CALLS, 560 Manifest.permission.READ_CELL_BROADCASTS, 561 Manifest.permission.BODY_SENSORS, 562 Manifest.permission.SEND_SMS, 563 Manifest.permission.RECEIVE_SMS, 564 Manifest.permission.READ_SMS, 565 Manifest.permission.RECEIVE_WAP_PUSH, 566 Manifest.permission.RECEIVE_MMS, 567 Manifest.permission.READ_EXTERNAL_STORAGE, 568 Manifest.permission.WRITE_EXTERNAL_STORAGE, 569 Manifest.permission.READ_PHONE_NUMBERS, 570 Manifest.permission.ANSWER_PHONE_CALLS); 571 572 573 /** 574 * Version number for the package parser cache. Increment this whenever the format or 575 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 576 */ 577 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 578 579 /** 580 * Whether the package parser cache is enabled. 581 */ 582 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 583 584 final ServiceThread mHandlerThread; 585 586 final PackageHandler mHandler; 587 588 private final ProcessLoggingHandler mProcessLoggingHandler; 589 590 /** 591 * Messages for {@link #mHandler} that need to wait for system ready before 592 * being dispatched. 593 */ 594 private ArrayList<Message> mPostSystemReadyMessages; 595 596 final int mSdkVersion = Build.VERSION.SDK_INT; 597 598 final Context mContext; 599 final boolean mFactoryTest; 600 final boolean mOnlyCore; 601 final DisplayMetrics mMetrics; 602 final int mDefParseFlags; 603 final String[] mSeparateProcesses; 604 final boolean mIsUpgrade; 605 final boolean mIsPreNUpgrade; 606 final boolean mIsPreNMR1Upgrade; 607 608 // Have we told the Activity Manager to whitelist the default container service by uid yet? 609 @GuardedBy("mPackages") 610 boolean mDefaultContainerWhitelisted = false; 611 612 @GuardedBy("mPackages") 613 private boolean mDexOptDialogShown; 614 615 /** The location for ASEC container files on internal storage. */ 616 final String mAsecInternalPath; 617 618 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 619 // LOCK HELD. Can be called with mInstallLock held. 620 @GuardedBy("mInstallLock") 621 final Installer mInstaller; 622 623 /** Directory where installed third-party apps stored */ 624 final File mAppInstallDir; 625 626 /** 627 * Directory to which applications installed internally have their 628 * 32 bit native libraries copied. 629 */ 630 private File mAppLib32InstallDir; 631 632 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 633 // apps. 634 final File mDrmAppPrivateInstallDir; 635 636 // ---------------------------------------------------------------- 637 638 // Lock for state used when installing and doing other long running 639 // operations. Methods that must be called with this lock held have 640 // the suffix "LI". 641 final Object mInstallLock = new Object(); 642 643 // ---------------------------------------------------------------- 644 645 // Keys are String (package name), values are Package. This also serves 646 // as the lock for the global state. Methods that must be called with 647 // this lock held have the prefix "LP". 648 @GuardedBy("mPackages") 649 final ArrayMap<String, PackageParser.Package> mPackages = 650 new ArrayMap<String, PackageParser.Package>(); 651 652 final ArrayMap<String, Set<String>> mKnownCodebase = 653 new ArrayMap<String, Set<String>>(); 654 655 // Keys are isolated uids and values are the uid of the application 656 // that created the isolated proccess. 657 @GuardedBy("mPackages") 658 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 659 660 // List of APK paths to load for each user and package. This data is never 661 // persisted by the package manager. Instead, the overlay manager will 662 // ensure the data is up-to-date in runtime. 663 @GuardedBy("mPackages") 664 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 665 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 666 667 /** 668 * Tracks new system packages [received in an OTA] that we expect to 669 * find updated user-installed versions. Keys are package name, values 670 * are package location. 671 */ 672 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 673 /** 674 * Tracks high priority intent filters for protected actions. During boot, certain 675 * filter actions are protected and should never be allowed to have a high priority 676 * intent filter for them. However, there is one, and only one exception -- the 677 * setup wizard. It must be able to define a high priority intent filter for these 678 * actions to ensure there are no escapes from the wizard. We need to delay processing 679 * of these during boot as we need to look at all of the system packages in order 680 * to know which component is the setup wizard. 681 */ 682 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 683 /** 684 * Whether or not processing protected filters should be deferred. 685 */ 686 private boolean mDeferProtectedFilters = true; 687 688 /** 689 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 690 */ 691 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 692 /** 693 * Whether or not system app permissions should be promoted from install to runtime. 694 */ 695 boolean mPromoteSystemApps; 696 697 @GuardedBy("mPackages") 698 final Settings mSettings; 699 700 /** 701 * Set of package names that are currently "frozen", which means active 702 * surgery is being done on the code/data for that package. The platform 703 * will refuse to launch frozen packages to avoid race conditions. 704 * 705 * @see PackageFreezer 706 */ 707 @GuardedBy("mPackages") 708 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 709 710 final ProtectedPackages mProtectedPackages; 711 712 boolean mFirstBoot; 713 714 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 715 716 // System configuration read by SystemConfig. 717 final int[] mGlobalGids; 718 final SparseArray<ArraySet<String>> mSystemPermissions; 719 @GuardedBy("mAvailableFeatures") 720 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 721 722 // If mac_permissions.xml was found for seinfo labeling. 723 boolean mFoundPolicyFile; 724 725 private final InstantAppRegistry mInstantAppRegistry; 726 727 @GuardedBy("mPackages") 728 int mChangedPackagesSequenceNumber; 729 /** 730 * List of changed [installed, removed or updated] packages. 731 * mapping from user id -> sequence number -> package name 732 */ 733 @GuardedBy("mPackages") 734 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 735 /** 736 * The sequence number of the last change to a package. 737 * mapping from user id -> package name -> sequence number 738 */ 739 @GuardedBy("mPackages") 740 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 741 742 class PackageParserCallback implements PackageParser.Callback { 743 @Override public final boolean hasFeature(String feature) { 744 return PackageManagerService.this.hasSystemFeature(feature, 0); 745 } 746 747 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 748 Collection<PackageParser.Package> allPackages, String targetPackageName) { 749 List<PackageParser.Package> overlayPackages = null; 750 for (PackageParser.Package p : allPackages) { 751 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 752 if (overlayPackages == null) { 753 overlayPackages = new ArrayList<PackageParser.Package>(); 754 } 755 overlayPackages.add(p); 756 } 757 } 758 if (overlayPackages != null) { 759 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 760 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 761 return p1.mOverlayPriority - p2.mOverlayPriority; 762 } 763 }; 764 Collections.sort(overlayPackages, cmp); 765 } 766 return overlayPackages; 767 } 768 769 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 770 String targetPackageName, String targetPath) { 771 if ("android".equals(targetPackageName)) { 772 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 773 // native AssetManager. 774 return null; 775 } 776 List<PackageParser.Package> overlayPackages = 777 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 778 if (overlayPackages == null || overlayPackages.isEmpty()) { 779 return null; 780 } 781 List<String> overlayPathList = null; 782 for (PackageParser.Package overlayPackage : overlayPackages) { 783 if (targetPath == null) { 784 if (overlayPathList == null) { 785 overlayPathList = new ArrayList<String>(); 786 } 787 overlayPathList.add(overlayPackage.baseCodePath); 788 continue; 789 } 790 791 try { 792 // Creates idmaps for system to parse correctly the Android manifest of the 793 // target package. 794 // 795 // OverlayManagerService will update each of them with a correct gid from its 796 // target package app id. 797 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 798 UserHandle.getSharedAppGid( 799 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 800 if (overlayPathList == null) { 801 overlayPathList = new ArrayList<String>(); 802 } 803 overlayPathList.add(overlayPackage.baseCodePath); 804 } catch (InstallerException e) { 805 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 806 overlayPackage.baseCodePath); 807 } 808 } 809 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 810 } 811 812 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 813 synchronized (mPackages) { 814 return getStaticOverlayPathsLocked( 815 mPackages.values(), targetPackageName, targetPath); 816 } 817 } 818 819 @Override public final String[] getOverlayApks(String targetPackageName) { 820 return getStaticOverlayPaths(targetPackageName, null); 821 } 822 823 @Override public final String[] getOverlayPaths(String targetPackageName, 824 String targetPath) { 825 return getStaticOverlayPaths(targetPackageName, targetPath); 826 } 827 }; 828 829 class ParallelPackageParserCallback extends PackageParserCallback { 830 List<PackageParser.Package> mOverlayPackages = null; 831 832 void findStaticOverlayPackages() { 833 synchronized (mPackages) { 834 for (PackageParser.Package p : mPackages.values()) { 835 if (p.mIsStaticOverlay) { 836 if (mOverlayPackages == null) { 837 mOverlayPackages = new ArrayList<PackageParser.Package>(); 838 } 839 mOverlayPackages.add(p); 840 } 841 } 842 } 843 } 844 845 @Override 846 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 847 // We can trust mOverlayPackages without holding mPackages because package uninstall 848 // can't happen while running parallel parsing. 849 // Moreover holding mPackages on each parsing thread causes dead-lock. 850 return mOverlayPackages == null ? null : 851 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 852 } 853 } 854 855 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 856 final ParallelPackageParserCallback mParallelPackageParserCallback = 857 new ParallelPackageParserCallback(); 858 859 public static final class SharedLibraryEntry { 860 public final String path; 861 public final String apk; 862 public final SharedLibraryInfo info; 863 864 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 865 String declaringPackageName, int declaringPackageVersionCode) { 866 path = _path; 867 apk = _apk; 868 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 869 declaringPackageName, declaringPackageVersionCode), null); 870 } 871 } 872 873 // Currently known shared libraries. 874 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 875 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 876 new ArrayMap<>(); 877 878 // All available activities, for your resolving pleasure. 879 final ActivityIntentResolver mActivities = 880 new ActivityIntentResolver(); 881 882 // All available receivers, for your resolving pleasure. 883 final ActivityIntentResolver mReceivers = 884 new ActivityIntentResolver(); 885 886 // All available services, for your resolving pleasure. 887 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 888 889 // All available providers, for your resolving pleasure. 890 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 891 892 // Mapping from provider base names (first directory in content URI codePath) 893 // to the provider information. 894 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 895 new ArrayMap<String, PackageParser.Provider>(); 896 897 // Mapping from instrumentation class names to info about them. 898 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 899 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 900 901 // Mapping from permission names to info about them. 902 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 903 new ArrayMap<String, PackageParser.PermissionGroup>(); 904 905 // Packages whose data we have transfered into another package, thus 906 // should no longer exist. 907 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 908 909 // Broadcast actions that are only available to the system. 910 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 911 912 /** List of packages waiting for verification. */ 913 final SparseArray<PackageVerificationState> mPendingVerification 914 = new SparseArray<PackageVerificationState>(); 915 916 /** Set of packages associated with each app op permission. */ 917 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 918 919 final PackageInstallerService mInstallerService; 920 921 private final PackageDexOptimizer mPackageDexOptimizer; 922 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 923 // is used by other apps). 924 private final DexManager mDexManager; 925 926 private AtomicInteger mNextMoveId = new AtomicInteger(); 927 private final MoveCallbacks mMoveCallbacks; 928 929 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 930 931 // Cache of users who need badging. 932 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 933 934 /** Token for keys in mPendingVerification. */ 935 private int mPendingVerificationToken = 0; 936 937 volatile boolean mSystemReady; 938 volatile boolean mSafeMode; 939 volatile boolean mHasSystemUidErrors; 940 private volatile boolean mEphemeralAppsDisabled; 941 942 ApplicationInfo mAndroidApplication; 943 final ActivityInfo mResolveActivity = new ActivityInfo(); 944 final ResolveInfo mResolveInfo = new ResolveInfo(); 945 ComponentName mResolveComponentName; 946 PackageParser.Package mPlatformPackage; 947 ComponentName mCustomResolverComponentName; 948 949 boolean mResolverReplaced = false; 950 951 private final @Nullable ComponentName mIntentFilterVerifierComponent; 952 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 953 954 private int mIntentFilterVerificationToken = 0; 955 956 /** The service connection to the ephemeral resolver */ 957 final EphemeralResolverConnection mInstantAppResolverConnection; 958 /** Component used to show resolver settings for Instant Apps */ 959 final ComponentName mInstantAppResolverSettingsComponent; 960 961 /** Activity used to install instant applications */ 962 ActivityInfo mInstantAppInstallerActivity; 963 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 964 965 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 966 = new SparseArray<IntentFilterVerificationState>(); 967 968 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 969 970 // List of packages names to keep cached, even if they are uninstalled for all users 971 private List<String> mKeepUninstalledPackages; 972 973 private UserManagerInternal mUserManagerInternal; 974 975 private DeviceIdleController.LocalService mDeviceIdleController; 976 977 private File mCacheDir; 978 979 private ArraySet<String> mPrivappPermissionsViolations; 980 981 private Future<?> mPrepareAppDataFuture; 982 983 private static class IFVerificationParams { 984 PackageParser.Package pkg; 985 boolean replacing; 986 int userId; 987 int verifierUid; 988 989 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 990 int _userId, int _verifierUid) { 991 pkg = _pkg; 992 replacing = _replacing; 993 userId = _userId; 994 replacing = _replacing; 995 verifierUid = _verifierUid; 996 } 997 } 998 999 private interface IntentFilterVerifier<T extends IntentFilter> { 1000 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1001 T filter, String packageName); 1002 void startVerifications(int userId); 1003 void receiveVerificationResponse(int verificationId); 1004 } 1005 1006 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1007 private Context mContext; 1008 private ComponentName mIntentFilterVerifierComponent; 1009 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1010 1011 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1012 mContext = context; 1013 mIntentFilterVerifierComponent = verifierComponent; 1014 } 1015 1016 private String getDefaultScheme() { 1017 return IntentFilter.SCHEME_HTTPS; 1018 } 1019 1020 @Override 1021 public void startVerifications(int userId) { 1022 // Launch verifications requests 1023 int count = mCurrentIntentFilterVerifications.size(); 1024 for (int n=0; n<count; n++) { 1025 int verificationId = mCurrentIntentFilterVerifications.get(n); 1026 final IntentFilterVerificationState ivs = 1027 mIntentFilterVerificationStates.get(verificationId); 1028 1029 String packageName = ivs.getPackageName(); 1030 1031 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1032 final int filterCount = filters.size(); 1033 ArraySet<String> domainsSet = new ArraySet<>(); 1034 for (int m=0; m<filterCount; m++) { 1035 PackageParser.ActivityIntentInfo filter = filters.get(m); 1036 domainsSet.addAll(filter.getHostsList()); 1037 } 1038 synchronized (mPackages) { 1039 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1040 packageName, domainsSet) != null) { 1041 scheduleWriteSettingsLocked(); 1042 } 1043 } 1044 sendVerificationRequest(userId, verificationId, ivs); 1045 } 1046 mCurrentIntentFilterVerifications.clear(); 1047 } 1048 1049 private void sendVerificationRequest(int userId, int verificationId, 1050 IntentFilterVerificationState ivs) { 1051 1052 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1053 verificationIntent.putExtra( 1054 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1055 verificationId); 1056 verificationIntent.putExtra( 1057 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1058 getDefaultScheme()); 1059 verificationIntent.putExtra( 1060 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1061 ivs.getHostsString()); 1062 verificationIntent.putExtra( 1063 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1064 ivs.getPackageName()); 1065 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1066 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1067 1068 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1069 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1070 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1071 userId, false, "intent filter verifier"); 1072 1073 UserHandle user = new UserHandle(userId); 1074 mContext.sendBroadcastAsUser(verificationIntent, user); 1075 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1076 "Sending IntentFilter verification broadcast"); 1077 } 1078 1079 public void receiveVerificationResponse(int verificationId) { 1080 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1081 1082 final boolean verified = ivs.isVerified(); 1083 1084 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1085 final int count = filters.size(); 1086 if (DEBUG_DOMAIN_VERIFICATION) { 1087 Slog.i(TAG, "Received verification response " + verificationId 1088 + " for " + count + " filters, verified=" + verified); 1089 } 1090 for (int n=0; n<count; n++) { 1091 PackageParser.ActivityIntentInfo filter = filters.get(n); 1092 filter.setVerified(verified); 1093 1094 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1095 + " verified with result:" + verified + " and hosts:" 1096 + ivs.getHostsString()); 1097 } 1098 1099 mIntentFilterVerificationStates.remove(verificationId); 1100 1101 final String packageName = ivs.getPackageName(); 1102 IntentFilterVerificationInfo ivi = null; 1103 1104 synchronized (mPackages) { 1105 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1106 } 1107 if (ivi == null) { 1108 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1109 + verificationId + " packageName:" + packageName); 1110 return; 1111 } 1112 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1113 "Updating IntentFilterVerificationInfo for package " + packageName 1114 +" verificationId:" + verificationId); 1115 1116 synchronized (mPackages) { 1117 if (verified) { 1118 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1119 } else { 1120 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1121 } 1122 scheduleWriteSettingsLocked(); 1123 1124 final int userId = ivs.getUserId(); 1125 if (userId != UserHandle.USER_ALL) { 1126 final int userStatus = 1127 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1128 1129 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1130 boolean needUpdate = false; 1131 1132 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1133 // already been set by the User thru the Disambiguation dialog 1134 switch (userStatus) { 1135 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1136 if (verified) { 1137 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1138 } else { 1139 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1140 } 1141 needUpdate = true; 1142 break; 1143 1144 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1145 if (verified) { 1146 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1147 needUpdate = true; 1148 } 1149 break; 1150 1151 default: 1152 // Nothing to do 1153 } 1154 1155 if (needUpdate) { 1156 mSettings.updateIntentFilterVerificationStatusLPw( 1157 packageName, updatedStatus, userId); 1158 scheduleWritePackageRestrictionsLocked(userId); 1159 } 1160 } 1161 } 1162 } 1163 1164 @Override 1165 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1166 ActivityIntentInfo filter, String packageName) { 1167 if (!hasValidDomains(filter)) { 1168 return false; 1169 } 1170 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1171 if (ivs == null) { 1172 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1173 packageName); 1174 } 1175 if (DEBUG_DOMAIN_VERIFICATION) { 1176 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1177 } 1178 ivs.addFilter(filter); 1179 return true; 1180 } 1181 1182 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1183 int userId, int verificationId, String packageName) { 1184 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1185 verifierUid, userId, packageName); 1186 ivs.setPendingState(); 1187 synchronized (mPackages) { 1188 mIntentFilterVerificationStates.append(verificationId, ivs); 1189 mCurrentIntentFilterVerifications.add(verificationId); 1190 } 1191 return ivs; 1192 } 1193 } 1194 1195 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1196 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1197 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1198 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1199 } 1200 1201 // Set of pending broadcasts for aggregating enable/disable of components. 1202 static class PendingPackageBroadcasts { 1203 // for each user id, a map of <package name -> components within that package> 1204 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1205 1206 public PendingPackageBroadcasts() { 1207 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1208 } 1209 1210 public ArrayList<String> get(int userId, String packageName) { 1211 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1212 return packages.get(packageName); 1213 } 1214 1215 public void put(int userId, String packageName, ArrayList<String> components) { 1216 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1217 packages.put(packageName, components); 1218 } 1219 1220 public void remove(int userId, String packageName) { 1221 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1222 if (packages != null) { 1223 packages.remove(packageName); 1224 } 1225 } 1226 1227 public void remove(int userId) { 1228 mUidMap.remove(userId); 1229 } 1230 1231 public int userIdCount() { 1232 return mUidMap.size(); 1233 } 1234 1235 public int userIdAt(int n) { 1236 return mUidMap.keyAt(n); 1237 } 1238 1239 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1240 return mUidMap.get(userId); 1241 } 1242 1243 public int size() { 1244 // total number of pending broadcast entries across all userIds 1245 int num = 0; 1246 for (int i = 0; i< mUidMap.size(); i++) { 1247 num += mUidMap.valueAt(i).size(); 1248 } 1249 return num; 1250 } 1251 1252 public void clear() { 1253 mUidMap.clear(); 1254 } 1255 1256 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1257 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1258 if (map == null) { 1259 map = new ArrayMap<String, ArrayList<String>>(); 1260 mUidMap.put(userId, map); 1261 } 1262 return map; 1263 } 1264 } 1265 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1266 1267 // Service Connection to remote media container service to copy 1268 // package uri's from external media onto secure containers 1269 // or internal storage. 1270 private IMediaContainerService mContainerService = null; 1271 1272 static final int SEND_PENDING_BROADCAST = 1; 1273 static final int MCS_BOUND = 3; 1274 static final int END_COPY = 4; 1275 static final int INIT_COPY = 5; 1276 static final int MCS_UNBIND = 6; 1277 static final int START_CLEANING_PACKAGE = 7; 1278 static final int FIND_INSTALL_LOC = 8; 1279 static final int POST_INSTALL = 9; 1280 static final int MCS_RECONNECT = 10; 1281 static final int MCS_GIVE_UP = 11; 1282 static final int UPDATED_MEDIA_STATUS = 12; 1283 static final int WRITE_SETTINGS = 13; 1284 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1285 static final int PACKAGE_VERIFIED = 15; 1286 static final int CHECK_PENDING_VERIFICATION = 16; 1287 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1288 static final int INTENT_FILTER_VERIFIED = 18; 1289 static final int WRITE_PACKAGE_LIST = 19; 1290 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1291 1292 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1293 1294 // Delay time in millisecs 1295 static final int BROADCAST_DELAY = 10 * 1000; 1296 1297 static UserManagerService sUserManager; 1298 1299 // Stores a list of users whose package restrictions file needs to be updated 1300 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1301 1302 final private DefaultContainerConnection mDefContainerConn = 1303 new DefaultContainerConnection(); 1304 class DefaultContainerConnection implements ServiceConnection { 1305 public void onServiceConnected(ComponentName name, IBinder service) { 1306 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1307 final IMediaContainerService imcs = IMediaContainerService.Stub 1308 .asInterface(Binder.allowBlocking(service)); 1309 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1310 } 1311 1312 public void onServiceDisconnected(ComponentName name) { 1313 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1314 } 1315 } 1316 1317 // Recordkeeping of restore-after-install operations that are currently in flight 1318 // between the Package Manager and the Backup Manager 1319 static class PostInstallData { 1320 public InstallArgs args; 1321 public PackageInstalledInfo res; 1322 1323 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1324 args = _a; 1325 res = _r; 1326 } 1327 } 1328 1329 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1330 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1331 1332 // XML tags for backup/restore of various bits of state 1333 private static final String TAG_PREFERRED_BACKUP = "pa"; 1334 private static final String TAG_DEFAULT_APPS = "da"; 1335 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1336 1337 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1338 private static final String TAG_ALL_GRANTS = "rt-grants"; 1339 private static final String TAG_GRANT = "grant"; 1340 private static final String ATTR_PACKAGE_NAME = "pkg"; 1341 1342 private static final String TAG_PERMISSION = "perm"; 1343 private static final String ATTR_PERMISSION_NAME = "name"; 1344 private static final String ATTR_IS_GRANTED = "g"; 1345 private static final String ATTR_USER_SET = "set"; 1346 private static final String ATTR_USER_FIXED = "fixed"; 1347 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1348 1349 // System/policy permission grants are not backed up 1350 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1351 FLAG_PERMISSION_POLICY_FIXED 1352 | FLAG_PERMISSION_SYSTEM_FIXED 1353 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1354 1355 // And we back up these user-adjusted states 1356 private static final int USER_RUNTIME_GRANT_MASK = 1357 FLAG_PERMISSION_USER_SET 1358 | FLAG_PERMISSION_USER_FIXED 1359 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1360 1361 final @Nullable String mRequiredVerifierPackage; 1362 final @NonNull String mRequiredInstallerPackage; 1363 final @NonNull String mRequiredUninstallerPackage; 1364 final @Nullable String mSetupWizardPackage; 1365 final @Nullable String mStorageManagerPackage; 1366 final @NonNull String mServicesSystemSharedLibraryPackageName; 1367 final @NonNull String mSharedSystemSharedLibraryPackageName; 1368 1369 final boolean mPermissionReviewRequired; 1370 1371 private final PackageUsage mPackageUsage = new PackageUsage(); 1372 private final CompilerStats mCompilerStats = new CompilerStats(); 1373 1374 class PackageHandler extends Handler { 1375 private boolean mBound = false; 1376 final ArrayList<HandlerParams> mPendingInstalls = 1377 new ArrayList<HandlerParams>(); 1378 1379 private boolean connectToService() { 1380 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1381 " DefaultContainerService"); 1382 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1383 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1384 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1385 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 mBound = true; 1388 return true; 1389 } 1390 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1391 return false; 1392 } 1393 1394 private void disconnectService() { 1395 mContainerService = null; 1396 mBound = false; 1397 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1398 mContext.unbindService(mDefContainerConn); 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1400 } 1401 1402 PackageHandler(Looper looper) { 1403 super(looper); 1404 } 1405 1406 public void handleMessage(Message msg) { 1407 try { 1408 doHandleMessage(msg); 1409 } finally { 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 } 1412 } 1413 1414 void doHandleMessage(Message msg) { 1415 switch (msg.what) { 1416 case INIT_COPY: { 1417 HandlerParams params = (HandlerParams) msg.obj; 1418 int idx = mPendingInstalls.size(); 1419 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1420 // If a bind was already initiated we dont really 1421 // need to do anything. The pending install 1422 // will be processed later on. 1423 if (!mBound) { 1424 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1425 System.identityHashCode(mHandler)); 1426 // If this is the only one pending we might 1427 // have to bind to the service again. 1428 if (!connectToService()) { 1429 Slog.e(TAG, "Failed to bind to media container service"); 1430 params.serviceError(); 1431 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1432 System.identityHashCode(mHandler)); 1433 if (params.traceMethod != null) { 1434 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1435 params.traceCookie); 1436 } 1437 return; 1438 } else { 1439 // Once we bind to the service, the first 1440 // pending request will be processed. 1441 mPendingInstalls.add(idx, params); 1442 } 1443 } else { 1444 mPendingInstalls.add(idx, params); 1445 // Already bound to the service. Just make 1446 // sure we trigger off processing the first request. 1447 if (idx == 0) { 1448 mHandler.sendEmptyMessage(MCS_BOUND); 1449 } 1450 } 1451 break; 1452 } 1453 case MCS_BOUND: { 1454 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1455 if (msg.obj != null) { 1456 mContainerService = (IMediaContainerService) msg.obj; 1457 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1458 System.identityHashCode(mHandler)); 1459 } 1460 if (mContainerService == null) { 1461 if (!mBound) { 1462 // Something seriously wrong since we are not bound and we are not 1463 // waiting for connection. Bail out. 1464 Slog.e(TAG, "Cannot bind to media container service"); 1465 for (HandlerParams params : mPendingInstalls) { 1466 // Indicate service bind error 1467 params.serviceError(); 1468 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1469 System.identityHashCode(params)); 1470 if (params.traceMethod != null) { 1471 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1472 params.traceMethod, params.traceCookie); 1473 } 1474 return; 1475 } 1476 mPendingInstalls.clear(); 1477 } else { 1478 Slog.w(TAG, "Waiting to connect to media container service"); 1479 } 1480 } else if (mPendingInstalls.size() > 0) { 1481 HandlerParams params = mPendingInstalls.get(0); 1482 if (params != null) { 1483 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1484 System.identityHashCode(params)); 1485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1486 if (params.startCopy()) { 1487 // We are done... look for more work or to 1488 // go idle. 1489 if (DEBUG_SD_INSTALL) Log.i(TAG, 1490 "Checking for more work or unbind..."); 1491 // Delete pending install 1492 if (mPendingInstalls.size() > 0) { 1493 mPendingInstalls.remove(0); 1494 } 1495 if (mPendingInstalls.size() == 0) { 1496 if (mBound) { 1497 if (DEBUG_SD_INSTALL) Log.i(TAG, 1498 "Posting delayed MCS_UNBIND"); 1499 removeMessages(MCS_UNBIND); 1500 Message ubmsg = obtainMessage(MCS_UNBIND); 1501 // Unbind after a little delay, to avoid 1502 // continual thrashing. 1503 sendMessageDelayed(ubmsg, 10000); 1504 } 1505 } else { 1506 // There are more pending requests in queue. 1507 // Just post MCS_BOUND message to trigger processing 1508 // of next pending install. 1509 if (DEBUG_SD_INSTALL) Log.i(TAG, 1510 "Posting MCS_BOUND for next work"); 1511 mHandler.sendEmptyMessage(MCS_BOUND); 1512 } 1513 } 1514 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1515 } 1516 } else { 1517 // Should never happen ideally. 1518 Slog.w(TAG, "Empty queue"); 1519 } 1520 break; 1521 } 1522 case MCS_RECONNECT: { 1523 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1524 if (mPendingInstalls.size() > 0) { 1525 if (mBound) { 1526 disconnectService(); 1527 } 1528 if (!connectToService()) { 1529 Slog.e(TAG, "Failed to bind to media container service"); 1530 for (HandlerParams params : mPendingInstalls) { 1531 // Indicate service bind error 1532 params.serviceError(); 1533 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1534 System.identityHashCode(params)); 1535 } 1536 mPendingInstalls.clear(); 1537 } 1538 } 1539 break; 1540 } 1541 case MCS_UNBIND: { 1542 // If there is no actual work left, then time to unbind. 1543 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1544 1545 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1546 if (mBound) { 1547 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1548 1549 disconnectService(); 1550 } 1551 } else if (mPendingInstalls.size() > 0) { 1552 // There are more pending requests in queue. 1553 // Just post MCS_BOUND message to trigger processing 1554 // of next pending install. 1555 mHandler.sendEmptyMessage(MCS_BOUND); 1556 } 1557 1558 break; 1559 } 1560 case MCS_GIVE_UP: { 1561 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1562 HandlerParams params = mPendingInstalls.remove(0); 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1564 System.identityHashCode(params)); 1565 break; 1566 } 1567 case SEND_PENDING_BROADCAST: { 1568 String packages[]; 1569 ArrayList<String> components[]; 1570 int size = 0; 1571 int uids[]; 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 if (mPendingBroadcasts == null) { 1575 return; 1576 } 1577 size = mPendingBroadcasts.size(); 1578 if (size <= 0) { 1579 // Nothing to be done. Just return 1580 return; 1581 } 1582 packages = new String[size]; 1583 components = new ArrayList[size]; 1584 uids = new int[size]; 1585 int i = 0; // filling out the above arrays 1586 1587 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1588 int packageUserId = mPendingBroadcasts.userIdAt(n); 1589 Iterator<Map.Entry<String, ArrayList<String>>> it 1590 = mPendingBroadcasts.packagesForUserId(packageUserId) 1591 .entrySet().iterator(); 1592 while (it.hasNext() && i < size) { 1593 Map.Entry<String, ArrayList<String>> ent = it.next(); 1594 packages[i] = ent.getKey(); 1595 components[i] = ent.getValue(); 1596 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1597 uids[i] = (ps != null) 1598 ? UserHandle.getUid(packageUserId, ps.appId) 1599 : -1; 1600 i++; 1601 } 1602 } 1603 size = i; 1604 mPendingBroadcasts.clear(); 1605 } 1606 // Send broadcasts 1607 for (int i = 0; i < size; i++) { 1608 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1609 } 1610 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1611 break; 1612 } 1613 case START_CLEANING_PACKAGE: { 1614 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1615 final String packageName = (String)msg.obj; 1616 final int userId = msg.arg1; 1617 final boolean andCode = msg.arg2 != 0; 1618 synchronized (mPackages) { 1619 if (userId == UserHandle.USER_ALL) { 1620 int[] users = sUserManager.getUserIds(); 1621 for (int user : users) { 1622 mSettings.addPackageToCleanLPw( 1623 new PackageCleanItem(user, packageName, andCode)); 1624 } 1625 } else { 1626 mSettings.addPackageToCleanLPw( 1627 new PackageCleanItem(userId, packageName, andCode)); 1628 } 1629 } 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1631 startCleaningPackages(); 1632 } break; 1633 case POST_INSTALL: { 1634 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1635 1636 PostInstallData data = mRunningInstalls.get(msg.arg1); 1637 final boolean didRestore = (msg.arg2 != 0); 1638 mRunningInstalls.delete(msg.arg1); 1639 1640 if (data != null) { 1641 InstallArgs args = data.args; 1642 PackageInstalledInfo parentRes = data.res; 1643 1644 final boolean grantPermissions = (args.installFlags 1645 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1646 final boolean killApp = (args.installFlags 1647 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1648 final String[] grantedPermissions = args.installGrantPermissions; 1649 1650 // Handle the parent package 1651 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1652 grantedPermissions, didRestore, args.installerPackageName, 1653 args.observer); 1654 1655 // Handle the child packages 1656 final int childCount = (parentRes.addedChildPackages != null) 1657 ? parentRes.addedChildPackages.size() : 0; 1658 for (int i = 0; i < childCount; i++) { 1659 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1660 handlePackagePostInstall(childRes, grantPermissions, killApp, 1661 grantedPermissions, false, args.installerPackageName, 1662 args.observer); 1663 } 1664 1665 // Log tracing if needed 1666 if (args.traceMethod != null) { 1667 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1668 args.traceCookie); 1669 } 1670 } else { 1671 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1672 } 1673 1674 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1675 } break; 1676 case UPDATED_MEDIA_STATUS: { 1677 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1678 boolean reportStatus = msg.arg1 == 1; 1679 boolean doGc = msg.arg2 == 1; 1680 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1681 if (doGc) { 1682 // Force a gc to clear up stale containers. 1683 Runtime.getRuntime().gc(); 1684 } 1685 if (msg.obj != null) { 1686 @SuppressWarnings("unchecked") 1687 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1688 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1689 // Unload containers 1690 unloadAllContainers(args); 1691 } 1692 if (reportStatus) { 1693 try { 1694 if (DEBUG_SD_INSTALL) Log.i(TAG, 1695 "Invoking StorageManagerService call back"); 1696 PackageHelper.getStorageManager().finishMediaUpdate(); 1697 } catch (RemoteException e) { 1698 Log.e(TAG, "StorageManagerService not running?"); 1699 } 1700 } 1701 } break; 1702 case WRITE_SETTINGS: { 1703 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1704 synchronized (mPackages) { 1705 removeMessages(WRITE_SETTINGS); 1706 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1707 mSettings.writeLPr(); 1708 mDirtyUsers.clear(); 1709 } 1710 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1711 } break; 1712 case WRITE_PACKAGE_RESTRICTIONS: { 1713 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1714 synchronized (mPackages) { 1715 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1716 for (int userId : mDirtyUsers) { 1717 mSettings.writePackageRestrictionsLPr(userId); 1718 } 1719 mDirtyUsers.clear(); 1720 } 1721 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1722 } break; 1723 case WRITE_PACKAGE_LIST: { 1724 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1725 synchronized (mPackages) { 1726 removeMessages(WRITE_PACKAGE_LIST); 1727 mSettings.writePackageListLPr(msg.arg1); 1728 } 1729 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1730 } break; 1731 case CHECK_PENDING_VERIFICATION: { 1732 final int verificationId = msg.arg1; 1733 final PackageVerificationState state = mPendingVerification.get(verificationId); 1734 1735 if ((state != null) && !state.timeoutExtended()) { 1736 final InstallArgs args = state.getInstallArgs(); 1737 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1738 1739 Slog.i(TAG, "Verification timed out for " + originUri); 1740 mPendingVerification.remove(verificationId); 1741 1742 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1743 1744 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1745 Slog.i(TAG, "Continuing with installation of " + originUri); 1746 state.setVerifierResponse(Binder.getCallingUid(), 1747 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1748 broadcastPackageVerified(verificationId, originUri, 1749 PackageManager.VERIFICATION_ALLOW, 1750 state.getInstallArgs().getUser()); 1751 try { 1752 ret = args.copyApk(mContainerService, true); 1753 } catch (RemoteException e) { 1754 Slog.e(TAG, "Could not contact the ContainerService"); 1755 } 1756 } else { 1757 broadcastPackageVerified(verificationId, originUri, 1758 PackageManager.VERIFICATION_REJECT, 1759 state.getInstallArgs().getUser()); 1760 } 1761 1762 Trace.asyncTraceEnd( 1763 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1764 1765 processPendingInstall(args, ret); 1766 mHandler.sendEmptyMessage(MCS_UNBIND); 1767 } 1768 break; 1769 } 1770 case PACKAGE_VERIFIED: { 1771 final int verificationId = msg.arg1; 1772 1773 final PackageVerificationState state = mPendingVerification.get(verificationId); 1774 if (state == null) { 1775 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1776 break; 1777 } 1778 1779 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1780 1781 state.setVerifierResponse(response.callerUid, response.code); 1782 1783 if (state.isVerificationComplete()) { 1784 mPendingVerification.remove(verificationId); 1785 1786 final InstallArgs args = state.getInstallArgs(); 1787 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1788 1789 int ret; 1790 if (state.isInstallAllowed()) { 1791 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1792 broadcastPackageVerified(verificationId, originUri, 1793 response.code, state.getInstallArgs().getUser()); 1794 try { 1795 ret = args.copyApk(mContainerService, true); 1796 } catch (RemoteException e) { 1797 Slog.e(TAG, "Could not contact the ContainerService"); 1798 } 1799 } else { 1800 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1801 } 1802 1803 Trace.asyncTraceEnd( 1804 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1805 1806 processPendingInstall(args, ret); 1807 mHandler.sendEmptyMessage(MCS_UNBIND); 1808 } 1809 1810 break; 1811 } 1812 case START_INTENT_FILTER_VERIFICATIONS: { 1813 IFVerificationParams params = (IFVerificationParams) msg.obj; 1814 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1815 params.replacing, params.pkg); 1816 break; 1817 } 1818 case INTENT_FILTER_VERIFIED: { 1819 final int verificationId = msg.arg1; 1820 1821 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1822 verificationId); 1823 if (state == null) { 1824 Slog.w(TAG, "Invalid IntentFilter verification token " 1825 + verificationId + " received"); 1826 break; 1827 } 1828 1829 final int userId = state.getUserId(); 1830 1831 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1832 "Processing IntentFilter verification with token:" 1833 + verificationId + " and userId:" + userId); 1834 1835 final IntentFilterVerificationResponse response = 1836 (IntentFilterVerificationResponse) msg.obj; 1837 1838 state.setVerifierResponse(response.callerUid, response.code); 1839 1840 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1841 "IntentFilter verification with token:" + verificationId 1842 + " and userId:" + userId 1843 + " is settings verifier response with response code:" 1844 + response.code); 1845 1846 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1848 + response.getFailedDomainsString()); 1849 } 1850 1851 if (state.isVerificationComplete()) { 1852 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1853 } else { 1854 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1855 "IntentFilter verification with token:" + verificationId 1856 + " was not said to be complete"); 1857 } 1858 1859 break; 1860 } 1861 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1862 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1863 mInstantAppResolverConnection, 1864 (InstantAppRequest) msg.obj, 1865 mInstantAppInstallerActivity, 1866 mHandler); 1867 } 1868 } 1869 } 1870 } 1871 1872 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1873 boolean killApp, String[] grantedPermissions, 1874 boolean launchedForRestore, String installerPackage, 1875 IPackageInstallObserver2 installObserver) { 1876 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1877 // Send the removed broadcasts 1878 if (res.removedInfo != null) { 1879 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1880 } 1881 1882 // Now that we successfully installed the package, grant runtime 1883 // permissions if requested before broadcasting the install. Also 1884 // for legacy apps in permission review mode we clear the permission 1885 // review flag which is used to emulate runtime permissions for 1886 // legacy apps. 1887 if (grantPermissions) { 1888 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1889 } 1890 1891 final boolean update = res.removedInfo != null 1892 && res.removedInfo.removedPackage != null; 1893 final String origInstallerPackageName = res.removedInfo != null 1894 ? res.removedInfo.installerPackageName : null; 1895 1896 // If this is the first time we have child packages for a disabled privileged 1897 // app that had no children, we grant requested runtime permissions to the new 1898 // children if the parent on the system image had them already granted. 1899 if (res.pkg.parentPackage != null) { 1900 synchronized (mPackages) { 1901 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1902 } 1903 } 1904 1905 synchronized (mPackages) { 1906 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1907 } 1908 1909 final String packageName = res.pkg.applicationInfo.packageName; 1910 1911 // Determine the set of users who are adding this package for 1912 // the first time vs. those who are seeing an update. 1913 int[] firstUsers = EMPTY_INT_ARRAY; 1914 int[] updateUsers = EMPTY_INT_ARRAY; 1915 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1916 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1917 for (int newUser : res.newUsers) { 1918 if (ps.getInstantApp(newUser)) { 1919 continue; 1920 } 1921 if (allNewUsers) { 1922 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1923 continue; 1924 } 1925 boolean isNew = true; 1926 for (int origUser : res.origUsers) { 1927 if (origUser == newUser) { 1928 isNew = false; 1929 break; 1930 } 1931 } 1932 if (isNew) { 1933 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1934 } else { 1935 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1936 } 1937 } 1938 1939 // Send installed broadcasts if the package is not a static shared lib. 1940 if (res.pkg.staticSharedLibName == null) { 1941 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1942 1943 // Send added for users that see the package for the first time 1944 // sendPackageAddedForNewUsers also deals with system apps 1945 int appId = UserHandle.getAppId(res.uid); 1946 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1947 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1948 1949 // Send added for users that don't see the package for the first time 1950 Bundle extras = new Bundle(1); 1951 extras.putInt(Intent.EXTRA_UID, res.uid); 1952 if (update) { 1953 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1954 } 1955 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1956 extras, 0 /*flags*/, 1957 null /*targetPackage*/, null /*finishedReceiver*/, updateUsers); 1958 if (origInstallerPackageName != null) { 1959 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1960 extras, 0 /*flags*/, 1961 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1962 } 1963 1964 // Send replaced for users that don't see the package for the first time 1965 if (update) { 1966 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1967 packageName, extras, 0 /*flags*/, 1968 null /*targetPackage*/, null /*finishedReceiver*/, 1969 updateUsers); 1970 if (origInstallerPackageName != null) { 1971 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1972 extras, 0 /*flags*/, 1973 origInstallerPackageName, null /*finishedReceiver*/, updateUsers); 1974 } 1975 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1976 null /*package*/, null /*extras*/, 0 /*flags*/, 1977 packageName /*targetPackage*/, 1978 null /*finishedReceiver*/, updateUsers); 1979 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1980 // First-install and we did a restore, so we're responsible for the 1981 // first-launch broadcast. 1982 if (DEBUG_BACKUP) { 1983 Slog.i(TAG, "Post-restore of " + packageName 1984 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1985 } 1986 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1987 } 1988 1989 // Send broadcast package appeared if forward locked/external for all users 1990 // treat asec-hosted packages like removable media on upgrade 1991 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1992 if (DEBUG_INSTALL) { 1993 Slog.i(TAG, "upgrading pkg " + res.pkg 1994 + " is ASEC-hosted -> AVAILABLE"); 1995 } 1996 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1997 ArrayList<String> pkgList = new ArrayList<>(1); 1998 pkgList.add(packageName); 1999 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2000 } 2001 } 2002 2003 // Work that needs to happen on first install within each user 2004 if (firstUsers != null && firstUsers.length > 0) { 2005 synchronized (mPackages) { 2006 for (int userId : firstUsers) { 2007 // If this app is a browser and it's newly-installed for some 2008 // users, clear any default-browser state in those users. The 2009 // app's nature doesn't depend on the user, so we can just check 2010 // its browser nature in any user and generalize. 2011 if (packageIsBrowser(packageName, userId)) { 2012 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2013 } 2014 2015 // We may also need to apply pending (restored) runtime 2016 // permission grants within these users. 2017 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2018 } 2019 } 2020 } 2021 2022 // Log current value of "unknown sources" setting 2023 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2024 getUnknownSourcesSettings()); 2025 2026 // Force a gc to clear up things 2027 Runtime.getRuntime().gc(); 2028 2029 // Remove the replaced package's older resources safely now 2030 // We delete after a gc for applications on sdcard. 2031 if (res.removedInfo != null && res.removedInfo.args != null) { 2032 synchronized (mInstallLock) { 2033 res.removedInfo.args.doPostDeleteLI(true); 2034 } 2035 } 2036 2037 // Notify DexManager that the package was installed for new users. 2038 // The updated users should already be indexed and the package code paths 2039 // should not change. 2040 // Don't notify the manager for ephemeral apps as they are not expected to 2041 // survive long enough to benefit of background optimizations. 2042 for (int userId : firstUsers) { 2043 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2044 // There's a race currently where some install events may interleave with an uninstall. 2045 // This can lead to package info being null (b/36642664). 2046 if (info != null) { 2047 mDexManager.notifyPackageInstalled(info, userId); 2048 } 2049 } 2050 } 2051 2052 // If someone is watching installs - notify them 2053 if (installObserver != null) { 2054 try { 2055 Bundle extras = extrasForInstallResult(res); 2056 installObserver.onPackageInstalled(res.name, res.returnCode, 2057 res.returnMsg, extras); 2058 } catch (RemoteException e) { 2059 Slog.i(TAG, "Observer no longer exists."); 2060 } 2061 } 2062 } 2063 2064 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 2065 PackageParser.Package pkg) { 2066 if (pkg.parentPackage == null) { 2067 return; 2068 } 2069 if (pkg.requestedPermissions == null) { 2070 return; 2071 } 2072 final PackageSetting disabledSysParentPs = mSettings 2073 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 2074 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 2075 || !disabledSysParentPs.isPrivileged() 2076 || (disabledSysParentPs.childPackageNames != null 2077 && !disabledSysParentPs.childPackageNames.isEmpty())) { 2078 return; 2079 } 2080 final int[] allUserIds = sUserManager.getUserIds(); 2081 final int permCount = pkg.requestedPermissions.size(); 2082 for (int i = 0; i < permCount; i++) { 2083 String permission = pkg.requestedPermissions.get(i); 2084 BasePermission bp = mSettings.mPermissions.get(permission); 2085 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2086 continue; 2087 } 2088 for (int userId : allUserIds) { 2089 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2090 permission, userId)) { 2091 grantRuntimePermission(pkg.packageName, permission, userId); 2092 } 2093 } 2094 } 2095 } 2096 2097 private StorageEventListener mStorageListener = new StorageEventListener() { 2098 @Override 2099 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2100 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2101 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2102 final String volumeUuid = vol.getFsUuid(); 2103 2104 // Clean up any users or apps that were removed or recreated 2105 // while this volume was missing 2106 sUserManager.reconcileUsers(volumeUuid); 2107 reconcileApps(volumeUuid); 2108 2109 // Clean up any install sessions that expired or were 2110 // cancelled while this volume was missing 2111 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2112 2113 loadPrivatePackages(vol); 2114 2115 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2116 unloadPrivatePackages(vol); 2117 } 2118 } 2119 2120 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2121 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2122 updateExternalMediaStatus(true, false); 2123 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2124 updateExternalMediaStatus(false, false); 2125 } 2126 } 2127 } 2128 2129 @Override 2130 public void onVolumeForgotten(String fsUuid) { 2131 if (TextUtils.isEmpty(fsUuid)) { 2132 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2133 return; 2134 } 2135 2136 // Remove any apps installed on the forgotten volume 2137 synchronized (mPackages) { 2138 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2139 for (PackageSetting ps : packages) { 2140 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2141 deletePackageVersioned(new VersionedPackage(ps.name, 2142 PackageManager.VERSION_CODE_HIGHEST), 2143 new LegacyPackageDeleteObserver(null).getBinder(), 2144 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2145 // Try very hard to release any references to this package 2146 // so we don't risk the system server being killed due to 2147 // open FDs 2148 AttributeCache.instance().removePackage(ps.name); 2149 } 2150 2151 mSettings.onVolumeForgotten(fsUuid); 2152 mSettings.writeLPr(); 2153 } 2154 } 2155 }; 2156 2157 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2158 String[] grantedPermissions) { 2159 for (int userId : userIds) { 2160 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2161 } 2162 } 2163 2164 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2165 String[] grantedPermissions) { 2166 SettingBase sb = (SettingBase) pkg.mExtras; 2167 if (sb == null) { 2168 return; 2169 } 2170 2171 PermissionsState permissionsState = sb.getPermissionsState(); 2172 2173 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2174 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2175 2176 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2177 >= Build.VERSION_CODES.M; 2178 2179 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2180 2181 for (String permission : pkg.requestedPermissions) { 2182 final BasePermission bp; 2183 synchronized (mPackages) { 2184 bp = mSettings.mPermissions.get(permission); 2185 } 2186 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2187 && (!instantApp || bp.isInstant()) 2188 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2189 && (grantedPermissions == null 2190 || ArrayUtils.contains(grantedPermissions, permission))) { 2191 final int flags = permissionsState.getPermissionFlags(permission, userId); 2192 if (supportsRuntimePermissions) { 2193 // Installer cannot change immutable permissions. 2194 if ((flags & immutableFlags) == 0) { 2195 grantRuntimePermission(pkg.packageName, permission, userId); 2196 } 2197 } else if (mPermissionReviewRequired) { 2198 // In permission review mode we clear the review flag when we 2199 // are asked to install the app with all permissions granted. 2200 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2201 updatePermissionFlags(permission, pkg.packageName, 2202 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2203 } 2204 } 2205 } 2206 } 2207 } 2208 2209 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2210 Bundle extras = null; 2211 switch (res.returnCode) { 2212 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2213 extras = new Bundle(); 2214 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2215 res.origPermission); 2216 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2217 res.origPackage); 2218 break; 2219 } 2220 case PackageManager.INSTALL_SUCCEEDED: { 2221 extras = new Bundle(); 2222 extras.putBoolean(Intent.EXTRA_REPLACING, 2223 res.removedInfo != null && res.removedInfo.removedPackage != null); 2224 break; 2225 } 2226 } 2227 return extras; 2228 } 2229 2230 void scheduleWriteSettingsLocked() { 2231 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2232 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2233 } 2234 } 2235 2236 void scheduleWritePackageListLocked(int userId) { 2237 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2238 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2239 msg.arg1 = userId; 2240 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2241 } 2242 } 2243 2244 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2245 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2246 scheduleWritePackageRestrictionsLocked(userId); 2247 } 2248 2249 void scheduleWritePackageRestrictionsLocked(int userId) { 2250 final int[] userIds = (userId == UserHandle.USER_ALL) 2251 ? sUserManager.getUserIds() : new int[]{userId}; 2252 for (int nextUserId : userIds) { 2253 if (!sUserManager.exists(nextUserId)) return; 2254 mDirtyUsers.add(nextUserId); 2255 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2256 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2257 } 2258 } 2259 } 2260 2261 public static PackageManagerService main(Context context, Installer installer, 2262 boolean factoryTest, boolean onlyCore) { 2263 // Self-check for initial settings. 2264 PackageManagerServiceCompilerMapping.checkProperties(); 2265 2266 PackageManagerService m = new PackageManagerService(context, installer, 2267 factoryTest, onlyCore); 2268 m.enableSystemUserPackages(); 2269 ServiceManager.addService("package", m); 2270 return m; 2271 } 2272 2273 private void enableSystemUserPackages() { 2274 if (!UserManager.isSplitSystemUser()) { 2275 return; 2276 } 2277 // For system user, enable apps based on the following conditions: 2278 // - app is whitelisted or belong to one of these groups: 2279 // -- system app which has no launcher icons 2280 // -- system app which has INTERACT_ACROSS_USERS permission 2281 // -- system IME app 2282 // - app is not in the blacklist 2283 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2284 Set<String> enableApps = new ArraySet<>(); 2285 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2286 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2287 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2288 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2289 enableApps.addAll(wlApps); 2290 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2291 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2292 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2293 enableApps.removeAll(blApps); 2294 Log.i(TAG, "Applications installed for system user: " + enableApps); 2295 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2296 UserHandle.SYSTEM); 2297 final int allAppsSize = allAps.size(); 2298 synchronized (mPackages) { 2299 for (int i = 0; i < allAppsSize; i++) { 2300 String pName = allAps.get(i); 2301 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2302 // Should not happen, but we shouldn't be failing if it does 2303 if (pkgSetting == null) { 2304 continue; 2305 } 2306 boolean install = enableApps.contains(pName); 2307 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2308 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2309 + " for system user"); 2310 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2311 } 2312 } 2313 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2314 } 2315 } 2316 2317 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2318 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2319 Context.DISPLAY_SERVICE); 2320 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2321 } 2322 2323 /** 2324 * Requests that files preopted on a secondary system partition be copied to the data partition 2325 * if possible. Note that the actual copying of the files is accomplished by init for security 2326 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2327 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2328 */ 2329 private static void requestCopyPreoptedFiles() { 2330 final int WAIT_TIME_MS = 100; 2331 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2332 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2333 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2334 // We will wait for up to 100 seconds. 2335 final long timeStart = SystemClock.uptimeMillis(); 2336 final long timeEnd = timeStart + 100 * 1000; 2337 long timeNow = timeStart; 2338 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2339 try { 2340 Thread.sleep(WAIT_TIME_MS); 2341 } catch (InterruptedException e) { 2342 // Do nothing 2343 } 2344 timeNow = SystemClock.uptimeMillis(); 2345 if (timeNow > timeEnd) { 2346 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2347 Slog.wtf(TAG, "cppreopt did not finish!"); 2348 break; 2349 } 2350 } 2351 2352 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2353 } 2354 } 2355 2356 public PackageManagerService(Context context, Installer installer, 2357 boolean factoryTest, boolean onlyCore) { 2358 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2360 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2361 SystemClock.uptimeMillis()); 2362 2363 if (mSdkVersion <= 0) { 2364 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2365 } 2366 2367 mContext = context; 2368 2369 mPermissionReviewRequired = context.getResources().getBoolean( 2370 R.bool.config_permissionReviewRequired); 2371 2372 mFactoryTest = factoryTest; 2373 mOnlyCore = onlyCore; 2374 mMetrics = new DisplayMetrics(); 2375 mSettings = new Settings(mPackages); 2376 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2377 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2378 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2379 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2380 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2381 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2382 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2383 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2384 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2385 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2386 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2387 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2388 2389 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2390 if (separateProcesses != null && separateProcesses.length() > 0) { 2391 if ("*".equals(separateProcesses)) { 2392 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2393 mSeparateProcesses = null; 2394 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2395 } else { 2396 mDefParseFlags = 0; 2397 mSeparateProcesses = separateProcesses.split(","); 2398 Slog.w(TAG, "Running with debug.separate_processes: " 2399 + separateProcesses); 2400 } 2401 } else { 2402 mDefParseFlags = 0; 2403 mSeparateProcesses = null; 2404 } 2405 2406 mInstaller = installer; 2407 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2408 "*dexopt*"); 2409 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2410 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2411 2412 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2413 FgThread.get().getLooper()); 2414 2415 getDefaultDisplayMetrics(context, mMetrics); 2416 2417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2418 SystemConfig systemConfig = SystemConfig.getInstance(); 2419 mGlobalGids = systemConfig.getGlobalGids(); 2420 mSystemPermissions = systemConfig.getSystemPermissions(); 2421 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2422 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2423 2424 mProtectedPackages = new ProtectedPackages(mContext); 2425 2426 synchronized (mInstallLock) { 2427 // writer 2428 synchronized (mPackages) { 2429 mHandlerThread = new ServiceThread(TAG, 2430 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2431 mHandlerThread.start(); 2432 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2433 mProcessLoggingHandler = new ProcessLoggingHandler(); 2434 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2435 2436 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2437 mInstantAppRegistry = new InstantAppRegistry(this); 2438 2439 File dataDir = Environment.getDataDirectory(); 2440 mAppInstallDir = new File(dataDir, "app"); 2441 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2442 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2443 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2444 sUserManager = new UserManagerService(context, this, 2445 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2446 2447 // Propagate permission configuration in to package manager. 2448 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2449 = systemConfig.getPermissions(); 2450 for (int i=0; i<permConfig.size(); i++) { 2451 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2452 BasePermission bp = mSettings.mPermissions.get(perm.name); 2453 if (bp == null) { 2454 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2455 mSettings.mPermissions.put(perm.name, bp); 2456 } 2457 if (perm.gids != null) { 2458 bp.setGids(perm.gids, perm.perUser); 2459 } 2460 } 2461 2462 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2463 final int builtInLibCount = libConfig.size(); 2464 for (int i = 0; i < builtInLibCount; i++) { 2465 String name = libConfig.keyAt(i); 2466 String path = libConfig.valueAt(i); 2467 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2468 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2469 } 2470 2471 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2472 2473 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2474 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2475 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2476 2477 // Clean up orphaned packages for which the code path doesn't exist 2478 // and they are an update to a system app - caused by bug/32321269 2479 final int packageSettingCount = mSettings.mPackages.size(); 2480 for (int i = packageSettingCount - 1; i >= 0; i--) { 2481 PackageSetting ps = mSettings.mPackages.valueAt(i); 2482 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2483 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2484 mSettings.mPackages.removeAt(i); 2485 mSettings.enableSystemPackageLPw(ps.name); 2486 } 2487 } 2488 2489 if (mFirstBoot) { 2490 requestCopyPreoptedFiles(); 2491 } 2492 2493 String customResolverActivity = Resources.getSystem().getString( 2494 R.string.config_customResolverActivity); 2495 if (TextUtils.isEmpty(customResolverActivity)) { 2496 customResolverActivity = null; 2497 } else { 2498 mCustomResolverComponentName = ComponentName.unflattenFromString( 2499 customResolverActivity); 2500 } 2501 2502 long startTime = SystemClock.uptimeMillis(); 2503 2504 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2505 startTime); 2506 2507 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2508 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2509 2510 if (bootClassPath == null) { 2511 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2512 } 2513 2514 if (systemServerClassPath == null) { 2515 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2516 } 2517 2518 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2519 2520 final VersionInfo ver = mSettings.getInternalVersion(); 2521 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2522 if (mIsUpgrade) { 2523 logCriticalInfo(Log.INFO, 2524 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2525 } 2526 2527 // when upgrading from pre-M, promote system app permissions from install to runtime 2528 mPromoteSystemApps = 2529 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2530 2531 // When upgrading from pre-N, we need to handle package extraction like first boot, 2532 // as there is no profiling data available. 2533 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2534 2535 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2536 2537 // save off the names of pre-existing system packages prior to scanning; we don't 2538 // want to automatically grant runtime permissions for new system apps 2539 if (mPromoteSystemApps) { 2540 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2541 while (pkgSettingIter.hasNext()) { 2542 PackageSetting ps = pkgSettingIter.next(); 2543 if (isSystemApp(ps)) { 2544 mExistingSystemPackages.add(ps.name); 2545 } 2546 } 2547 } 2548 2549 mCacheDir = preparePackageParserCache(mIsUpgrade); 2550 2551 // Set flag to monitor and not change apk file paths when 2552 // scanning install directories. 2553 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2554 2555 if (mIsUpgrade || mFirstBoot) { 2556 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2557 } 2558 2559 // Collect vendor overlay packages. (Do this before scanning any apps.) 2560 // For security and version matching reason, only consider 2561 // overlay packages if they reside in the right directory. 2562 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2563 | PackageParser.PARSE_IS_SYSTEM 2564 | PackageParser.PARSE_IS_SYSTEM_DIR 2565 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2566 2567 mParallelPackageParserCallback.findStaticOverlayPackages(); 2568 2569 // Find base frameworks (resource packages without code). 2570 scanDirTracedLI(frameworkDir, mDefParseFlags 2571 | PackageParser.PARSE_IS_SYSTEM 2572 | PackageParser.PARSE_IS_SYSTEM_DIR 2573 | PackageParser.PARSE_IS_PRIVILEGED, 2574 scanFlags | SCAN_NO_DEX, 0); 2575 2576 // Collected privileged system packages. 2577 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2578 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2579 | PackageParser.PARSE_IS_SYSTEM 2580 | PackageParser.PARSE_IS_SYSTEM_DIR 2581 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2582 2583 // Collect ordinary system packages. 2584 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2585 scanDirTracedLI(systemAppDir, mDefParseFlags 2586 | PackageParser.PARSE_IS_SYSTEM 2587 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2588 2589 // Collect all vendor packages. 2590 File vendorAppDir = new File("/vendor/app"); 2591 try { 2592 vendorAppDir = vendorAppDir.getCanonicalFile(); 2593 } catch (IOException e) { 2594 // failed to look up canonical path, continue with original one 2595 } 2596 scanDirTracedLI(vendorAppDir, mDefParseFlags 2597 | PackageParser.PARSE_IS_SYSTEM 2598 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2599 2600 // Collect all OEM packages. 2601 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2602 scanDirTracedLI(oemAppDir, mDefParseFlags 2603 | PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2605 2606 // Prune any system packages that no longer exist. 2607 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2608 if (!mOnlyCore) { 2609 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2610 while (psit.hasNext()) { 2611 PackageSetting ps = psit.next(); 2612 2613 /* 2614 * If this is not a system app, it can't be a 2615 * disable system app. 2616 */ 2617 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2618 continue; 2619 } 2620 2621 /* 2622 * If the package is scanned, it's not erased. 2623 */ 2624 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2625 if (scannedPkg != null) { 2626 /* 2627 * If the system app is both scanned and in the 2628 * disabled packages list, then it must have been 2629 * added via OTA. Remove it from the currently 2630 * scanned package so the previously user-installed 2631 * application can be scanned. 2632 */ 2633 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2634 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2635 + ps.name + "; removing system app. Last known codePath=" 2636 + ps.codePathString + ", installStatus=" + ps.installStatus 2637 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2638 + scannedPkg.mVersionCode); 2639 removePackageLI(scannedPkg, true); 2640 mExpectingBetter.put(ps.name, ps.codePath); 2641 } 2642 2643 continue; 2644 } 2645 2646 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2647 psit.remove(); 2648 logCriticalInfo(Log.WARN, "System package " + ps.name 2649 + " no longer exists; it's data will be wiped"); 2650 // Actual deletion of code and data will be handled by later 2651 // reconciliation step 2652 } else { 2653 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2654 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2655 possiblyDeletedUpdatedSystemApps.add(ps.name); 2656 } 2657 } 2658 } 2659 } 2660 2661 //look for any incomplete package installations 2662 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2663 for (int i = 0; i < deletePkgsList.size(); i++) { 2664 // Actual deletion of code and data will be handled by later 2665 // reconciliation step 2666 final String packageName = deletePkgsList.get(i).name; 2667 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2668 synchronized (mPackages) { 2669 mSettings.removePackageLPw(packageName); 2670 } 2671 } 2672 2673 //delete tmp files 2674 deleteTempPackageFiles(); 2675 2676 // Remove any shared userIDs that have no associated packages 2677 mSettings.pruneSharedUsersLPw(); 2678 2679 if (!mOnlyCore) { 2680 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2681 SystemClock.uptimeMillis()); 2682 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2683 2684 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2685 | PackageParser.PARSE_FORWARD_LOCK, 2686 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2687 2688 /** 2689 * Remove disable package settings for any updated system 2690 * apps that were removed via an OTA. If they're not a 2691 * previously-updated app, remove them completely. 2692 * Otherwise, just revoke their system-level permissions. 2693 */ 2694 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2695 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2696 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2697 2698 String msg; 2699 if (deletedPkg == null) { 2700 msg = "Updated system package " + deletedAppName 2701 + " no longer exists; it's data will be wiped"; 2702 // Actual deletion of code and data will be handled by later 2703 // reconciliation step 2704 } else { 2705 msg = "Updated system app + " + deletedAppName 2706 + " no longer present; removing system privileges for " 2707 + deletedAppName; 2708 2709 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2710 2711 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2712 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2713 } 2714 logCriticalInfo(Log.WARN, msg); 2715 } 2716 2717 /** 2718 * Make sure all system apps that we expected to appear on 2719 * the userdata partition actually showed up. If they never 2720 * appeared, crawl back and revive the system version. 2721 */ 2722 for (int i = 0; i < mExpectingBetter.size(); i++) { 2723 final String packageName = mExpectingBetter.keyAt(i); 2724 if (!mPackages.containsKey(packageName)) { 2725 final File scanFile = mExpectingBetter.valueAt(i); 2726 2727 logCriticalInfo(Log.WARN, "Expected better " + packageName 2728 + " but never showed up; reverting to system"); 2729 2730 int reparseFlags = mDefParseFlags; 2731 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2732 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2733 | PackageParser.PARSE_IS_SYSTEM_DIR 2734 | PackageParser.PARSE_IS_PRIVILEGED; 2735 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2736 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2737 | PackageParser.PARSE_IS_SYSTEM_DIR; 2738 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2739 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2740 | PackageParser.PARSE_IS_SYSTEM_DIR; 2741 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2742 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2743 | PackageParser.PARSE_IS_SYSTEM_DIR; 2744 } else { 2745 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2746 continue; 2747 } 2748 2749 mSettings.enableSystemPackageLPw(packageName); 2750 2751 try { 2752 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2753 } catch (PackageManagerException e) { 2754 Slog.e(TAG, "Failed to parse original system package: " 2755 + e.getMessage()); 2756 } 2757 } 2758 } 2759 } 2760 mExpectingBetter.clear(); 2761 2762 // Resolve the storage manager. 2763 mStorageManagerPackage = getStorageManagerPackageName(); 2764 2765 // Resolve protected action filters. Only the setup wizard is allowed to 2766 // have a high priority filter for these actions. 2767 mSetupWizardPackage = getSetupWizardPackageName(); 2768 if (mProtectedFilters.size() > 0) { 2769 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2770 Slog.i(TAG, "No setup wizard;" 2771 + " All protected intents capped to priority 0"); 2772 } 2773 for (ActivityIntentInfo filter : mProtectedFilters) { 2774 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2775 if (DEBUG_FILTERS) { 2776 Slog.i(TAG, "Found setup wizard;" 2777 + " allow priority " + filter.getPriority() + ";" 2778 + " package: " + filter.activity.info.packageName 2779 + " activity: " + filter.activity.className 2780 + " priority: " + filter.getPriority()); 2781 } 2782 // skip setup wizard; allow it to keep the high priority filter 2783 continue; 2784 } 2785 Slog.w(TAG, "Protected action; cap priority to 0;" 2786 + " package: " + filter.activity.info.packageName 2787 + " activity: " + filter.activity.className 2788 + " origPrio: " + filter.getPriority()); 2789 filter.setPriority(0); 2790 } 2791 } 2792 mDeferProtectedFilters = false; 2793 mProtectedFilters.clear(); 2794 2795 // Now that we know all of the shared libraries, update all clients to have 2796 // the correct library paths. 2797 updateAllSharedLibrariesLPw(null); 2798 2799 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2800 // NOTE: We ignore potential failures here during a system scan (like 2801 // the rest of the commands above) because there's precious little we 2802 // can do about it. A settings error is reported, though. 2803 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2804 } 2805 2806 // Now that we know all the packages we are keeping, 2807 // read and update their last usage times. 2808 mPackageUsage.read(mPackages); 2809 mCompilerStats.read(); 2810 2811 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2812 SystemClock.uptimeMillis()); 2813 Slog.i(TAG, "Time to scan packages: " 2814 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2815 + " seconds"); 2816 2817 // If the platform SDK has changed since the last time we booted, 2818 // we need to re-grant app permission to catch any new ones that 2819 // appear. This is really a hack, and means that apps can in some 2820 // cases get permissions that the user didn't initially explicitly 2821 // allow... it would be nice to have some better way to handle 2822 // this situation. 2823 int updateFlags = UPDATE_PERMISSIONS_ALL; 2824 if (ver.sdkVersion != mSdkVersion) { 2825 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2826 + mSdkVersion + "; regranting permissions for internal storage"); 2827 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2828 } 2829 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2830 ver.sdkVersion = mSdkVersion; 2831 2832 // If this is the first boot or an update from pre-M, and it is a normal 2833 // boot, then we need to initialize the default preferred apps across 2834 // all defined users. 2835 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2836 for (UserInfo user : sUserManager.getUsers(true)) { 2837 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2838 applyFactoryDefaultBrowserLPw(user.id); 2839 primeDomainVerificationsLPw(user.id); 2840 } 2841 } 2842 2843 // Prepare storage for system user really early during boot, 2844 // since core system apps like SettingsProvider and SystemUI 2845 // can't wait for user to start 2846 final int storageFlags; 2847 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2848 storageFlags = StorageManager.FLAG_STORAGE_DE; 2849 } else { 2850 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2851 } 2852 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2853 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2854 true /* onlyCoreApps */); 2855 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2856 BootTimingsTraceLog traceLog = new BootTimingsTraceLog("SystemServerTimingAsync", 2857 Trace.TRACE_TAG_PACKAGE_MANAGER); 2858 traceLog.traceBegin("AppDataFixup"); 2859 try { 2860 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2861 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2862 } catch (InstallerException e) { 2863 Slog.w(TAG, "Trouble fixing GIDs", e); 2864 } 2865 traceLog.traceEnd(); 2866 2867 traceLog.traceBegin("AppDataPrepare"); 2868 if (deferPackages == null || deferPackages.isEmpty()) { 2869 return; 2870 } 2871 int count = 0; 2872 for (String pkgName : deferPackages) { 2873 PackageParser.Package pkg = null; 2874 synchronized (mPackages) { 2875 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2876 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2877 pkg = ps.pkg; 2878 } 2879 } 2880 if (pkg != null) { 2881 synchronized (mInstallLock) { 2882 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2883 true /* maybeMigrateAppData */); 2884 } 2885 count++; 2886 } 2887 } 2888 traceLog.traceEnd(); 2889 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2890 }, "prepareAppData"); 2891 2892 // If this is first boot after an OTA, and a normal boot, then 2893 // we need to clear code cache directories. 2894 // Note that we do *not* clear the application profiles. These remain valid 2895 // across OTAs and are used to drive profile verification (post OTA) and 2896 // profile compilation (without waiting to collect a fresh set of profiles). 2897 if (mIsUpgrade && !onlyCore) { 2898 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2899 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2900 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2901 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2902 // No apps are running this early, so no need to freeze 2903 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2904 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2905 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2906 } 2907 } 2908 ver.fingerprint = Build.FINGERPRINT; 2909 } 2910 2911 checkDefaultBrowser(); 2912 2913 // clear only after permissions and other defaults have been updated 2914 mExistingSystemPackages.clear(); 2915 mPromoteSystemApps = false; 2916 2917 // All the changes are done during package scanning. 2918 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2919 2920 // can downgrade to reader 2921 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2922 mSettings.writeLPr(); 2923 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2924 2925 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2926 SystemClock.uptimeMillis()); 2927 2928 if (!mOnlyCore) { 2929 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2930 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2931 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2932 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2933 if (mIntentFilterVerifierComponent != null) { 2934 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2935 mIntentFilterVerifierComponent); 2936 } else { 2937 mIntentFilterVerifier = null; 2938 } 2939 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2940 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2941 SharedLibraryInfo.VERSION_UNDEFINED); 2942 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2943 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2944 SharedLibraryInfo.VERSION_UNDEFINED); 2945 } else { 2946 mRequiredVerifierPackage = null; 2947 mRequiredInstallerPackage = null; 2948 mRequiredUninstallerPackage = null; 2949 mIntentFilterVerifierComponent = null; 2950 mIntentFilterVerifier = null; 2951 mServicesSystemSharedLibraryPackageName = null; 2952 mSharedSystemSharedLibraryPackageName = null; 2953 } 2954 2955 mInstallerService = new PackageInstallerService(context, this); 2956 final Pair<ComponentName, String> instantAppResolverComponent = 2957 getInstantAppResolverLPr(); 2958 if (instantAppResolverComponent != null) { 2959 if (DEBUG_EPHEMERAL) { 2960 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2961 } 2962 mInstantAppResolverConnection = new EphemeralResolverConnection( 2963 mContext, instantAppResolverComponent.first, 2964 instantAppResolverComponent.second); 2965 mInstantAppResolverSettingsComponent = 2966 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2967 } else { 2968 mInstantAppResolverConnection = null; 2969 mInstantAppResolverSettingsComponent = null; 2970 } 2971 updateInstantAppInstallerLocked(null); 2972 2973 // Read and update the usage of dex files. 2974 // Do this at the end of PM init so that all the packages have their 2975 // data directory reconciled. 2976 // At this point we know the code paths of the packages, so we can validate 2977 // the disk file and build the internal cache. 2978 // The usage file is expected to be small so loading and verifying it 2979 // should take a fairly small time compare to the other activities (e.g. package 2980 // scanning). 2981 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2982 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2983 for (int userId : currentUserIds) { 2984 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2985 } 2986 mDexManager.load(userPackages); 2987 } // synchronized (mPackages) 2988 } // synchronized (mInstallLock) 2989 2990 // Now after opening every single application zip, make sure they 2991 // are all flushed. Not really needed, but keeps things nice and 2992 // tidy. 2993 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2994 Runtime.getRuntime().gc(); 2995 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2996 2997 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2998 FallbackCategoryProvider.loadFallbacks(); 2999 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3000 3001 // The initial scanning above does many calls into installd while 3002 // holding the mPackages lock, but we're mostly interested in yelling 3003 // once we have a booted system. 3004 mInstaller.setWarnIfHeld(mPackages); 3005 3006 // Expose private service for system components to use. 3007 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 3008 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3009 } 3010 3011 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3012 // we're only interested in updating the installer appliction when 1) it's not 3013 // already set or 2) the modified package is the installer 3014 if (mInstantAppInstallerActivity != null 3015 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3016 .equals(modifiedPackage)) { 3017 return; 3018 } 3019 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3020 } 3021 3022 private static File preparePackageParserCache(boolean isUpgrade) { 3023 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3024 return null; 3025 } 3026 3027 // Disable package parsing on eng builds to allow for faster incremental development. 3028 if ("eng".equals(Build.TYPE)) { 3029 return null; 3030 } 3031 3032 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3033 Slog.i(TAG, "Disabling package parser cache due to system property."); 3034 return null; 3035 } 3036 3037 // The base directory for the package parser cache lives under /data/system/. 3038 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3039 "package_cache"); 3040 if (cacheBaseDir == null) { 3041 return null; 3042 } 3043 3044 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3045 // This also serves to "GC" unused entries when the package cache version changes (which 3046 // can only happen during upgrades). 3047 if (isUpgrade) { 3048 FileUtils.deleteContents(cacheBaseDir); 3049 } 3050 3051 3052 // Return the versioned package cache directory. This is something like 3053 // "/data/system/package_cache/1" 3054 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3055 3056 // The following is a workaround to aid development on non-numbered userdebug 3057 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3058 // the system partition is newer. 3059 // 3060 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3061 // that starts with "eng." to signify that this is an engineering build and not 3062 // destined for release. 3063 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3064 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3065 3066 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3067 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3068 // in general and should not be used for production changes. In this specific case, 3069 // we know that they will work. 3070 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3071 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3072 FileUtils.deleteContents(cacheBaseDir); 3073 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3074 } 3075 } 3076 3077 return cacheDir; 3078 } 3079 3080 @Override 3081 public boolean isFirstBoot() { 3082 return mFirstBoot; 3083 } 3084 3085 @Override 3086 public boolean isOnlyCoreApps() { 3087 return mOnlyCore; 3088 } 3089 3090 @Override 3091 public boolean isUpgrade() { 3092 return mIsUpgrade; 3093 } 3094 3095 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3096 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3097 3098 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3099 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3100 UserHandle.USER_SYSTEM); 3101 if (matches.size() == 1) { 3102 return matches.get(0).getComponentInfo().packageName; 3103 } else if (matches.size() == 0) { 3104 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3105 return null; 3106 } 3107 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3108 } 3109 3110 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3111 synchronized (mPackages) { 3112 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3113 if (libraryEntry == null) { 3114 throw new IllegalStateException("Missing required shared library:" + name); 3115 } 3116 return libraryEntry.apk; 3117 } 3118 } 3119 3120 private @NonNull String getRequiredInstallerLPr() { 3121 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3122 intent.addCategory(Intent.CATEGORY_DEFAULT); 3123 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3124 3125 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3126 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3127 UserHandle.USER_SYSTEM); 3128 if (matches.size() == 1) { 3129 ResolveInfo resolveInfo = matches.get(0); 3130 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3131 throw new RuntimeException("The installer must be a privileged app"); 3132 } 3133 return matches.get(0).getComponentInfo().packageName; 3134 } else { 3135 throw new RuntimeException("There must be exactly one installer; found " + matches); 3136 } 3137 } 3138 3139 private @NonNull String getRequiredUninstallerLPr() { 3140 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3141 intent.addCategory(Intent.CATEGORY_DEFAULT); 3142 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3143 3144 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3145 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3146 UserHandle.USER_SYSTEM); 3147 if (resolveInfo == null || 3148 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3149 throw new RuntimeException("There must be exactly one uninstaller; found " 3150 + resolveInfo); 3151 } 3152 return resolveInfo.getComponentInfo().packageName; 3153 } 3154 3155 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3156 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3157 3158 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3159 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3160 UserHandle.USER_SYSTEM); 3161 ResolveInfo best = null; 3162 final int N = matches.size(); 3163 for (int i = 0; i < N; i++) { 3164 final ResolveInfo cur = matches.get(i); 3165 final String packageName = cur.getComponentInfo().packageName; 3166 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3167 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3168 continue; 3169 } 3170 3171 if (best == null || cur.priority > best.priority) { 3172 best = cur; 3173 } 3174 } 3175 3176 if (best != null) { 3177 return best.getComponentInfo().getComponentName(); 3178 } 3179 Slog.w(TAG, "Intent filter verifier not found"); 3180 return null; 3181 } 3182 3183 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3184 final String[] packageArray = 3185 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3186 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3187 if (DEBUG_EPHEMERAL) { 3188 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3189 } 3190 return null; 3191 } 3192 3193 final int callingUid = Binder.getCallingUid(); 3194 final int resolveFlags = 3195 MATCH_DIRECT_BOOT_AWARE 3196 | MATCH_DIRECT_BOOT_UNAWARE 3197 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3198 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3199 final Intent resolverIntent = new Intent(actionName); 3200 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3201 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3202 // temporarily look for the old action 3203 if (resolvers.size() == 0) { 3204 if (DEBUG_EPHEMERAL) { 3205 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3206 } 3207 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3208 resolverIntent.setAction(actionName); 3209 resolvers = queryIntentServicesInternal(resolverIntent, null, 3210 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3211 } 3212 final int N = resolvers.size(); 3213 if (N == 0) { 3214 if (DEBUG_EPHEMERAL) { 3215 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3216 } 3217 return null; 3218 } 3219 3220 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3221 for (int i = 0; i < N; i++) { 3222 final ResolveInfo info = resolvers.get(i); 3223 3224 if (info.serviceInfo == null) { 3225 continue; 3226 } 3227 3228 final String packageName = info.serviceInfo.packageName; 3229 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3230 if (DEBUG_EPHEMERAL) { 3231 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3232 + " pkg: " + packageName + ", info:" + info); 3233 } 3234 continue; 3235 } 3236 3237 if (DEBUG_EPHEMERAL) { 3238 Slog.v(TAG, "Ephemeral resolver found;" 3239 + " pkg: " + packageName + ", info:" + info); 3240 } 3241 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3242 } 3243 if (DEBUG_EPHEMERAL) { 3244 Slog.v(TAG, "Ephemeral resolver NOT found"); 3245 } 3246 return null; 3247 } 3248 3249 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3250 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3251 intent.addCategory(Intent.CATEGORY_DEFAULT); 3252 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3253 3254 final int resolveFlags = 3255 MATCH_DIRECT_BOOT_AWARE 3256 | MATCH_DIRECT_BOOT_UNAWARE 3257 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3258 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3259 resolveFlags, UserHandle.USER_SYSTEM); 3260 // temporarily look for the old action 3261 if (matches.isEmpty()) { 3262 if (DEBUG_EPHEMERAL) { 3263 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3264 } 3265 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3266 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3267 resolveFlags, UserHandle.USER_SYSTEM); 3268 } 3269 Iterator<ResolveInfo> iter = matches.iterator(); 3270 while (iter.hasNext()) { 3271 final ResolveInfo rInfo = iter.next(); 3272 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3273 if (ps != null) { 3274 final PermissionsState permissionsState = ps.getPermissionsState(); 3275 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3276 continue; 3277 } 3278 } 3279 iter.remove(); 3280 } 3281 if (matches.size() == 0) { 3282 return null; 3283 } else if (matches.size() == 1) { 3284 return (ActivityInfo) matches.get(0).getComponentInfo(); 3285 } else { 3286 throw new RuntimeException( 3287 "There must be at most one ephemeral installer; found " + matches); 3288 } 3289 } 3290 3291 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3292 @NonNull ComponentName resolver) { 3293 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3294 .addCategory(Intent.CATEGORY_DEFAULT) 3295 .setPackage(resolver.getPackageName()); 3296 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3297 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3298 UserHandle.USER_SYSTEM); 3299 // temporarily look for the old action 3300 if (matches.isEmpty()) { 3301 if (DEBUG_EPHEMERAL) { 3302 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3303 } 3304 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3305 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3306 UserHandle.USER_SYSTEM); 3307 } 3308 if (matches.isEmpty()) { 3309 return null; 3310 } 3311 return matches.get(0).getComponentInfo().getComponentName(); 3312 } 3313 3314 private void primeDomainVerificationsLPw(int userId) { 3315 if (DEBUG_DOMAIN_VERIFICATION) { 3316 Slog.d(TAG, "Priming domain verifications in user " + userId); 3317 } 3318 3319 SystemConfig systemConfig = SystemConfig.getInstance(); 3320 ArraySet<String> packages = systemConfig.getLinkedApps(); 3321 3322 for (String packageName : packages) { 3323 PackageParser.Package pkg = mPackages.get(packageName); 3324 if (pkg != null) { 3325 if (!pkg.isSystemApp()) { 3326 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3327 continue; 3328 } 3329 3330 ArraySet<String> domains = null; 3331 for (PackageParser.Activity a : pkg.activities) { 3332 for (ActivityIntentInfo filter : a.intents) { 3333 if (hasValidDomains(filter)) { 3334 if (domains == null) { 3335 domains = new ArraySet<String>(); 3336 } 3337 domains.addAll(filter.getHostsList()); 3338 } 3339 } 3340 } 3341 3342 if (domains != null && domains.size() > 0) { 3343 if (DEBUG_DOMAIN_VERIFICATION) { 3344 Slog.v(TAG, " + " + packageName); 3345 } 3346 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3347 // state w.r.t. the formal app-linkage "no verification attempted" state; 3348 // and then 'always' in the per-user state actually used for intent resolution. 3349 final IntentFilterVerificationInfo ivi; 3350 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3351 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3352 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3353 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3354 } else { 3355 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3356 + "' does not handle web links"); 3357 } 3358 } else { 3359 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3360 } 3361 } 3362 3363 scheduleWritePackageRestrictionsLocked(userId); 3364 scheduleWriteSettingsLocked(); 3365 } 3366 3367 private void applyFactoryDefaultBrowserLPw(int userId) { 3368 // The default browser app's package name is stored in a string resource, 3369 // with a product-specific overlay used for vendor customization. 3370 String browserPkg = mContext.getResources().getString( 3371 com.android.internal.R.string.default_browser); 3372 if (!TextUtils.isEmpty(browserPkg)) { 3373 // non-empty string => required to be a known package 3374 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3375 if (ps == null) { 3376 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3377 browserPkg = null; 3378 } else { 3379 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3380 } 3381 } 3382 3383 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3384 // default. If there's more than one, just leave everything alone. 3385 if (browserPkg == null) { 3386 calculateDefaultBrowserLPw(userId); 3387 } 3388 } 3389 3390 private void calculateDefaultBrowserLPw(int userId) { 3391 List<String> allBrowsers = resolveAllBrowserApps(userId); 3392 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3393 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3394 } 3395 3396 private List<String> resolveAllBrowserApps(int userId) { 3397 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3398 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3399 PackageManager.MATCH_ALL, userId); 3400 3401 final int count = list.size(); 3402 List<String> result = new ArrayList<String>(count); 3403 for (int i=0; i<count; i++) { 3404 ResolveInfo info = list.get(i); 3405 if (info.activityInfo == null 3406 || !info.handleAllWebDataURI 3407 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3408 || result.contains(info.activityInfo.packageName)) { 3409 continue; 3410 } 3411 result.add(info.activityInfo.packageName); 3412 } 3413 3414 return result; 3415 } 3416 3417 private boolean packageIsBrowser(String packageName, int userId) { 3418 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3419 PackageManager.MATCH_ALL, userId); 3420 final int N = list.size(); 3421 for (int i = 0; i < N; i++) { 3422 ResolveInfo info = list.get(i); 3423 if (packageName.equals(info.activityInfo.packageName)) { 3424 return true; 3425 } 3426 } 3427 return false; 3428 } 3429 3430 private void checkDefaultBrowser() { 3431 final int myUserId = UserHandle.myUserId(); 3432 final String packageName = getDefaultBrowserPackageName(myUserId); 3433 if (packageName != null) { 3434 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3435 if (info == null) { 3436 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3437 synchronized (mPackages) { 3438 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3439 } 3440 } 3441 } 3442 } 3443 3444 @Override 3445 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3446 throws RemoteException { 3447 try { 3448 return super.onTransact(code, data, reply, flags); 3449 } catch (RuntimeException e) { 3450 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3451 Slog.wtf(TAG, "Package Manager Crash", e); 3452 } 3453 throw e; 3454 } 3455 } 3456 3457 static int[] appendInts(int[] cur, int[] add) { 3458 if (add == null) return cur; 3459 if (cur == null) return add; 3460 final int N = add.length; 3461 for (int i=0; i<N; i++) { 3462 cur = appendInt(cur, add[i]); 3463 } 3464 return cur; 3465 } 3466 3467 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3468 if (!sUserManager.exists(userId)) return null; 3469 if (ps == null) { 3470 return null; 3471 } 3472 final PackageParser.Package p = ps.pkg; 3473 if (p == null) { 3474 return null; 3475 } 3476 // Filter out ephemeral app metadata: 3477 // * The system/shell/root can see metadata for any app 3478 // * An installed app can see metadata for 1) other installed apps 3479 // and 2) ephemeral apps that have explicitly interacted with it 3480 // * Ephemeral apps can only see their own data and exposed installed apps 3481 // * Holding a signature permission allows seeing instant apps 3482 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3483 if (callingAppId != Process.SYSTEM_UID 3484 && callingAppId != Process.SHELL_UID 3485 && callingAppId != Process.ROOT_UID 3486 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3487 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3488 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3489 if (instantAppPackageName != null) { 3490 // ephemeral apps can only get information on themselves or 3491 // installed apps that are exposed. 3492 if (!instantAppPackageName.equals(p.packageName) 3493 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3494 return null; 3495 } 3496 } else { 3497 if (ps.getInstantApp(userId)) { 3498 // only get access to the ephemeral app if we've been granted access 3499 if (!mInstantAppRegistry.isInstantAccessGranted( 3500 userId, callingAppId, ps.appId)) { 3501 return null; 3502 } 3503 } 3504 } 3505 } 3506 3507 final PermissionsState permissionsState = ps.getPermissionsState(); 3508 3509 // Compute GIDs only if requested 3510 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3511 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3512 // Compute granted permissions only if package has requested permissions 3513 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3514 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3515 final PackageUserState state = ps.readUserState(userId); 3516 3517 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3518 && ps.isSystem()) { 3519 flags |= MATCH_ANY_USER; 3520 } 3521 3522 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3523 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3524 3525 if (packageInfo == null) { 3526 return null; 3527 } 3528 3529 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3530 3531 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3532 resolveExternalPackageNameLPr(p); 3533 3534 return packageInfo; 3535 } 3536 3537 @Override 3538 public void checkPackageStartable(String packageName, int userId) { 3539 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3540 3541 synchronized (mPackages) { 3542 final PackageSetting ps = mSettings.mPackages.get(packageName); 3543 if (ps == null) { 3544 throw new SecurityException("Package " + packageName + " was not found!"); 3545 } 3546 3547 if (!ps.getInstalled(userId)) { 3548 throw new SecurityException( 3549 "Package " + packageName + " was not installed for user " + userId + "!"); 3550 } 3551 3552 if (mSafeMode && !ps.isSystem()) { 3553 throw new SecurityException("Package " + packageName + " not a system app!"); 3554 } 3555 3556 if (mFrozenPackages.contains(packageName)) { 3557 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3558 } 3559 3560 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3561 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3562 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3563 } 3564 } 3565 } 3566 3567 @Override 3568 public boolean isPackageAvailable(String packageName, int userId) { 3569 if (!sUserManager.exists(userId)) return false; 3570 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3571 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3572 synchronized (mPackages) { 3573 PackageParser.Package p = mPackages.get(packageName); 3574 if (p != null) { 3575 final PackageSetting ps = (PackageSetting) p.mExtras; 3576 if (ps != null) { 3577 final PackageUserState state = ps.readUserState(userId); 3578 if (state != null) { 3579 return PackageParser.isAvailable(state); 3580 } 3581 } 3582 } 3583 } 3584 return false; 3585 } 3586 3587 @Override 3588 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3589 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3590 flags, userId); 3591 } 3592 3593 @Override 3594 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3595 int flags, int userId) { 3596 return getPackageInfoInternal(versionedPackage.getPackageName(), 3597 // TODO: We will change version code to long, so in the new API it is long 3598 (int) versionedPackage.getVersionCode(), flags, userId); 3599 } 3600 3601 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3602 int flags, int userId) { 3603 if (!sUserManager.exists(userId)) return null; 3604 flags = updateFlagsForPackage(flags, userId, packageName); 3605 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3606 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3607 3608 // reader 3609 synchronized (mPackages) { 3610 // Normalize package name to handle renamed packages and static libs 3611 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3612 3613 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3614 if (matchFactoryOnly) { 3615 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3616 if (ps != null) { 3617 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3618 return null; 3619 } 3620 return generatePackageInfo(ps, flags, userId); 3621 } 3622 } 3623 3624 PackageParser.Package p = mPackages.get(packageName); 3625 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3626 return null; 3627 } 3628 if (DEBUG_PACKAGE_INFO) 3629 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3630 if (p != null) { 3631 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3632 Binder.getCallingUid(), userId)) { 3633 return null; 3634 } 3635 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3636 } 3637 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3638 final PackageSetting ps = mSettings.mPackages.get(packageName); 3639 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3640 return null; 3641 } 3642 return generatePackageInfo(ps, flags, userId); 3643 } 3644 } 3645 return null; 3646 } 3647 3648 3649 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3650 // System/shell/root get to see all static libs 3651 final int appId = UserHandle.getAppId(uid); 3652 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3653 || appId == Process.ROOT_UID) { 3654 return false; 3655 } 3656 3657 // No package means no static lib as it is always on internal storage 3658 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3659 return false; 3660 } 3661 3662 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3663 ps.pkg.staticSharedLibVersion); 3664 if (libEntry == null) { 3665 return false; 3666 } 3667 3668 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3669 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3670 if (uidPackageNames == null) { 3671 return true; 3672 } 3673 3674 for (String uidPackageName : uidPackageNames) { 3675 if (ps.name.equals(uidPackageName)) { 3676 return false; 3677 } 3678 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3679 if (uidPs != null) { 3680 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3681 libEntry.info.getName()); 3682 if (index < 0) { 3683 continue; 3684 } 3685 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3686 return false; 3687 } 3688 } 3689 } 3690 return true; 3691 } 3692 3693 @Override 3694 public String[] currentToCanonicalPackageNames(String[] names) { 3695 String[] out = new String[names.length]; 3696 // reader 3697 synchronized (mPackages) { 3698 for (int i=names.length-1; i>=0; i--) { 3699 PackageSetting ps = mSettings.mPackages.get(names[i]); 3700 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3701 } 3702 } 3703 return out; 3704 } 3705 3706 @Override 3707 public String[] canonicalToCurrentPackageNames(String[] names) { 3708 String[] out = new String[names.length]; 3709 // reader 3710 synchronized (mPackages) { 3711 for (int i=names.length-1; i>=0; i--) { 3712 String cur = mSettings.getRenamedPackageLPr(names[i]); 3713 out[i] = cur != null ? cur : names[i]; 3714 } 3715 } 3716 return out; 3717 } 3718 3719 @Override 3720 public int getPackageUid(String packageName, int flags, int userId) { 3721 if (!sUserManager.exists(userId)) return -1; 3722 flags = updateFlagsForPackage(flags, userId, packageName); 3723 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3724 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3725 3726 // reader 3727 synchronized (mPackages) { 3728 final PackageParser.Package p = mPackages.get(packageName); 3729 if (p != null && p.isMatch(flags)) { 3730 return UserHandle.getUid(userId, p.applicationInfo.uid); 3731 } 3732 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3733 final PackageSetting ps = mSettings.mPackages.get(packageName); 3734 if (ps != null && ps.isMatch(flags)) { 3735 return UserHandle.getUid(userId, ps.appId); 3736 } 3737 } 3738 } 3739 3740 return -1; 3741 } 3742 3743 @Override 3744 public int[] getPackageGids(String packageName, int flags, int userId) { 3745 if (!sUserManager.exists(userId)) return null; 3746 flags = updateFlagsForPackage(flags, userId, packageName); 3747 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3748 false /* requireFullPermission */, false /* checkShell */, 3749 "getPackageGids"); 3750 3751 // reader 3752 synchronized (mPackages) { 3753 final PackageParser.Package p = mPackages.get(packageName); 3754 if (p != null && p.isMatch(flags)) { 3755 PackageSetting ps = (PackageSetting) p.mExtras; 3756 // TODO: Shouldn't this be checking for package installed state for userId and 3757 // return null? 3758 return ps.getPermissionsState().computeGids(userId); 3759 } 3760 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3761 final PackageSetting ps = mSettings.mPackages.get(packageName); 3762 if (ps != null && ps.isMatch(flags)) { 3763 return ps.getPermissionsState().computeGids(userId); 3764 } 3765 } 3766 } 3767 3768 return null; 3769 } 3770 3771 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3772 if (bp.perm != null) { 3773 return PackageParser.generatePermissionInfo(bp.perm, flags); 3774 } 3775 PermissionInfo pi = new PermissionInfo(); 3776 pi.name = bp.name; 3777 pi.packageName = bp.sourcePackage; 3778 pi.nonLocalizedLabel = bp.name; 3779 pi.protectionLevel = bp.protectionLevel; 3780 return pi; 3781 } 3782 3783 @Override 3784 public PermissionInfo getPermissionInfo(String name, int flags) { 3785 // reader 3786 synchronized (mPackages) { 3787 final BasePermission p = mSettings.mPermissions.get(name); 3788 if (p != null) { 3789 return generatePermissionInfo(p, flags); 3790 } 3791 return null; 3792 } 3793 } 3794 3795 @Override 3796 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3797 int flags) { 3798 // reader 3799 synchronized (mPackages) { 3800 if (group != null && !mPermissionGroups.containsKey(group)) { 3801 // This is thrown as NameNotFoundException 3802 return null; 3803 } 3804 3805 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3806 for (BasePermission p : mSettings.mPermissions.values()) { 3807 if (group == null) { 3808 if (p.perm == null || p.perm.info.group == null) { 3809 out.add(generatePermissionInfo(p, flags)); 3810 } 3811 } else { 3812 if (p.perm != null && group.equals(p.perm.info.group)) { 3813 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3814 } 3815 } 3816 } 3817 return new ParceledListSlice<>(out); 3818 } 3819 } 3820 3821 @Override 3822 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3823 // reader 3824 synchronized (mPackages) { 3825 return PackageParser.generatePermissionGroupInfo( 3826 mPermissionGroups.get(name), flags); 3827 } 3828 } 3829 3830 @Override 3831 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3832 // reader 3833 synchronized (mPackages) { 3834 final int N = mPermissionGroups.size(); 3835 ArrayList<PermissionGroupInfo> out 3836 = new ArrayList<PermissionGroupInfo>(N); 3837 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3838 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3839 } 3840 return new ParceledListSlice<>(out); 3841 } 3842 } 3843 3844 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3845 int uid, int userId) { 3846 if (!sUserManager.exists(userId)) return null; 3847 PackageSetting ps = mSettings.mPackages.get(packageName); 3848 if (ps != null) { 3849 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3850 return null; 3851 } 3852 if (ps.pkg == null) { 3853 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3854 if (pInfo != null) { 3855 return pInfo.applicationInfo; 3856 } 3857 return null; 3858 } 3859 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3860 ps.readUserState(userId), userId); 3861 if (ai != null) { 3862 rebaseEnabledOverlays(ai, userId); 3863 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3864 } 3865 return ai; 3866 } 3867 return null; 3868 } 3869 3870 @Override 3871 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3872 if (!sUserManager.exists(userId)) return null; 3873 flags = updateFlagsForApplication(flags, userId, packageName); 3874 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3875 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3876 3877 // writer 3878 synchronized (mPackages) { 3879 // Normalize package name to handle renamed packages and static libs 3880 packageName = resolveInternalPackageNameLPr(packageName, 3881 PackageManager.VERSION_CODE_HIGHEST); 3882 3883 PackageParser.Package p = mPackages.get(packageName); 3884 if (DEBUG_PACKAGE_INFO) Log.v( 3885 TAG, "getApplicationInfo " + packageName 3886 + ": " + p); 3887 if (p != null) { 3888 PackageSetting ps = mSettings.mPackages.get(packageName); 3889 if (ps == null) return null; 3890 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3891 return null; 3892 } 3893 // Note: isEnabledLP() does not apply here - always return info 3894 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3895 p, flags, ps.readUserState(userId), userId); 3896 if (ai != null) { 3897 rebaseEnabledOverlays(ai, userId); 3898 ai.packageName = resolveExternalPackageNameLPr(p); 3899 } 3900 return ai; 3901 } 3902 if ("android".equals(packageName)||"system".equals(packageName)) { 3903 return mAndroidApplication; 3904 } 3905 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3906 // Already generates the external package name 3907 return generateApplicationInfoFromSettingsLPw(packageName, 3908 Binder.getCallingUid(), flags, userId); 3909 } 3910 } 3911 return null; 3912 } 3913 3914 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3915 List<String> paths = new ArrayList<>(); 3916 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3917 mEnabledOverlayPaths.get(userId); 3918 if (userSpecificOverlays != null) { 3919 if (!"android".equals(ai.packageName)) { 3920 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3921 if (frameworkOverlays != null) { 3922 paths.addAll(frameworkOverlays); 3923 } 3924 } 3925 3926 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3927 if (appOverlays != null) { 3928 paths.addAll(appOverlays); 3929 } 3930 } 3931 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3932 } 3933 3934 private String normalizePackageNameLPr(String packageName) { 3935 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3936 return normalizedPackageName != null ? normalizedPackageName : packageName; 3937 } 3938 3939 @Override 3940 public void deletePreloadsFileCache() { 3941 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3942 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3943 } 3944 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3945 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3946 FileUtils.deleteContents(dir); 3947 } 3948 3949 @Override 3950 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3951 final IPackageDataObserver observer) { 3952 mContext.enforceCallingOrSelfPermission( 3953 android.Manifest.permission.CLEAR_APP_CACHE, null); 3954 mHandler.post(() -> { 3955 boolean success = false; 3956 try { 3957 freeStorage(volumeUuid, freeStorageSize, 0); 3958 success = true; 3959 } catch (IOException e) { 3960 Slog.w(TAG, e); 3961 } 3962 if (observer != null) { 3963 try { 3964 observer.onRemoveCompleted(null, success); 3965 } catch (RemoteException e) { 3966 Slog.w(TAG, e); 3967 } 3968 } 3969 }); 3970 } 3971 3972 @Override 3973 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3974 final IntentSender pi) { 3975 mContext.enforceCallingOrSelfPermission( 3976 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3977 mHandler.post(() -> { 3978 boolean success = false; 3979 try { 3980 freeStorage(volumeUuid, freeStorageSize, 0); 3981 success = true; 3982 } catch (IOException e) { 3983 Slog.w(TAG, e); 3984 } 3985 if (pi != null) { 3986 try { 3987 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3988 } catch (SendIntentException e) { 3989 Slog.w(TAG, e); 3990 } 3991 } 3992 }); 3993 } 3994 3995 /** 3996 * Blocking call to clear various types of cached data across the system 3997 * until the requested bytes are available. 3998 */ 3999 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4000 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4001 final File file = storage.findPathForUuid(volumeUuid); 4002 if (file.getUsableSpace() >= bytes) return; 4003 4004 if (ENABLE_FREE_CACHE_V2) { 4005 final boolean aggressive = (storageFlags 4006 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4007 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4008 volumeUuid); 4009 4010 // 1. Pre-flight to determine if we have any chance to succeed 4011 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4012 if (internalVolume && (aggressive || SystemProperties 4013 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4014 deletePreloadsFileCache(); 4015 if (file.getUsableSpace() >= bytes) return; 4016 } 4017 4018 // 3. Consider parsed APK data (aggressive only) 4019 if (internalVolume && aggressive) { 4020 FileUtils.deleteContents(mCacheDir); 4021 if (file.getUsableSpace() >= bytes) return; 4022 } 4023 4024 // 4. Consider cached app data (above quotas) 4025 try { 4026 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 4027 } catch (InstallerException ignored) { 4028 } 4029 if (file.getUsableSpace() >= bytes) return; 4030 4031 // 5. Consider shared libraries with refcount=0 and age>2h 4032 // 6. Consider dexopt output (aggressive only) 4033 // 7. Consider ephemeral apps not used in last week 4034 4035 // 8. Consider cached app data (below quotas) 4036 try { 4037 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 4038 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4039 } catch (InstallerException ignored) { 4040 } 4041 if (file.getUsableSpace() >= bytes) return; 4042 4043 // 9. Consider DropBox entries 4044 // 10. Consider ephemeral cookies 4045 4046 } else { 4047 try { 4048 mInstaller.freeCache(volumeUuid, bytes, 0); 4049 } catch (InstallerException ignored) { 4050 } 4051 if (file.getUsableSpace() >= bytes) return; 4052 } 4053 4054 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4055 } 4056 4057 /** 4058 * Update given flags based on encryption status of current user. 4059 */ 4060 private int updateFlags(int flags, int userId) { 4061 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4062 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4063 // Caller expressed an explicit opinion about what encryption 4064 // aware/unaware components they want to see, so fall through and 4065 // give them what they want 4066 } else { 4067 // Caller expressed no opinion, so match based on user state 4068 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4069 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4070 } else { 4071 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4072 } 4073 } 4074 return flags; 4075 } 4076 4077 private UserManagerInternal getUserManagerInternal() { 4078 if (mUserManagerInternal == null) { 4079 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4080 } 4081 return mUserManagerInternal; 4082 } 4083 4084 private DeviceIdleController.LocalService getDeviceIdleController() { 4085 if (mDeviceIdleController == null) { 4086 mDeviceIdleController = 4087 LocalServices.getService(DeviceIdleController.LocalService.class); 4088 } 4089 return mDeviceIdleController; 4090 } 4091 4092 /** 4093 * Update given flags when being used to request {@link PackageInfo}. 4094 */ 4095 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4096 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4097 boolean triaged = true; 4098 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4099 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4100 // Caller is asking for component details, so they'd better be 4101 // asking for specific encryption matching behavior, or be triaged 4102 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4103 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4104 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4105 triaged = false; 4106 } 4107 } 4108 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4109 | PackageManager.MATCH_SYSTEM_ONLY 4110 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4111 triaged = false; 4112 } 4113 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4114 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 4115 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4116 + Debug.getCallers(5)); 4117 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4118 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4119 // If the caller wants all packages and has a restricted profile associated with it, 4120 // then match all users. This is to make sure that launchers that need to access work 4121 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4122 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4123 flags |= PackageManager.MATCH_ANY_USER; 4124 } 4125 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4126 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4127 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4128 } 4129 return updateFlags(flags, userId); 4130 } 4131 4132 /** 4133 * Update given flags when being used to request {@link ApplicationInfo}. 4134 */ 4135 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4136 return updateFlagsForPackage(flags, userId, cookie); 4137 } 4138 4139 /** 4140 * Update given flags when being used to request {@link ComponentInfo}. 4141 */ 4142 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4143 if (cookie instanceof Intent) { 4144 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4145 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4146 } 4147 } 4148 4149 boolean triaged = true; 4150 // Caller is asking for component details, so they'd better be 4151 // asking for specific encryption matching behavior, or be triaged 4152 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4153 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4154 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4155 triaged = false; 4156 } 4157 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4158 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4159 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4160 } 4161 4162 return updateFlags(flags, userId); 4163 } 4164 4165 /** 4166 * Update given intent when being used to request {@link ResolveInfo}. 4167 */ 4168 private Intent updateIntentForResolve(Intent intent) { 4169 if (intent.getSelector() != null) { 4170 intent = intent.getSelector(); 4171 } 4172 if (DEBUG_PREFERRED) { 4173 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4174 } 4175 return intent; 4176 } 4177 4178 /** 4179 * Update given flags when being used to request {@link ResolveInfo}. 4180 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4181 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4182 * flag set. However, this flag is only honoured in three circumstances: 4183 * <ul> 4184 * <li>when called from a system process</li> 4185 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4186 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4187 * action and a {@code android.intent.category.BROWSABLE} category</li> 4188 * </ul> 4189 */ 4190 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4191 return updateFlagsForResolve(flags, userId, intent, callingUid, 4192 false /*includeInstantApps*/, false /*onlyExposedExplicitly*/); 4193 } 4194 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4195 boolean includeInstantApps) { 4196 return updateFlagsForResolve(flags, userId, intent, callingUid, 4197 includeInstantApps, false /*onlyExposedExplicitly*/); 4198 } 4199 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4200 boolean includeInstantApps, boolean onlyExposedExplicitly) { 4201 // Safe mode means we shouldn't match any third-party components 4202 if (mSafeMode) { 4203 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4204 } 4205 if (getInstantAppPackageName(callingUid) != null) { 4206 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4207 if (onlyExposedExplicitly) { 4208 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4209 } 4210 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4211 flags |= PackageManager.MATCH_INSTANT; 4212 } else { 4213 // Otherwise, prevent leaking ephemeral components 4214 final boolean isSpecialProcess = 4215 callingUid == Process.SYSTEM_UID 4216 || callingUid == Process.SHELL_UID 4217 || callingUid == 0; 4218 final boolean allowMatchInstant = 4219 (includeInstantApps 4220 && Intent.ACTION_VIEW.equals(intent.getAction()) 4221 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4222 && hasWebURI(intent)) 4223 || isSpecialProcess 4224 || mContext.checkCallingOrSelfPermission( 4225 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4226 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4227 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4228 if (!allowMatchInstant) { 4229 flags &= ~PackageManager.MATCH_INSTANT; 4230 } 4231 } 4232 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4233 } 4234 4235 private ActivityInfo generateActivityInfo(ActivityInfo ai, int flags, PackageUserState state, 4236 int userId) { 4237 ActivityInfo ret = PackageParser.generateActivityInfo(ai, flags, state, userId); 4238 if (ret != null) { 4239 rebaseEnabledOverlays(ret.applicationInfo, userId); 4240 } 4241 return ret; 4242 } 4243 4244 private ActivityInfo generateActivityInfo(PackageParser.Activity a, int flags, 4245 PackageUserState state, int userId) { 4246 ActivityInfo ai = PackageParser.generateActivityInfo(a, flags, state, userId); 4247 if (ai != null) { 4248 rebaseEnabledOverlays(ai.applicationInfo, userId); 4249 } 4250 return ai; 4251 } 4252 4253 @Override 4254 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4255 if (!sUserManager.exists(userId)) return null; 4256 flags = updateFlagsForComponent(flags, userId, component); 4257 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4258 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4259 synchronized (mPackages) { 4260 PackageParser.Activity a = mActivities.mActivities.get(component); 4261 4262 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4263 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4264 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4265 if (ps == null) return null; 4266 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4267 } 4268 if (mResolveComponentName.equals(component)) { 4269 return generateActivityInfo(mResolveActivity, flags, new PackageUserState(), 4270 userId); 4271 } 4272 } 4273 return null; 4274 } 4275 4276 @Override 4277 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4278 String resolvedType) { 4279 synchronized (mPackages) { 4280 if (component.equals(mResolveComponentName)) { 4281 // The resolver supports EVERYTHING! 4282 return true; 4283 } 4284 PackageParser.Activity a = mActivities.mActivities.get(component); 4285 if (a == null) { 4286 return false; 4287 } 4288 for (int i=0; i<a.intents.size(); i++) { 4289 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4290 intent.getData(), intent.getCategories(), TAG) >= 0) { 4291 return true; 4292 } 4293 } 4294 return false; 4295 } 4296 } 4297 4298 @Override 4299 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4300 if (!sUserManager.exists(userId)) return null; 4301 flags = updateFlagsForComponent(flags, userId, component); 4302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4303 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4304 synchronized (mPackages) { 4305 PackageParser.Activity a = mReceivers.mActivities.get(component); 4306 if (DEBUG_PACKAGE_INFO) Log.v( 4307 TAG, "getReceiverInfo " + component + ": " + a); 4308 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4309 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4310 if (ps == null) return null; 4311 return generateActivityInfo(a, flags, ps.readUserState(userId), userId); 4312 } 4313 } 4314 return null; 4315 } 4316 4317 @Override 4318 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4319 if (!sUserManager.exists(userId)) return null; 4320 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4321 4322 flags = updateFlagsForPackage(flags, userId, null); 4323 4324 final boolean canSeeStaticLibraries = 4325 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4326 == PERMISSION_GRANTED 4327 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4328 == PERMISSION_GRANTED 4329 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4330 == PERMISSION_GRANTED 4331 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4332 == PERMISSION_GRANTED; 4333 4334 synchronized (mPackages) { 4335 List<SharedLibraryInfo> result = null; 4336 4337 final int libCount = mSharedLibraries.size(); 4338 for (int i = 0; i < libCount; i++) { 4339 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4340 if (versionedLib == null) { 4341 continue; 4342 } 4343 4344 final int versionCount = versionedLib.size(); 4345 for (int j = 0; j < versionCount; j++) { 4346 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4347 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4348 break; 4349 } 4350 final long identity = Binder.clearCallingIdentity(); 4351 try { 4352 // TODO: We will change version code to long, so in the new API it is long 4353 PackageInfo packageInfo = getPackageInfoVersioned( 4354 libInfo.getDeclaringPackage(), flags, userId); 4355 if (packageInfo == null) { 4356 continue; 4357 } 4358 } finally { 4359 Binder.restoreCallingIdentity(identity); 4360 } 4361 4362 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4363 // TODO: Remove cast for lib version once internally we support longs. 4364 (int) 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 isEphemeralAllowed( 5875 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5876 boolean skipPackageCheck) { 5877 final int callingUser = UserHandle.getCallingUserId(); 5878 if (mInstantAppResolverConnection == null) { 5879 return false; 5880 } 5881 if (mInstantAppInstallerActivity == null) { 5882 return false; 5883 } 5884 if (intent.getComponent() != null) { 5885 return false; 5886 } 5887 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5888 return false; 5889 } 5890 if (!skipPackageCheck && intent.getPackage() != null) { 5891 return false; 5892 } 5893 final boolean isWebUri = hasWebURI(intent); 5894 if (!isWebUri || intent.getData().getHost() == null) { 5895 return false; 5896 } 5897 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5898 // Or if there's already an ephemeral app installed that handles the action 5899 synchronized (mPackages) { 5900 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5901 for (int n = 0; n < count; n++) { 5902 final ResolveInfo info = resolvedActivities.get(n); 5903 final String packageName = info.activityInfo.packageName; 5904 final PackageSetting ps = mSettings.mPackages.get(packageName); 5905 if (ps != null) { 5906 // only check domain verification status if the app is not a browser 5907 if (!info.handleAllWebDataURI) { 5908 // Try to get the status from User settings first 5909 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5910 final int status = (int) (packedStatus >> 32); 5911 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5912 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5913 if (DEBUG_EPHEMERAL) { 5914 Slog.v(TAG, "DENY instant app;" 5915 + " pkg: " + packageName + ", status: " + status); 5916 } 5917 return false; 5918 } 5919 } 5920 if (ps.getInstantApp(userId)) { 5921 if (DEBUG_EPHEMERAL) { 5922 Slog.v(TAG, "DENY instant app installed;" 5923 + " pkg: " + packageName); 5924 } 5925 return false; 5926 } 5927 } 5928 } 5929 } 5930 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5931 return true; 5932 } 5933 5934 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5935 Intent origIntent, String resolvedType, String callingPackage, 5936 Bundle verificationBundle, int userId) { 5937 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5938 new InstantAppRequest(responseObj, origIntent, resolvedType, 5939 callingPackage, userId, verificationBundle)); 5940 mHandler.sendMessage(msg); 5941 } 5942 5943 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5944 int flags, List<ResolveInfo> query, int userId) { 5945 if (query != null) { 5946 final int N = query.size(); 5947 if (N == 1) { 5948 return query.get(0); 5949 } else if (N > 1) { 5950 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5951 // If there is more than one activity with the same priority, 5952 // then let the user decide between them. 5953 ResolveInfo r0 = query.get(0); 5954 ResolveInfo r1 = query.get(1); 5955 if (DEBUG_INTENT_MATCHING || debug) { 5956 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5957 + r1.activityInfo.name + "=" + r1.priority); 5958 } 5959 // If the first activity has a higher priority, or a different 5960 // default, then it is always desirable to pick it. 5961 if (r0.priority != r1.priority 5962 || r0.preferredOrder != r1.preferredOrder 5963 || r0.isDefault != r1.isDefault) { 5964 return query.get(0); 5965 } 5966 // If we have saved a preference for a preferred activity for 5967 // this Intent, use that. 5968 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5969 flags, query, r0.priority, true, false, debug, userId); 5970 if (ri != null) { 5971 return ri; 5972 } 5973 // If we have an ephemeral app, use it 5974 for (int i = 0; i < N; i++) { 5975 ri = query.get(i); 5976 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5977 return ri; 5978 } 5979 } 5980 ri = new ResolveInfo(mResolveInfo); 5981 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5982 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5983 // If all of the options come from the same package, show the application's 5984 // label and icon instead of the generic resolver's. 5985 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5986 // and then throw away the ResolveInfo itself, meaning that the caller loses 5987 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5988 // a fallback for this case; we only set the target package's resources on 5989 // the ResolveInfo, not the ActivityInfo. 5990 final String intentPackage = intent.getPackage(); 5991 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5992 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5993 ri.resolvePackageName = intentPackage; 5994 if (userNeedsBadging(userId)) { 5995 ri.noResourceId = true; 5996 } else { 5997 ri.icon = appi.icon; 5998 } 5999 ri.iconResourceId = appi.icon; 6000 ri.labelRes = appi.labelRes; 6001 } 6002 ri.activityInfo.applicationInfo = new ApplicationInfo( 6003 ri.activityInfo.applicationInfo); 6004 if (userId != 0) { 6005 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6006 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6007 } 6008 // Make sure that the resolver is displayable in car mode 6009 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6010 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6011 return ri; 6012 } 6013 } 6014 return null; 6015 } 6016 6017 /** 6018 * Return true if the given list is not empty and all of its contents have 6019 * an activityInfo with the given package name. 6020 */ 6021 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6022 if (ArrayUtils.isEmpty(list)) { 6023 return false; 6024 } 6025 for (int i = 0, N = list.size(); i < N; i++) { 6026 final ResolveInfo ri = list.get(i); 6027 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6028 if (ai == null || !packageName.equals(ai.packageName)) { 6029 return false; 6030 } 6031 } 6032 return true; 6033 } 6034 6035 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6036 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6037 final int N = query.size(); 6038 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6039 .get(userId); 6040 // Get the list of persistent preferred activities that handle the intent 6041 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6042 List<PersistentPreferredActivity> pprefs = ppir != null 6043 ? ppir.queryIntent(intent, resolvedType, 6044 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6045 userId) 6046 : null; 6047 if (pprefs != null && pprefs.size() > 0) { 6048 final int M = pprefs.size(); 6049 for (int i=0; i<M; i++) { 6050 final PersistentPreferredActivity ppa = pprefs.get(i); 6051 if (DEBUG_PREFERRED || debug) { 6052 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6053 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6054 + "\n component=" + ppa.mComponent); 6055 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6056 } 6057 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6058 flags | MATCH_DISABLED_COMPONENTS, userId); 6059 if (DEBUG_PREFERRED || debug) { 6060 Slog.v(TAG, "Found persistent preferred activity:"); 6061 if (ai != null) { 6062 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6063 } else { 6064 Slog.v(TAG, " null"); 6065 } 6066 } 6067 if (ai == null) { 6068 // This previously registered persistent preferred activity 6069 // component is no longer known. Ignore it and do NOT remove it. 6070 continue; 6071 } 6072 for (int j=0; j<N; j++) { 6073 final ResolveInfo ri = query.get(j); 6074 if (!ri.activityInfo.applicationInfo.packageName 6075 .equals(ai.applicationInfo.packageName)) { 6076 continue; 6077 } 6078 if (!ri.activityInfo.name.equals(ai.name)) { 6079 continue; 6080 } 6081 // Found a persistent preference that can handle the intent. 6082 if (DEBUG_PREFERRED || debug) { 6083 Slog.v(TAG, "Returning persistent preferred activity: " + 6084 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6085 } 6086 return ri; 6087 } 6088 } 6089 } 6090 return null; 6091 } 6092 6093 // TODO: handle preferred activities missing while user has amnesia 6094 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6095 List<ResolveInfo> query, int priority, boolean always, 6096 boolean removeMatches, boolean debug, int userId) { 6097 if (!sUserManager.exists(userId)) return null; 6098 final int callingUid = Binder.getCallingUid(); 6099 flags = updateFlagsForResolve( 6100 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6101 intent = updateIntentForResolve(intent); 6102 // writer 6103 synchronized (mPackages) { 6104 // Try to find a matching persistent preferred activity. 6105 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6106 debug, userId); 6107 6108 // If a persistent preferred activity matched, use it. 6109 if (pri != null) { 6110 return pri; 6111 } 6112 6113 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6114 // Get the list of preferred activities that handle the intent 6115 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6116 List<PreferredActivity> prefs = pir != null 6117 ? pir.queryIntent(intent, resolvedType, 6118 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6119 userId) 6120 : null; 6121 if (prefs != null && prefs.size() > 0) { 6122 boolean changed = false; 6123 try { 6124 // First figure out how good the original match set is. 6125 // We will only allow preferred activities that came 6126 // from the same match quality. 6127 int match = 0; 6128 6129 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6130 6131 final int N = query.size(); 6132 for (int j=0; j<N; j++) { 6133 final ResolveInfo ri = query.get(j); 6134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6135 + ": 0x" + Integer.toHexString(match)); 6136 if (ri.match > match) { 6137 match = ri.match; 6138 } 6139 } 6140 6141 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6142 + Integer.toHexString(match)); 6143 6144 match &= IntentFilter.MATCH_CATEGORY_MASK; 6145 final int M = prefs.size(); 6146 for (int i=0; i<M; i++) { 6147 final PreferredActivity pa = prefs.get(i); 6148 if (DEBUG_PREFERRED || debug) { 6149 Slog.v(TAG, "Checking PreferredActivity ds=" 6150 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6151 + "\n component=" + pa.mPref.mComponent); 6152 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6153 } 6154 if (pa.mPref.mMatch != match) { 6155 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6156 + Integer.toHexString(pa.mPref.mMatch)); 6157 continue; 6158 } 6159 // If it's not an "always" type preferred activity and that's what we're 6160 // looking for, skip it. 6161 if (always && !pa.mPref.mAlways) { 6162 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6163 continue; 6164 } 6165 final ActivityInfo ai = getActivityInfo( 6166 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6167 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6168 userId); 6169 if (DEBUG_PREFERRED || debug) { 6170 Slog.v(TAG, "Found preferred activity:"); 6171 if (ai != null) { 6172 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6173 } else { 6174 Slog.v(TAG, " null"); 6175 } 6176 } 6177 if (ai == null) { 6178 // This previously registered preferred activity 6179 // component is no longer known. Most likely an update 6180 // to the app was installed and in the new version this 6181 // component no longer exists. Clean it up by removing 6182 // it from the preferred activities list, and skip it. 6183 Slog.w(TAG, "Removing dangling preferred activity: " 6184 + pa.mPref.mComponent); 6185 pir.removeFilter(pa); 6186 changed = true; 6187 continue; 6188 } 6189 for (int j=0; j<N; j++) { 6190 final ResolveInfo ri = query.get(j); 6191 if (!ri.activityInfo.applicationInfo.packageName 6192 .equals(ai.applicationInfo.packageName)) { 6193 continue; 6194 } 6195 if (!ri.activityInfo.name.equals(ai.name)) { 6196 continue; 6197 } 6198 6199 if (removeMatches) { 6200 pir.removeFilter(pa); 6201 changed = true; 6202 if (DEBUG_PREFERRED) { 6203 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6204 } 6205 break; 6206 } 6207 6208 // Okay we found a previously set preferred or last chosen app. 6209 // If the result set is different from when this 6210 // was created, we need to clear it and re-ask the 6211 // user their preference, if we're looking for an "always" type entry. 6212 if (always && !pa.mPref.sameSet(query)) { 6213 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6214 + intent + " type " + resolvedType); 6215 if (DEBUG_PREFERRED) { 6216 Slog.v(TAG, "Removing preferred activity since set changed " 6217 + pa.mPref.mComponent); 6218 } 6219 pir.removeFilter(pa); 6220 // Re-add the filter as a "last chosen" entry (!always) 6221 PreferredActivity lastChosen = new PreferredActivity( 6222 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6223 pir.addFilter(lastChosen); 6224 changed = true; 6225 return null; 6226 } 6227 6228 // Yay! Either the set matched or we're looking for the last chosen 6229 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6230 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6231 return ri; 6232 } 6233 } 6234 } finally { 6235 if (changed) { 6236 if (DEBUG_PREFERRED) { 6237 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6238 } 6239 scheduleWritePackageRestrictionsLocked(userId); 6240 } 6241 } 6242 } 6243 } 6244 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6245 return null; 6246 } 6247 6248 /* 6249 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6250 */ 6251 @Override 6252 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6253 int targetUserId) { 6254 mContext.enforceCallingOrSelfPermission( 6255 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6256 List<CrossProfileIntentFilter> matches = 6257 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6258 if (matches != null) { 6259 int size = matches.size(); 6260 for (int i = 0; i < size; i++) { 6261 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6262 } 6263 } 6264 if (hasWebURI(intent)) { 6265 // cross-profile app linking works only towards the parent. 6266 final int callingUid = Binder.getCallingUid(); 6267 final UserInfo parent = getProfileParent(sourceUserId); 6268 synchronized(mPackages) { 6269 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6270 false /*includeInstantApps*/); 6271 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6272 intent, resolvedType, flags, sourceUserId, parent.id); 6273 return xpDomainInfo != null; 6274 } 6275 } 6276 return false; 6277 } 6278 6279 private UserInfo getProfileParent(int userId) { 6280 final long identity = Binder.clearCallingIdentity(); 6281 try { 6282 return sUserManager.getProfileParent(userId); 6283 } finally { 6284 Binder.restoreCallingIdentity(identity); 6285 } 6286 } 6287 6288 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6289 String resolvedType, int userId) { 6290 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6291 if (resolver != null) { 6292 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6293 } 6294 return null; 6295 } 6296 6297 @Override 6298 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6299 String resolvedType, int flags, int userId) { 6300 try { 6301 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6302 6303 return new ParceledListSlice<>( 6304 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6305 } finally { 6306 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6307 } 6308 } 6309 6310 /** 6311 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6312 * instant, returns {@code null}. 6313 */ 6314 private String getInstantAppPackageName(int callingUid) { 6315 // If the caller is an isolated app use the owner's uid for the lookup. 6316 if (Process.isIsolated(callingUid)) { 6317 callingUid = mIsolatedOwners.get(callingUid); 6318 } 6319 final int appId = UserHandle.getAppId(callingUid); 6320 synchronized (mPackages) { 6321 final Object obj = mSettings.getUserIdLPr(appId); 6322 if (obj instanceof PackageSetting) { 6323 final PackageSetting ps = (PackageSetting) obj; 6324 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6325 return isInstantApp ? ps.pkg.packageName : null; 6326 } 6327 } 6328 return null; 6329 } 6330 6331 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6332 String resolvedType, int flags, int userId) { 6333 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6334 } 6335 6336 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6337 String resolvedType, int flags, int userId, boolean resolveForStart) { 6338 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6339 final int callingUid = Binder.getCallingUid(); 6340 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6341 enforceCrossUserPermission(callingUid, userId, 6342 false /* requireFullPermission */, false /* checkShell */, 6343 "query intent activities"); 6344 final String pkgName = intent.getPackage(); 6345 ComponentName comp = intent.getComponent(); 6346 if (comp == null) { 6347 if (intent.getSelector() != null) { 6348 intent = intent.getSelector(); 6349 comp = intent.getComponent(); 6350 } 6351 } 6352 6353 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart, 6354 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6355 if (comp != null) { 6356 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6357 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6358 if (ai != null) { 6359 // When specifying an explicit component, we prevent the activity from being 6360 // used when either 1) the calling package is normal and the activity is within 6361 // an ephemeral application or 2) the calling package is ephemeral and the 6362 // activity is not visible to ephemeral applications. 6363 final boolean matchInstantApp = 6364 (flags & PackageManager.MATCH_INSTANT) != 0; 6365 final boolean matchVisibleToInstantAppOnly = 6366 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6367 final boolean matchExplicitlyVisibleOnly = 6368 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6369 final boolean isCallerInstantApp = 6370 instantAppPkgName != null; 6371 final boolean isTargetSameInstantApp = 6372 comp.getPackageName().equals(instantAppPkgName); 6373 final boolean isTargetInstantApp = 6374 (ai.applicationInfo.privateFlags 6375 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6376 final boolean isTargetVisibleToInstantApp = 6377 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6378 final boolean isTargetExplicitlyVisibleToInstantApp = 6379 isTargetVisibleToInstantApp 6380 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6381 final boolean isTargetHiddenFromInstantApp = 6382 !isTargetVisibleToInstantApp 6383 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6384 final boolean blockResolution = 6385 !isTargetSameInstantApp 6386 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6387 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6388 && isTargetHiddenFromInstantApp)); 6389 if (!blockResolution) { 6390 final ResolveInfo ri = new ResolveInfo(); 6391 ri.activityInfo = ai; 6392 list.add(ri); 6393 } 6394 } 6395 return applyPostResolutionFilter(list, instantAppPkgName); 6396 } 6397 6398 // reader 6399 boolean sortResult = false; 6400 boolean addEphemeral = false; 6401 List<ResolveInfo> result; 6402 final boolean ephemeralDisabled = isEphemeralDisabled(); 6403 synchronized (mPackages) { 6404 if (pkgName == null) { 6405 List<CrossProfileIntentFilter> matchingFilters = 6406 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6407 // Check for results that need to skip the current profile. 6408 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6409 resolvedType, flags, userId); 6410 if (xpResolveInfo != null) { 6411 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6412 xpResult.add(xpResolveInfo); 6413 return applyPostResolutionFilter( 6414 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6415 } 6416 6417 // Check for results in the current profile. 6418 result = filterIfNotSystemUser(mActivities.queryIntent( 6419 intent, resolvedType, flags, userId), userId); 6420 addEphemeral = !ephemeralDisabled 6421 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6422 // Check for cross profile results. 6423 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6424 xpResolveInfo = queryCrossProfileIntents( 6425 matchingFilters, intent, resolvedType, flags, userId, 6426 hasNonNegativePriorityResult); 6427 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6428 boolean isVisibleToUser = filterIfNotSystemUser( 6429 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6430 if (isVisibleToUser) { 6431 result.add(xpResolveInfo); 6432 sortResult = true; 6433 } 6434 } 6435 if (hasWebURI(intent)) { 6436 CrossProfileDomainInfo xpDomainInfo = null; 6437 final UserInfo parent = getProfileParent(userId); 6438 if (parent != null) { 6439 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6440 flags, userId, parent.id); 6441 } 6442 if (xpDomainInfo != null) { 6443 if (xpResolveInfo != null) { 6444 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6445 // in the result. 6446 result.remove(xpResolveInfo); 6447 } 6448 if (result.size() == 0 && !addEphemeral) { 6449 // No result in current profile, but found candidate in parent user. 6450 // And we are not going to add emphemeral app, so we can return the 6451 // result straight away. 6452 result.add(xpDomainInfo.resolveInfo); 6453 return applyPostResolutionFilter(result, instantAppPkgName); 6454 } 6455 } else if (result.size() <= 1 && !addEphemeral) { 6456 // No result in parent user and <= 1 result in current profile, and we 6457 // are not going to add emphemeral app, so we can return the result without 6458 // further processing. 6459 return applyPostResolutionFilter(result, instantAppPkgName); 6460 } 6461 // We have more than one candidate (combining results from current and parent 6462 // profile), so we need filtering and sorting. 6463 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6464 intent, flags, result, xpDomainInfo, userId); 6465 sortResult = true; 6466 } 6467 } else { 6468 final PackageParser.Package pkg = mPackages.get(pkgName); 6469 if (pkg != null) { 6470 return applyPostResolutionFilter(filterIfNotSystemUser( 6471 mActivities.queryIntentForPackage( 6472 intent, resolvedType, flags, pkg.activities, userId), 6473 userId), instantAppPkgName); 6474 } else { 6475 // the caller wants to resolve for a particular package; however, there 6476 // were no installed results, so, try to find an ephemeral result 6477 addEphemeral = !ephemeralDisabled 6478 && isEphemeralAllowed( 6479 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6480 result = new ArrayList<ResolveInfo>(); 6481 } 6482 } 6483 } 6484 if (addEphemeral) { 6485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6486 final InstantAppRequest requestObject = new InstantAppRequest( 6487 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6488 null /*callingPackage*/, userId, null /*verificationBundle*/); 6489 final AuxiliaryResolveInfo auxiliaryResponse = 6490 InstantAppResolver.doInstantAppResolutionPhaseOne( 6491 mContext, mInstantAppResolverConnection, requestObject); 6492 if (auxiliaryResponse != null) { 6493 if (DEBUG_EPHEMERAL) { 6494 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6495 } 6496 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6497 final PackageSetting ps = 6498 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6499 if (ps != null) { 6500 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6501 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6502 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6503 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6504 // make sure this resolver is the default 6505 ephemeralInstaller.isDefault = true; 6506 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6507 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6508 // add a non-generic filter 6509 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6510 ephemeralInstaller.filter.addDataPath( 6511 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6512 ephemeralInstaller.instantAppAvailable = true; 6513 result.add(ephemeralInstaller); 6514 } 6515 } 6516 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6517 } 6518 if (sortResult) { 6519 Collections.sort(result, mResolvePrioritySorter); 6520 } 6521 return applyPostResolutionFilter(result, instantAppPkgName); 6522 } 6523 6524 private static class CrossProfileDomainInfo { 6525 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6526 ResolveInfo resolveInfo; 6527 /* Best domain verification status of the activities found in the other profile */ 6528 int bestDomainVerificationStatus; 6529 } 6530 6531 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6532 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6533 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6534 sourceUserId)) { 6535 return null; 6536 } 6537 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6538 resolvedType, flags, parentUserId); 6539 6540 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6541 return null; 6542 } 6543 CrossProfileDomainInfo result = null; 6544 int size = resultTargetUser.size(); 6545 for (int i = 0; i < size; i++) { 6546 ResolveInfo riTargetUser = resultTargetUser.get(i); 6547 // Intent filter verification is only for filters that specify a host. So don't return 6548 // those that handle all web uris. 6549 if (riTargetUser.handleAllWebDataURI) { 6550 continue; 6551 } 6552 String packageName = riTargetUser.activityInfo.packageName; 6553 PackageSetting ps = mSettings.mPackages.get(packageName); 6554 if (ps == null) { 6555 continue; 6556 } 6557 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6558 int status = (int)(verificationState >> 32); 6559 if (result == null) { 6560 result = new CrossProfileDomainInfo(); 6561 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6562 sourceUserId, parentUserId); 6563 result.bestDomainVerificationStatus = status; 6564 } else { 6565 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6566 result.bestDomainVerificationStatus); 6567 } 6568 } 6569 // Don't consider matches with status NEVER across profiles. 6570 if (result != null && result.bestDomainVerificationStatus 6571 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6572 return null; 6573 } 6574 return result; 6575 } 6576 6577 /** 6578 * Verification statuses are ordered from the worse to the best, except for 6579 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6580 */ 6581 private int bestDomainVerificationStatus(int status1, int status2) { 6582 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6583 return status2; 6584 } 6585 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6586 return status1; 6587 } 6588 return (int) MathUtils.max(status1, status2); 6589 } 6590 6591 private boolean isUserEnabled(int userId) { 6592 long callingId = Binder.clearCallingIdentity(); 6593 try { 6594 UserInfo userInfo = sUserManager.getUserInfo(userId); 6595 return userInfo != null && userInfo.isEnabled(); 6596 } finally { 6597 Binder.restoreCallingIdentity(callingId); 6598 } 6599 } 6600 6601 /** 6602 * Filter out activities with systemUserOnly flag set, when current user is not System. 6603 * 6604 * @return filtered list 6605 */ 6606 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6607 if (userId == UserHandle.USER_SYSTEM) { 6608 return resolveInfos; 6609 } 6610 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6611 ResolveInfo info = resolveInfos.get(i); 6612 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6613 resolveInfos.remove(i); 6614 } 6615 } 6616 return resolveInfos; 6617 } 6618 6619 /** 6620 * Filters out ephemeral activities. 6621 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6622 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6623 * 6624 * @param resolveInfos The pre-filtered list of resolved activities 6625 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6626 * is performed. 6627 * @return A filtered list of resolved activities. 6628 */ 6629 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6630 String ephemeralPkgName) { 6631 // TODO: When adding on-demand split support for non-instant apps, remove this check 6632 // and always apply post filtering 6633 if (ephemeralPkgName == null) { 6634 return resolveInfos; 6635 } 6636 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6637 final ResolveInfo info = resolveInfos.get(i); 6638 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6639 // allow activities that are defined in the provided package 6640 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6641 if (info.activityInfo.splitName != null 6642 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6643 info.activityInfo.splitName)) { 6644 // requested activity is defined in a split that hasn't been installed yet. 6645 // add the installer to the resolve list 6646 if (DEBUG_EPHEMERAL) { 6647 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6648 } 6649 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6650 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6651 info.activityInfo.packageName, info.activityInfo.splitName, 6652 info.activityInfo.applicationInfo.versionCode); 6653 // make sure this resolver is the default 6654 installerInfo.isDefault = true; 6655 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6656 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6657 // add a non-generic filter 6658 installerInfo.filter = new IntentFilter(); 6659 // load resources from the correct package 6660 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6661 resolveInfos.set(i, installerInfo); 6662 } 6663 continue; 6664 } 6665 // allow activities that have been explicitly exposed to ephemeral apps 6666 if (!isEphemeralApp 6667 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6668 continue; 6669 } 6670 resolveInfos.remove(i); 6671 } 6672 return resolveInfos; 6673 } 6674 6675 /** 6676 * @param resolveInfos list of resolve infos in descending priority order 6677 * @return if the list contains a resolve info with non-negative priority 6678 */ 6679 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6680 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6681 } 6682 6683 private static boolean hasWebURI(Intent intent) { 6684 if (intent.getData() == null) { 6685 return false; 6686 } 6687 final String scheme = intent.getScheme(); 6688 if (TextUtils.isEmpty(scheme)) { 6689 return false; 6690 } 6691 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6692 } 6693 6694 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6695 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6696 int userId) { 6697 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6698 6699 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6700 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6701 candidates.size()); 6702 } 6703 6704 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6705 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6706 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6707 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6708 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6709 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6710 6711 synchronized (mPackages) { 6712 final int count = candidates.size(); 6713 // First, try to use linked apps. Partition the candidates into four lists: 6714 // one for the final results, one for the "do not use ever", one for "undefined status" 6715 // and finally one for "browser app type". 6716 for (int n=0; n<count; n++) { 6717 ResolveInfo info = candidates.get(n); 6718 String packageName = info.activityInfo.packageName; 6719 PackageSetting ps = mSettings.mPackages.get(packageName); 6720 if (ps != null) { 6721 // Add to the special match all list (Browser use case) 6722 if (info.handleAllWebDataURI) { 6723 matchAllList.add(info); 6724 continue; 6725 } 6726 // Try to get the status from User settings first 6727 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6728 int status = (int)(packedStatus >> 32); 6729 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6730 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6731 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6732 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6733 + " : linkgen=" + linkGeneration); 6734 } 6735 // Use link-enabled generation as preferredOrder, i.e. 6736 // prefer newly-enabled over earlier-enabled. 6737 info.preferredOrder = linkGeneration; 6738 alwaysList.add(info); 6739 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6740 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6741 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6742 } 6743 neverList.add(info); 6744 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6745 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6746 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6747 } 6748 alwaysAskList.add(info); 6749 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6750 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6751 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6752 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6753 } 6754 undefinedList.add(info); 6755 } 6756 } 6757 } 6758 6759 // We'll want to include browser possibilities in a few cases 6760 boolean includeBrowser = false; 6761 6762 // First try to add the "always" resolution(s) for the current user, if any 6763 if (alwaysList.size() > 0) { 6764 result.addAll(alwaysList); 6765 } else { 6766 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6767 result.addAll(undefinedList); 6768 // Maybe add one for the other profile. 6769 if (xpDomainInfo != null && ( 6770 xpDomainInfo.bestDomainVerificationStatus 6771 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6772 result.add(xpDomainInfo.resolveInfo); 6773 } 6774 includeBrowser = true; 6775 } 6776 6777 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6778 // If there were 'always' entries their preferred order has been set, so we also 6779 // back that off to make the alternatives equivalent 6780 if (alwaysAskList.size() > 0) { 6781 for (ResolveInfo i : result) { 6782 i.preferredOrder = 0; 6783 } 6784 result.addAll(alwaysAskList); 6785 includeBrowser = true; 6786 } 6787 6788 if (includeBrowser) { 6789 // Also add browsers (all of them or only the default one) 6790 if (DEBUG_DOMAIN_VERIFICATION) { 6791 Slog.v(TAG, " ...including browsers in candidate set"); 6792 } 6793 if ((matchFlags & MATCH_ALL) != 0) { 6794 result.addAll(matchAllList); 6795 } else { 6796 // Browser/generic handling case. If there's a default browser, go straight 6797 // to that (but only if there is no other higher-priority match). 6798 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6799 int maxMatchPrio = 0; 6800 ResolveInfo defaultBrowserMatch = null; 6801 final int numCandidates = matchAllList.size(); 6802 for (int n = 0; n < numCandidates; n++) { 6803 ResolveInfo info = matchAllList.get(n); 6804 // track the highest overall match priority... 6805 if (info.priority > maxMatchPrio) { 6806 maxMatchPrio = info.priority; 6807 } 6808 // ...and the highest-priority default browser match 6809 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6810 if (defaultBrowserMatch == null 6811 || (defaultBrowserMatch.priority < info.priority)) { 6812 if (debug) { 6813 Slog.v(TAG, "Considering default browser match " + info); 6814 } 6815 defaultBrowserMatch = info; 6816 } 6817 } 6818 } 6819 if (defaultBrowserMatch != null 6820 && defaultBrowserMatch.priority >= maxMatchPrio 6821 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6822 { 6823 if (debug) { 6824 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6825 } 6826 result.add(defaultBrowserMatch); 6827 } else { 6828 result.addAll(matchAllList); 6829 } 6830 } 6831 6832 // If there is nothing selected, add all candidates and remove the ones that the user 6833 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6834 if (result.size() == 0) { 6835 result.addAll(candidates); 6836 result.removeAll(neverList); 6837 } 6838 } 6839 } 6840 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6841 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6842 result.size()); 6843 for (ResolveInfo info : result) { 6844 Slog.v(TAG, " + " + info.activityInfo); 6845 } 6846 } 6847 return result; 6848 } 6849 6850 // Returns a packed value as a long: 6851 // 6852 // high 'int'-sized word: link status: undefined/ask/never/always. 6853 // low 'int'-sized word: relative priority among 'always' results. 6854 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6855 long result = ps.getDomainVerificationStatusForUser(userId); 6856 // if none available, get the master status 6857 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6858 if (ps.getIntentFilterVerificationInfo() != null) { 6859 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6860 } 6861 } 6862 return result; 6863 } 6864 6865 private ResolveInfo querySkipCurrentProfileIntents( 6866 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6867 int flags, int sourceUserId) { 6868 if (matchingFilters != null) { 6869 int size = matchingFilters.size(); 6870 for (int i = 0; i < size; i ++) { 6871 CrossProfileIntentFilter filter = matchingFilters.get(i); 6872 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6873 // Checking if there are activities in the target user that can handle the 6874 // intent. 6875 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6876 resolvedType, flags, sourceUserId); 6877 if (resolveInfo != null) { 6878 return resolveInfo; 6879 } 6880 } 6881 } 6882 } 6883 return null; 6884 } 6885 6886 // Return matching ResolveInfo in target user if any. 6887 private ResolveInfo queryCrossProfileIntents( 6888 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6889 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6890 if (matchingFilters != null) { 6891 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6892 // match the same intent. For performance reasons, it is better not to 6893 // run queryIntent twice for the same userId 6894 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6895 int size = matchingFilters.size(); 6896 for (int i = 0; i < size; i++) { 6897 CrossProfileIntentFilter filter = matchingFilters.get(i); 6898 int targetUserId = filter.getTargetUserId(); 6899 boolean skipCurrentProfile = 6900 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6901 boolean skipCurrentProfileIfNoMatchFound = 6902 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6903 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6904 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6905 // Checking if there are activities in the target user that can handle the 6906 // intent. 6907 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6908 resolvedType, flags, sourceUserId); 6909 if (resolveInfo != null) return resolveInfo; 6910 alreadyTriedUserIds.put(targetUserId, true); 6911 } 6912 } 6913 } 6914 return null; 6915 } 6916 6917 /** 6918 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6919 * will forward the intent to the filter's target user. 6920 * Otherwise, returns null. 6921 */ 6922 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6923 String resolvedType, int flags, int sourceUserId) { 6924 int targetUserId = filter.getTargetUserId(); 6925 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6926 resolvedType, flags, targetUserId); 6927 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6928 // If all the matches in the target profile are suspended, return null. 6929 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6930 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6931 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6932 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6933 targetUserId); 6934 } 6935 } 6936 } 6937 return null; 6938 } 6939 6940 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6941 int sourceUserId, int targetUserId) { 6942 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6943 long ident = Binder.clearCallingIdentity(); 6944 boolean targetIsProfile; 6945 try { 6946 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6947 } finally { 6948 Binder.restoreCallingIdentity(ident); 6949 } 6950 String className; 6951 if (targetIsProfile) { 6952 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6953 } else { 6954 className = FORWARD_INTENT_TO_PARENT; 6955 } 6956 ComponentName forwardingActivityComponentName = new ComponentName( 6957 mAndroidApplication.packageName, className); 6958 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6959 sourceUserId); 6960 if (!targetIsProfile) { 6961 forwardingActivityInfo.showUserIcon = targetUserId; 6962 forwardingResolveInfo.noResourceId = true; 6963 } 6964 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6965 forwardingResolveInfo.priority = 0; 6966 forwardingResolveInfo.preferredOrder = 0; 6967 forwardingResolveInfo.match = 0; 6968 forwardingResolveInfo.isDefault = true; 6969 forwardingResolveInfo.filter = filter; 6970 forwardingResolveInfo.targetUserId = targetUserId; 6971 return forwardingResolveInfo; 6972 } 6973 6974 @Override 6975 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6976 Intent[] specifics, String[] specificTypes, Intent intent, 6977 String resolvedType, int flags, int userId) { 6978 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6979 specificTypes, intent, resolvedType, flags, userId)); 6980 } 6981 6982 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6983 Intent[] specifics, String[] specificTypes, Intent intent, 6984 String resolvedType, int flags, int userId) { 6985 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6986 final int callingUid = Binder.getCallingUid(); 6987 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6988 false /*includeInstantApps*/); 6989 enforceCrossUserPermission(callingUid, userId, 6990 false /*requireFullPermission*/, false /*checkShell*/, 6991 "query intent activity options"); 6992 final String resultsAction = intent.getAction(); 6993 6994 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6995 | PackageManager.GET_RESOLVED_FILTER, userId); 6996 6997 if (DEBUG_INTENT_MATCHING) { 6998 Log.v(TAG, "Query " + intent + ": " + results); 6999 } 7000 7001 int specificsPos = 0; 7002 int N; 7003 7004 // todo: note that the algorithm used here is O(N^2). This 7005 // isn't a problem in our current environment, but if we start running 7006 // into situations where we have more than 5 or 10 matches then this 7007 // should probably be changed to something smarter... 7008 7009 // First we go through and resolve each of the specific items 7010 // that were supplied, taking care of removing any corresponding 7011 // duplicate items in the generic resolve list. 7012 if (specifics != null) { 7013 for (int i=0; i<specifics.length; i++) { 7014 final Intent sintent = specifics[i]; 7015 if (sintent == null) { 7016 continue; 7017 } 7018 7019 if (DEBUG_INTENT_MATCHING) { 7020 Log.v(TAG, "Specific #" + i + ": " + sintent); 7021 } 7022 7023 String action = sintent.getAction(); 7024 if (resultsAction != null && resultsAction.equals(action)) { 7025 // If this action was explicitly requested, then don't 7026 // remove things that have it. 7027 action = null; 7028 } 7029 7030 ResolveInfo ri = null; 7031 ActivityInfo ai = null; 7032 7033 ComponentName comp = sintent.getComponent(); 7034 if (comp == null) { 7035 ri = resolveIntent( 7036 sintent, 7037 specificTypes != null ? specificTypes[i] : null, 7038 flags, userId); 7039 if (ri == null) { 7040 continue; 7041 } 7042 if (ri == mResolveInfo) { 7043 // ACK! Must do something better with this. 7044 } 7045 ai = ri.activityInfo; 7046 comp = new ComponentName(ai.applicationInfo.packageName, 7047 ai.name); 7048 } else { 7049 ai = getActivityInfo(comp, flags, userId); 7050 if (ai == null) { 7051 continue; 7052 } 7053 } 7054 7055 // Look for any generic query activities that are duplicates 7056 // of this specific one, and remove them from the results. 7057 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7058 N = results.size(); 7059 int j; 7060 for (j=specificsPos; j<N; j++) { 7061 ResolveInfo sri = results.get(j); 7062 if ((sri.activityInfo.name.equals(comp.getClassName()) 7063 && sri.activityInfo.applicationInfo.packageName.equals( 7064 comp.getPackageName())) 7065 || (action != null && sri.filter.matchAction(action))) { 7066 results.remove(j); 7067 if (DEBUG_INTENT_MATCHING) Log.v( 7068 TAG, "Removing duplicate item from " + j 7069 + " due to specific " + specificsPos); 7070 if (ri == null) { 7071 ri = sri; 7072 } 7073 j--; 7074 N--; 7075 } 7076 } 7077 7078 // Add this specific item to its proper place. 7079 if (ri == null) { 7080 ri = new ResolveInfo(); 7081 ri.activityInfo = ai; 7082 } 7083 results.add(specificsPos, ri); 7084 ri.specificIndex = i; 7085 specificsPos++; 7086 } 7087 } 7088 7089 // Now we go through the remaining generic results and remove any 7090 // duplicate actions that are found here. 7091 N = results.size(); 7092 for (int i=specificsPos; i<N-1; i++) { 7093 final ResolveInfo rii = results.get(i); 7094 if (rii.filter == null) { 7095 continue; 7096 } 7097 7098 // Iterate over all of the actions of this result's intent 7099 // filter... typically this should be just one. 7100 final Iterator<String> it = rii.filter.actionsIterator(); 7101 if (it == null) { 7102 continue; 7103 } 7104 while (it.hasNext()) { 7105 final String action = it.next(); 7106 if (resultsAction != null && resultsAction.equals(action)) { 7107 // If this action was explicitly requested, then don't 7108 // remove things that have it. 7109 continue; 7110 } 7111 for (int j=i+1; j<N; j++) { 7112 final ResolveInfo rij = results.get(j); 7113 if (rij.filter != null && rij.filter.hasAction(action)) { 7114 results.remove(j); 7115 if (DEBUG_INTENT_MATCHING) Log.v( 7116 TAG, "Removing duplicate item from " + j 7117 + " due to action " + action + " at " + i); 7118 j--; 7119 N--; 7120 } 7121 } 7122 } 7123 7124 // If the caller didn't request filter information, drop it now 7125 // so we don't have to marshall/unmarshall it. 7126 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7127 rii.filter = null; 7128 } 7129 } 7130 7131 // Filter out the caller activity if so requested. 7132 if (caller != null) { 7133 N = results.size(); 7134 for (int i=0; i<N; i++) { 7135 ActivityInfo ainfo = results.get(i).activityInfo; 7136 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7137 && caller.getClassName().equals(ainfo.name)) { 7138 results.remove(i); 7139 break; 7140 } 7141 } 7142 } 7143 7144 // If the caller didn't request filter information, 7145 // drop them now so we don't have to 7146 // marshall/unmarshall it. 7147 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7148 N = results.size(); 7149 for (int i=0; i<N; i++) { 7150 results.get(i).filter = null; 7151 } 7152 } 7153 7154 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7155 return results; 7156 } 7157 7158 @Override 7159 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7160 String resolvedType, int flags, int userId) { 7161 return new ParceledListSlice<>( 7162 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7163 } 7164 7165 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7166 String resolvedType, int flags, int userId) { 7167 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7168 final int callingUid = Binder.getCallingUid(); 7169 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7170 false /*includeInstantApps*/); 7171 ComponentName comp = intent.getComponent(); 7172 if (comp == null) { 7173 if (intent.getSelector() != null) { 7174 intent = intent.getSelector(); 7175 comp = intent.getComponent(); 7176 } 7177 } 7178 if (comp != null) { 7179 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7180 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7181 if (ai != null) { 7182 ResolveInfo ri = new ResolveInfo(); 7183 ri.activityInfo = ai; 7184 list.add(ri); 7185 } 7186 return list; 7187 } 7188 7189 // reader 7190 synchronized (mPackages) { 7191 String pkgName = intent.getPackage(); 7192 if (pkgName == null) { 7193 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7194 } 7195 final PackageParser.Package pkg = mPackages.get(pkgName); 7196 if (pkg != null) { 7197 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7198 userId); 7199 } 7200 return Collections.emptyList(); 7201 } 7202 } 7203 7204 @Override 7205 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7206 final int callingUid = Binder.getCallingUid(); 7207 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7208 } 7209 7210 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7211 int userId, int callingUid) { 7212 if (!sUserManager.exists(userId)) return null; 7213 flags = updateFlagsForResolve( 7214 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7215 List<ResolveInfo> query = queryIntentServicesInternal( 7216 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7217 if (query != null) { 7218 if (query.size() >= 1) { 7219 // If there is more than one service with the same priority, 7220 // just arbitrarily pick the first one. 7221 return query.get(0); 7222 } 7223 } 7224 return null; 7225 } 7226 7227 @Override 7228 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7229 String resolvedType, int flags, int userId) { 7230 final int callingUid = Binder.getCallingUid(); 7231 return new ParceledListSlice<>(queryIntentServicesInternal( 7232 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7233 } 7234 7235 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7236 String resolvedType, int flags, int userId, int callingUid, 7237 boolean includeInstantApps) { 7238 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7239 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7240 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7241 ComponentName comp = intent.getComponent(); 7242 if (comp == null) { 7243 if (intent.getSelector() != null) { 7244 intent = intent.getSelector(); 7245 comp = intent.getComponent(); 7246 } 7247 } 7248 if (comp != null) { 7249 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7250 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7251 if (si != null) { 7252 // When specifying an explicit component, we prevent the service from being 7253 // used when either 1) the service is in an instant application and the 7254 // caller is not the same instant application or 2) the calling package is 7255 // ephemeral and the activity is not visible to ephemeral applications. 7256 final boolean matchInstantApp = 7257 (flags & PackageManager.MATCH_INSTANT) != 0; 7258 final boolean matchVisibleToInstantAppOnly = 7259 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7260 final boolean isCallerInstantApp = 7261 instantAppPkgName != null; 7262 final boolean isTargetSameInstantApp = 7263 comp.getPackageName().equals(instantAppPkgName); 7264 final boolean isTargetInstantApp = 7265 (si.applicationInfo.privateFlags 7266 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7267 final boolean isTargetHiddenFromInstantApp = 7268 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7269 final boolean blockResolution = 7270 !isTargetSameInstantApp 7271 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7272 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7273 && isTargetHiddenFromInstantApp)); 7274 if (!blockResolution) { 7275 final ResolveInfo ri = new ResolveInfo(); 7276 ri.serviceInfo = si; 7277 list.add(ri); 7278 } 7279 } 7280 return list; 7281 } 7282 7283 // reader 7284 synchronized (mPackages) { 7285 String pkgName = intent.getPackage(); 7286 if (pkgName == null) { 7287 return applyPostServiceResolutionFilter( 7288 mServices.queryIntent(intent, resolvedType, flags, userId), 7289 instantAppPkgName); 7290 } 7291 final PackageParser.Package pkg = mPackages.get(pkgName); 7292 if (pkg != null) { 7293 return applyPostServiceResolutionFilter( 7294 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7295 userId), 7296 instantAppPkgName); 7297 } 7298 return Collections.emptyList(); 7299 } 7300 } 7301 7302 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7303 String instantAppPkgName) { 7304 // TODO: When adding on-demand split support for non-instant apps, remove this check 7305 // and always apply post filtering 7306 if (instantAppPkgName == null) { 7307 return resolveInfos; 7308 } 7309 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7310 final ResolveInfo info = resolveInfos.get(i); 7311 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7312 // allow services that are defined in the provided package 7313 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7314 if (info.serviceInfo.splitName != null 7315 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7316 info.serviceInfo.splitName)) { 7317 // requested service is defined in a split that hasn't been installed yet. 7318 // add the installer to the resolve list 7319 if (DEBUG_EPHEMERAL) { 7320 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7321 } 7322 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7323 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7324 info.serviceInfo.packageName, info.serviceInfo.splitName, 7325 info.serviceInfo.applicationInfo.versionCode); 7326 // make sure this resolver is the default 7327 installerInfo.isDefault = true; 7328 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7329 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7330 // add a non-generic filter 7331 installerInfo.filter = new IntentFilter(); 7332 // load resources from the correct package 7333 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7334 resolveInfos.set(i, installerInfo); 7335 } 7336 continue; 7337 } 7338 // allow services that have been explicitly exposed to ephemeral apps 7339 if (!isEphemeralApp 7340 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7341 continue; 7342 } 7343 resolveInfos.remove(i); 7344 } 7345 return resolveInfos; 7346 } 7347 7348 @Override 7349 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7350 String resolvedType, int flags, int userId) { 7351 return new ParceledListSlice<>( 7352 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7353 } 7354 7355 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7356 Intent intent, String resolvedType, int flags, int userId) { 7357 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7358 final int callingUid = Binder.getCallingUid(); 7359 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7360 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7361 false /*includeInstantApps*/); 7362 ComponentName comp = intent.getComponent(); 7363 if (comp == null) { 7364 if (intent.getSelector() != null) { 7365 intent = intent.getSelector(); 7366 comp = intent.getComponent(); 7367 } 7368 } 7369 if (comp != null) { 7370 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7371 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7372 if (pi != null) { 7373 // When specifying an explicit component, we prevent the provider from being 7374 // used when either 1) the provider is in an instant application and the 7375 // caller is not the same instant application or 2) the calling package is an 7376 // instant application and the provider is not visible to instant applications. 7377 final boolean matchInstantApp = 7378 (flags & PackageManager.MATCH_INSTANT) != 0; 7379 final boolean matchVisibleToInstantAppOnly = 7380 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7381 final boolean isCallerInstantApp = 7382 instantAppPkgName != null; 7383 final boolean isTargetSameInstantApp = 7384 comp.getPackageName().equals(instantAppPkgName); 7385 final boolean isTargetInstantApp = 7386 (pi.applicationInfo.privateFlags 7387 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7388 final boolean isTargetHiddenFromInstantApp = 7389 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7390 final boolean blockResolution = 7391 !isTargetSameInstantApp 7392 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7393 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7394 && isTargetHiddenFromInstantApp)); 7395 if (!blockResolution) { 7396 final ResolveInfo ri = new ResolveInfo(); 7397 ri.providerInfo = pi; 7398 list.add(ri); 7399 } 7400 } 7401 return list; 7402 } 7403 7404 // reader 7405 synchronized (mPackages) { 7406 String pkgName = intent.getPackage(); 7407 if (pkgName == null) { 7408 return applyPostContentProviderResolutionFilter( 7409 mProviders.queryIntent(intent, resolvedType, flags, userId), 7410 instantAppPkgName); 7411 } 7412 final PackageParser.Package pkg = mPackages.get(pkgName); 7413 if (pkg != null) { 7414 return applyPostContentProviderResolutionFilter( 7415 mProviders.queryIntentForPackage( 7416 intent, resolvedType, flags, pkg.providers, userId), 7417 instantAppPkgName); 7418 } 7419 return Collections.emptyList(); 7420 } 7421 } 7422 7423 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7424 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7425 // TODO: When adding on-demand split support for non-instant applications, remove 7426 // this check and always apply post filtering 7427 if (instantAppPkgName == null) { 7428 return resolveInfos; 7429 } 7430 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7431 final ResolveInfo info = resolveInfos.get(i); 7432 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7433 // allow providers that are defined in the provided package 7434 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7435 if (info.providerInfo.splitName != null 7436 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7437 info.providerInfo.splitName)) { 7438 // requested provider is defined in a split that hasn't been installed yet. 7439 // add the installer to the resolve list 7440 if (DEBUG_EPHEMERAL) { 7441 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7442 } 7443 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7444 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7445 info.providerInfo.packageName, info.providerInfo.splitName, 7446 info.providerInfo.applicationInfo.versionCode); 7447 // make sure this resolver is the default 7448 installerInfo.isDefault = true; 7449 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7450 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7451 // add a non-generic filter 7452 installerInfo.filter = new IntentFilter(); 7453 // load resources from the correct package 7454 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7455 resolveInfos.set(i, installerInfo); 7456 } 7457 continue; 7458 } 7459 // allow providers that have been explicitly exposed to instant applications 7460 if (!isEphemeralApp 7461 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7462 continue; 7463 } 7464 resolveInfos.remove(i); 7465 } 7466 return resolveInfos; 7467 } 7468 7469 @Override 7470 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7471 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7472 flags = updateFlagsForPackage(flags, userId, null); 7473 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7474 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7475 true /* requireFullPermission */, false /* checkShell */, 7476 "get installed packages"); 7477 7478 // writer 7479 synchronized (mPackages) { 7480 ArrayList<PackageInfo> list; 7481 if (listUninstalled) { 7482 list = new ArrayList<>(mSettings.mPackages.size()); 7483 for (PackageSetting ps : mSettings.mPackages.values()) { 7484 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7485 continue; 7486 } 7487 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7488 if (pi != null) { 7489 list.add(pi); 7490 } 7491 } 7492 } else { 7493 list = new ArrayList<>(mPackages.size()); 7494 for (PackageParser.Package p : mPackages.values()) { 7495 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7496 Binder.getCallingUid(), userId)) { 7497 continue; 7498 } 7499 final PackageInfo pi = generatePackageInfo((PackageSetting) 7500 p.mExtras, flags, userId); 7501 if (pi != null) { 7502 list.add(pi); 7503 } 7504 } 7505 } 7506 7507 return new ParceledListSlice<>(list); 7508 } 7509 } 7510 7511 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7512 String[] permissions, boolean[] tmp, int flags, int userId) { 7513 int numMatch = 0; 7514 final PermissionsState permissionsState = ps.getPermissionsState(); 7515 for (int i=0; i<permissions.length; i++) { 7516 final String permission = permissions[i]; 7517 if (permissionsState.hasPermission(permission, userId)) { 7518 tmp[i] = true; 7519 numMatch++; 7520 } else { 7521 tmp[i] = false; 7522 } 7523 } 7524 if (numMatch == 0) { 7525 return; 7526 } 7527 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7528 7529 // The above might return null in cases of uninstalled apps or install-state 7530 // skew across users/profiles. 7531 if (pi != null) { 7532 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7533 if (numMatch == permissions.length) { 7534 pi.requestedPermissions = permissions; 7535 } else { 7536 pi.requestedPermissions = new String[numMatch]; 7537 numMatch = 0; 7538 for (int i=0; i<permissions.length; i++) { 7539 if (tmp[i]) { 7540 pi.requestedPermissions[numMatch] = permissions[i]; 7541 numMatch++; 7542 } 7543 } 7544 } 7545 } 7546 list.add(pi); 7547 } 7548 } 7549 7550 @Override 7551 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7552 String[] permissions, int flags, int userId) { 7553 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7554 flags = updateFlagsForPackage(flags, userId, permissions); 7555 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7556 true /* requireFullPermission */, false /* checkShell */, 7557 "get packages holding permissions"); 7558 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7559 7560 // writer 7561 synchronized (mPackages) { 7562 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7563 boolean[] tmpBools = new boolean[permissions.length]; 7564 if (listUninstalled) { 7565 for (PackageSetting ps : mSettings.mPackages.values()) { 7566 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7567 userId); 7568 } 7569 } else { 7570 for (PackageParser.Package pkg : mPackages.values()) { 7571 PackageSetting ps = (PackageSetting)pkg.mExtras; 7572 if (ps != null) { 7573 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7574 userId); 7575 } 7576 } 7577 } 7578 7579 return new ParceledListSlice<PackageInfo>(list); 7580 } 7581 } 7582 7583 @Override 7584 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7585 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7586 flags = updateFlagsForApplication(flags, userId, null); 7587 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7588 7589 // writer 7590 synchronized (mPackages) { 7591 ArrayList<ApplicationInfo> list; 7592 if (listUninstalled) { 7593 list = new ArrayList<>(mSettings.mPackages.size()); 7594 for (PackageSetting ps : mSettings.mPackages.values()) { 7595 ApplicationInfo ai; 7596 int effectiveFlags = flags; 7597 if (ps.isSystem()) { 7598 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7599 } 7600 if (ps.pkg != null) { 7601 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7602 continue; 7603 } 7604 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7605 ps.readUserState(userId), userId); 7606 if (ai != null) { 7607 rebaseEnabledOverlays(ai, userId); 7608 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7609 } 7610 } else { 7611 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7612 // and already converts to externally visible package name 7613 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7614 Binder.getCallingUid(), effectiveFlags, userId); 7615 } 7616 if (ai != null) { 7617 list.add(ai); 7618 } 7619 } 7620 } else { 7621 list = new ArrayList<>(mPackages.size()); 7622 for (PackageParser.Package p : mPackages.values()) { 7623 if (p.mExtras != null) { 7624 PackageSetting ps = (PackageSetting) p.mExtras; 7625 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7626 continue; 7627 } 7628 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7629 ps.readUserState(userId), userId); 7630 if (ai != null) { 7631 rebaseEnabledOverlays(ai, userId); 7632 ai.packageName = resolveExternalPackageNameLPr(p); 7633 list.add(ai); 7634 } 7635 } 7636 } 7637 } 7638 7639 return new ParceledListSlice<>(list); 7640 } 7641 } 7642 7643 @Override 7644 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7645 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7646 return null; 7647 } 7648 7649 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7650 "getEphemeralApplications"); 7651 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7652 true /* requireFullPermission */, false /* checkShell */, 7653 "getEphemeralApplications"); 7654 synchronized (mPackages) { 7655 List<InstantAppInfo> instantApps = mInstantAppRegistry 7656 .getInstantAppsLPr(userId); 7657 if (instantApps != null) { 7658 return new ParceledListSlice<>(instantApps); 7659 } 7660 } 7661 return null; 7662 } 7663 7664 @Override 7665 public boolean isInstantApp(String packageName, int userId) { 7666 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7667 true /* requireFullPermission */, false /* checkShell */, 7668 "isInstantApp"); 7669 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7670 return false; 7671 } 7672 int uid = Binder.getCallingUid(); 7673 if (Process.isIsolated(uid)) { 7674 uid = mIsolatedOwners.get(uid); 7675 } 7676 7677 synchronized (mPackages) { 7678 final PackageSetting ps = mSettings.mPackages.get(packageName); 7679 PackageParser.Package pkg = mPackages.get(packageName); 7680 final boolean returnAllowed = 7681 ps != null 7682 && (isCallerSameApp(packageName, uid) 7683 || mContext.checkCallingOrSelfPermission( 7684 android.Manifest.permission.ACCESS_INSTANT_APPS) 7685 == PERMISSION_GRANTED 7686 || mInstantAppRegistry.isInstantAccessGranted( 7687 userId, UserHandle.getAppId(uid), ps.appId)); 7688 if (returnAllowed) { 7689 return ps.getInstantApp(userId); 7690 } 7691 } 7692 return false; 7693 } 7694 7695 @Override 7696 public byte[] getInstantAppCookie(String packageName, int userId) { 7697 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7698 return null; 7699 } 7700 7701 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7702 true /* requireFullPermission */, false /* checkShell */, 7703 "getInstantAppCookie"); 7704 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7705 return null; 7706 } 7707 synchronized (mPackages) { 7708 return mInstantAppRegistry.getInstantAppCookieLPw( 7709 packageName, userId); 7710 } 7711 } 7712 7713 @Override 7714 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7715 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7716 return true; 7717 } 7718 7719 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7720 true /* requireFullPermission */, true /* checkShell */, 7721 "setInstantAppCookie"); 7722 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7723 return false; 7724 } 7725 synchronized (mPackages) { 7726 return mInstantAppRegistry.setInstantAppCookieLPw( 7727 packageName, cookie, userId); 7728 } 7729 } 7730 7731 @Override 7732 public Bitmap getInstantAppIcon(String packageName, int userId) { 7733 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7734 return null; 7735 } 7736 7737 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7738 "getInstantAppIcon"); 7739 7740 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7741 true /* requireFullPermission */, false /* checkShell */, 7742 "getInstantAppIcon"); 7743 7744 synchronized (mPackages) { 7745 return mInstantAppRegistry.getInstantAppIconLPw( 7746 packageName, userId); 7747 } 7748 } 7749 7750 private boolean isCallerSameApp(String packageName, int uid) { 7751 PackageParser.Package pkg = mPackages.get(packageName); 7752 return pkg != null 7753 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7754 } 7755 7756 @Override 7757 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7758 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7759 } 7760 7761 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7762 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7763 7764 // reader 7765 synchronized (mPackages) { 7766 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7767 final int userId = UserHandle.getCallingUserId(); 7768 while (i.hasNext()) { 7769 final PackageParser.Package p = i.next(); 7770 if (p.applicationInfo == null) continue; 7771 7772 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7773 && !p.applicationInfo.isDirectBootAware(); 7774 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7775 && p.applicationInfo.isDirectBootAware(); 7776 7777 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7778 && (!mSafeMode || isSystemApp(p)) 7779 && (matchesUnaware || matchesAware)) { 7780 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7781 if (ps != null) { 7782 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7783 ps.readUserState(userId), userId); 7784 if (ai != null) { 7785 rebaseEnabledOverlays(ai, userId); 7786 finalList.add(ai); 7787 } 7788 } 7789 } 7790 } 7791 } 7792 7793 return finalList; 7794 } 7795 7796 @Override 7797 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7798 if (!sUserManager.exists(userId)) return null; 7799 flags = updateFlagsForComponent(flags, userId, name); 7800 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 7801 // reader 7802 synchronized (mPackages) { 7803 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7804 PackageSetting ps = provider != null 7805 ? mSettings.mPackages.get(provider.owner.packageName) 7806 : null; 7807 if (ps != null) { 7808 final boolean isInstantApp = ps.getInstantApp(userId); 7809 // normal application; filter out instant application provider 7810 if (instantAppPkgName == null && isInstantApp) { 7811 return null; 7812 } 7813 // instant application; filter out other instant applications 7814 if (instantAppPkgName != null 7815 && isInstantApp 7816 && !provider.owner.packageName.equals(instantAppPkgName)) { 7817 return null; 7818 } 7819 // instant application; filter out non-exposed provider 7820 if (instantAppPkgName != null 7821 && !isInstantApp 7822 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 7823 return null; 7824 } 7825 // provider not enabled 7826 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 7827 return null; 7828 } 7829 return PackageParser.generateProviderInfo( 7830 provider, flags, ps.readUserState(userId), userId); 7831 } 7832 return null; 7833 } 7834 } 7835 7836 /** 7837 * @deprecated 7838 */ 7839 @Deprecated 7840 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7841 // reader 7842 synchronized (mPackages) { 7843 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7844 .entrySet().iterator(); 7845 final int userId = UserHandle.getCallingUserId(); 7846 while (i.hasNext()) { 7847 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7848 PackageParser.Provider p = entry.getValue(); 7849 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7850 7851 if (ps != null && p.syncable 7852 && (!mSafeMode || (p.info.applicationInfo.flags 7853 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7854 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7855 ps.readUserState(userId), userId); 7856 if (info != null) { 7857 outNames.add(entry.getKey()); 7858 outInfo.add(info); 7859 } 7860 } 7861 } 7862 } 7863 } 7864 7865 @Override 7866 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7867 int uid, int flags, String metaDataKey) { 7868 final int userId = processName != null ? UserHandle.getUserId(uid) 7869 : UserHandle.getCallingUserId(); 7870 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7871 flags = updateFlagsForComponent(flags, userId, processName); 7872 7873 ArrayList<ProviderInfo> finalList = null; 7874 // reader 7875 synchronized (mPackages) { 7876 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7877 while (i.hasNext()) { 7878 final PackageParser.Provider p = i.next(); 7879 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7880 if (ps != null && p.info.authority != null 7881 && (processName == null 7882 || (p.info.processName.equals(processName) 7883 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7884 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7885 7886 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7887 // parameter. 7888 if (metaDataKey != null 7889 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7890 continue; 7891 } 7892 7893 if (finalList == null) { 7894 finalList = new ArrayList<ProviderInfo>(3); 7895 } 7896 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7897 ps.readUserState(userId), userId); 7898 if (info != null) { 7899 finalList.add(info); 7900 } 7901 } 7902 } 7903 } 7904 7905 if (finalList != null) { 7906 Collections.sort(finalList, mProviderInitOrderSorter); 7907 return new ParceledListSlice<ProviderInfo>(finalList); 7908 } 7909 7910 return ParceledListSlice.emptyList(); 7911 } 7912 7913 @Override 7914 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7915 // reader 7916 synchronized (mPackages) { 7917 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7918 return PackageParser.generateInstrumentationInfo(i, flags); 7919 } 7920 } 7921 7922 @Override 7923 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7924 String targetPackage, int flags) { 7925 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7926 } 7927 7928 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7929 int flags) { 7930 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7931 7932 // reader 7933 synchronized (mPackages) { 7934 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7935 while (i.hasNext()) { 7936 final PackageParser.Instrumentation p = i.next(); 7937 if (targetPackage == null 7938 || targetPackage.equals(p.info.targetPackage)) { 7939 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7940 flags); 7941 if (ii != null) { 7942 finalList.add(ii); 7943 } 7944 } 7945 } 7946 } 7947 7948 return finalList; 7949 } 7950 7951 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7952 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7953 try { 7954 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7955 } finally { 7956 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7957 } 7958 } 7959 7960 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7961 final File[] files = dir.listFiles(); 7962 if (ArrayUtils.isEmpty(files)) { 7963 Log.d(TAG, "No files in app dir " + dir); 7964 return; 7965 } 7966 7967 if (DEBUG_PACKAGE_SCANNING) { 7968 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7969 + " flags=0x" + Integer.toHexString(parseFlags)); 7970 } 7971 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7972 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 7973 mParallelPackageParserCallback); 7974 7975 // Submit files for parsing in parallel 7976 int fileCount = 0; 7977 for (File file : files) { 7978 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7979 && !PackageInstallerService.isStageName(file.getName()); 7980 if (!isPackage) { 7981 // Ignore entries which are not packages 7982 continue; 7983 } 7984 parallelPackageParser.submit(file, parseFlags); 7985 fileCount++; 7986 } 7987 7988 // Process results one by one 7989 for (; fileCount > 0; fileCount--) { 7990 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7991 Throwable throwable = parseResult.throwable; 7992 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7993 7994 if (throwable == null) { 7995 // Static shared libraries have synthetic package names 7996 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7997 renameStaticSharedLibraryPackage(parseResult.pkg); 7998 } 7999 try { 8000 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8001 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 8002 currentTime, null); 8003 } 8004 } catch (PackageManagerException e) { 8005 errorCode = e.error; 8006 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8007 } 8008 } else if (throwable instanceof PackageParser.PackageParserException) { 8009 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8010 throwable; 8011 errorCode = e.error; 8012 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8013 } else { 8014 throw new IllegalStateException("Unexpected exception occurred while parsing " 8015 + parseResult.scanFile, throwable); 8016 } 8017 8018 // Delete invalid userdata apps 8019 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 8020 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8021 logCriticalInfo(Log.WARN, 8022 "Deleting invalid package at " + parseResult.scanFile); 8023 removeCodePathLI(parseResult.scanFile); 8024 } 8025 } 8026 parallelPackageParser.close(); 8027 } 8028 8029 private static File getSettingsProblemFile() { 8030 File dataDir = Environment.getDataDirectory(); 8031 File systemDir = new File(dataDir, "system"); 8032 File fname = new File(systemDir, "uiderrors.txt"); 8033 return fname; 8034 } 8035 8036 static void reportSettingsProblem(int priority, String msg) { 8037 logCriticalInfo(priority, msg); 8038 } 8039 8040 public static void logCriticalInfo(int priority, String msg) { 8041 Slog.println(priority, TAG, msg); 8042 EventLogTags.writePmCriticalInfo(msg); 8043 try { 8044 File fname = getSettingsProblemFile(); 8045 FileOutputStream out = new FileOutputStream(fname, true); 8046 PrintWriter pw = new FastPrintWriter(out); 8047 SimpleDateFormat formatter = new SimpleDateFormat(); 8048 String dateString = formatter.format(new Date(System.currentTimeMillis())); 8049 pw.println(dateString + ": " + msg); 8050 pw.close(); 8051 FileUtils.setPermissions( 8052 fname.toString(), 8053 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 8054 -1, -1); 8055 } catch (java.io.IOException e) { 8056 } 8057 } 8058 8059 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 8060 if (srcFile.isDirectory()) { 8061 final File baseFile = new File(pkg.baseCodePath); 8062 long maxModifiedTime = baseFile.lastModified(); 8063 if (pkg.splitCodePaths != null) { 8064 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 8065 final File splitFile = new File(pkg.splitCodePaths[i]); 8066 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 8067 } 8068 } 8069 return maxModifiedTime; 8070 } 8071 return srcFile.lastModified(); 8072 } 8073 8074 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 8075 final int policyFlags) throws PackageManagerException { 8076 // When upgrading from pre-N MR1, verify the package time stamp using the package 8077 // directory and not the APK file. 8078 final long lastModifiedTime = mIsPreNMR1Upgrade 8079 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 8080 if (ps != null 8081 && ps.codePath.equals(srcFile) 8082 && ps.timeStamp == lastModifiedTime 8083 && !isCompatSignatureUpdateNeeded(pkg) 8084 && !isRecoverSignatureUpdateNeeded(pkg)) { 8085 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 8086 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8087 ArraySet<PublicKey> signingKs; 8088 synchronized (mPackages) { 8089 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 8090 } 8091 if (ps.signatures.mSignatures != null 8092 && ps.signatures.mSignatures.length != 0 8093 && signingKs != null) { 8094 // Optimization: reuse the existing cached certificates 8095 // if the package appears to be unchanged. 8096 pkg.mSignatures = ps.signatures.mSignatures; 8097 pkg.mSigningKeys = signingKs; 8098 return; 8099 } 8100 8101 Slog.w(TAG, "PackageSetting for " + ps.name 8102 + " is missing signatures. Collecting certs again to recover them."); 8103 } else { 8104 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 8105 } 8106 8107 try { 8108 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8109 PackageParser.collectCertificates(pkg, policyFlags); 8110 } catch (PackageParserException e) { 8111 throw PackageManagerException.from(e); 8112 } finally { 8113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8114 } 8115 } 8116 8117 /** 8118 * Traces a package scan. 8119 * @see #scanPackageLI(File, int, int, long, UserHandle) 8120 */ 8121 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8122 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8123 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8124 try { 8125 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8126 } finally { 8127 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8128 } 8129 } 8130 8131 /** 8132 * Scans a package and returns the newly parsed package. 8133 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8134 */ 8135 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8136 long currentTime, UserHandle user) throws PackageManagerException { 8137 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8138 PackageParser pp = new PackageParser(); 8139 pp.setSeparateProcesses(mSeparateProcesses); 8140 pp.setOnlyCoreApps(mOnlyCore); 8141 pp.setDisplayMetrics(mMetrics); 8142 pp.setCallback(mPackageParserCallback); 8143 8144 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 8145 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 8146 } 8147 8148 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8149 final PackageParser.Package pkg; 8150 try { 8151 pkg = pp.parsePackage(scanFile, parseFlags); 8152 } catch (PackageParserException e) { 8153 throw PackageManagerException.from(e); 8154 } finally { 8155 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8156 } 8157 8158 // Static shared libraries have synthetic package names 8159 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8160 renameStaticSharedLibraryPackage(pkg); 8161 } 8162 8163 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 8164 } 8165 8166 /** 8167 * Scans a package and returns the newly parsed package. 8168 * @throws PackageManagerException on a parse error. 8169 */ 8170 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 8171 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8172 throws PackageManagerException { 8173 // If the package has children and this is the first dive in the function 8174 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8175 // packages (parent and children) would be successfully scanned before the 8176 // actual scan since scanning mutates internal state and we want to atomically 8177 // install the package and its children. 8178 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8179 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8180 scanFlags |= SCAN_CHECK_ONLY; 8181 } 8182 } else { 8183 scanFlags &= ~SCAN_CHECK_ONLY; 8184 } 8185 8186 // Scan the parent 8187 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 8188 scanFlags, currentTime, user); 8189 8190 // Scan the children 8191 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8192 for (int i = 0; i < childCount; i++) { 8193 PackageParser.Package childPackage = pkg.childPackages.get(i); 8194 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 8195 currentTime, user); 8196 } 8197 8198 8199 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8200 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 8201 } 8202 8203 return scannedPkg; 8204 } 8205 8206 /** 8207 * Scans a package and returns the newly parsed package. 8208 * @throws PackageManagerException on a parse error. 8209 */ 8210 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 8211 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8212 throws PackageManagerException { 8213 PackageSetting ps = null; 8214 PackageSetting updatedPkg; 8215 // reader 8216 synchronized (mPackages) { 8217 // Look to see if we already know about this package. 8218 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 8219 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 8220 // This package has been renamed to its original name. Let's 8221 // use that. 8222 ps = mSettings.getPackageLPr(oldName); 8223 } 8224 // If there was no original package, see one for the real package name. 8225 if (ps == null) { 8226 ps = mSettings.getPackageLPr(pkg.packageName); 8227 } 8228 // Check to see if this package could be hiding/updating a system 8229 // package. Must look for it either under the original or real 8230 // package name depending on our state. 8231 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 8232 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 8233 8234 // If this is a package we don't know about on the system partition, we 8235 // may need to remove disabled child packages on the system partition 8236 // or may need to not add child packages if the parent apk is updated 8237 // on the data partition and no longer defines this child package. 8238 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8239 // If this is a parent package for an updated system app and this system 8240 // app got an OTA update which no longer defines some of the child packages 8241 // we have to prune them from the disabled system packages. 8242 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8243 if (disabledPs != null) { 8244 final int scannedChildCount = (pkg.childPackages != null) 8245 ? pkg.childPackages.size() : 0; 8246 final int disabledChildCount = disabledPs.childPackageNames != null 8247 ? disabledPs.childPackageNames.size() : 0; 8248 for (int i = 0; i < disabledChildCount; i++) { 8249 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 8250 boolean disabledPackageAvailable = false; 8251 for (int j = 0; j < scannedChildCount; j++) { 8252 PackageParser.Package childPkg = pkg.childPackages.get(j); 8253 if (childPkg.packageName.equals(disabledChildPackageName)) { 8254 disabledPackageAvailable = true; 8255 break; 8256 } 8257 } 8258 if (!disabledPackageAvailable) { 8259 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8260 } 8261 } 8262 } 8263 } 8264 } 8265 8266 boolean updatedPkgBetter = false; 8267 // First check if this is a system package that may involve an update 8268 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8269 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8270 // it needs to drop FLAG_PRIVILEGED. 8271 if (locationIsPrivileged(scanFile)) { 8272 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8273 } else { 8274 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8275 } 8276 8277 if (ps != null && !ps.codePath.equals(scanFile)) { 8278 // The path has changed from what was last scanned... check the 8279 // version of the new path against what we have stored to determine 8280 // what to do. 8281 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8282 if (pkg.mVersionCode <= ps.versionCode) { 8283 // The system package has been updated and the code path does not match 8284 // Ignore entry. Skip it. 8285 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8286 + " ignored: updated version " + ps.versionCode 8287 + " better than this " + pkg.mVersionCode); 8288 if (!updatedPkg.codePath.equals(scanFile)) { 8289 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8290 + ps.name + " changing from " + updatedPkg.codePathString 8291 + " to " + scanFile); 8292 updatedPkg.codePath = scanFile; 8293 updatedPkg.codePathString = scanFile.toString(); 8294 updatedPkg.resourcePath = scanFile; 8295 updatedPkg.resourcePathString = scanFile.toString(); 8296 } 8297 updatedPkg.pkg = pkg; 8298 updatedPkg.versionCode = pkg.mVersionCode; 8299 8300 // Update the disabled system child packages to point to the package too. 8301 final int childCount = updatedPkg.childPackageNames != null 8302 ? updatedPkg.childPackageNames.size() : 0; 8303 for (int i = 0; i < childCount; i++) { 8304 String childPackageName = updatedPkg.childPackageNames.get(i); 8305 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8306 childPackageName); 8307 if (updatedChildPkg != null) { 8308 updatedChildPkg.pkg = pkg; 8309 updatedChildPkg.versionCode = pkg.mVersionCode; 8310 } 8311 } 8312 8313 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8314 + scanFile + " ignored: updated version " + ps.versionCode 8315 + " better than this " + pkg.mVersionCode); 8316 } else { 8317 // The current app on the system partition is better than 8318 // what we have updated to on the data partition; switch 8319 // back to the system partition version. 8320 // At this point, its safely assumed that package installation for 8321 // apps in system partition will go through. If not there won't be a working 8322 // version of the app 8323 // writer 8324 synchronized (mPackages) { 8325 // Just remove the loaded entries from package lists. 8326 mPackages.remove(ps.name); 8327 } 8328 8329 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8330 + " reverting from " + ps.codePathString 8331 + ": new version " + pkg.mVersionCode 8332 + " better than installed " + ps.versionCode); 8333 8334 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8335 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8336 synchronized (mInstallLock) { 8337 args.cleanUpResourcesLI(); 8338 } 8339 synchronized (mPackages) { 8340 mSettings.enableSystemPackageLPw(ps.name); 8341 } 8342 updatedPkgBetter = true; 8343 } 8344 } 8345 } 8346 8347 if (updatedPkg != null) { 8348 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8349 // initially 8350 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8351 8352 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8353 // flag set initially 8354 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8355 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8356 } 8357 } 8358 8359 // Verify certificates against what was last scanned 8360 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8361 8362 /* 8363 * A new system app appeared, but we already had a non-system one of the 8364 * same name installed earlier. 8365 */ 8366 boolean shouldHideSystemApp = false; 8367 if (updatedPkg == null && ps != null 8368 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8369 /* 8370 * Check to make sure the signatures match first. If they don't, 8371 * wipe the installed application and its data. 8372 */ 8373 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8374 != PackageManager.SIGNATURE_MATCH) { 8375 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8376 + " signatures don't match existing userdata copy; removing"); 8377 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8378 "scanPackageInternalLI")) { 8379 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8380 } 8381 ps = null; 8382 } else { 8383 /* 8384 * If the newly-added system app is an older version than the 8385 * already installed version, hide it. It will be scanned later 8386 * and re-added like an update. 8387 */ 8388 if (pkg.mVersionCode <= ps.versionCode) { 8389 shouldHideSystemApp = true; 8390 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8391 + " but new version " + pkg.mVersionCode + " better than installed " 8392 + ps.versionCode + "; hiding system"); 8393 } else { 8394 /* 8395 * The newly found system app is a newer version that the 8396 * one previously installed. Simply remove the 8397 * already-installed application and replace it with our own 8398 * while keeping the application data. 8399 */ 8400 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8401 + " reverting from " + ps.codePathString + ": new version " 8402 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8403 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8404 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8405 synchronized (mInstallLock) { 8406 args.cleanUpResourcesLI(); 8407 } 8408 } 8409 } 8410 } 8411 8412 // The apk is forward locked (not public) if its code and resources 8413 // are kept in different files. (except for app in either system or 8414 // vendor path). 8415 // TODO grab this value from PackageSettings 8416 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8417 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8418 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8419 } 8420 } 8421 8422 // TODO: extend to support forward-locked splits 8423 String resourcePath = null; 8424 String baseResourcePath = null; 8425 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8426 if (ps != null && ps.resourcePathString != null) { 8427 resourcePath = ps.resourcePathString; 8428 baseResourcePath = ps.resourcePathString; 8429 } else { 8430 // Should not happen at all. Just log an error. 8431 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8432 } 8433 } else { 8434 resourcePath = pkg.codePath; 8435 baseResourcePath = pkg.baseCodePath; 8436 } 8437 8438 // Set application objects path explicitly. 8439 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8440 pkg.setApplicationInfoCodePath(pkg.codePath); 8441 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8442 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8443 pkg.setApplicationInfoResourcePath(resourcePath); 8444 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8445 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8446 8447 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8448 if (ps != null && ps.getInstantApp(userId)) { 8449 scanFlags |= SCAN_AS_INSTANT_APP; 8450 } 8451 8452 // Note that we invoke the following method only if we are about to unpack an application 8453 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8454 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8455 8456 /* 8457 * If the system app should be overridden by a previously installed 8458 * data, hide the system app now and let the /data/app scan pick it up 8459 * again. 8460 */ 8461 if (shouldHideSystemApp) { 8462 synchronized (mPackages) { 8463 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8464 } 8465 } 8466 8467 return scannedPkg; 8468 } 8469 8470 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8471 // Derive the new package synthetic package name 8472 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8473 + pkg.staticSharedLibVersion); 8474 } 8475 8476 private static String fixProcessName(String defProcessName, 8477 String processName) { 8478 if (processName == null) { 8479 return defProcessName; 8480 } 8481 return processName; 8482 } 8483 8484 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8485 throws PackageManagerException { 8486 if (pkgSetting.signatures.mSignatures != null) { 8487 // Already existing package. Make sure signatures match 8488 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8489 == PackageManager.SIGNATURE_MATCH; 8490 if (!match) { 8491 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8492 == PackageManager.SIGNATURE_MATCH; 8493 } 8494 if (!match) { 8495 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8496 == PackageManager.SIGNATURE_MATCH; 8497 } 8498 if (!match) { 8499 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8500 + pkg.packageName + " signatures do not match the " 8501 + "previously installed version; ignoring!"); 8502 } 8503 } 8504 8505 // Check for shared user signatures 8506 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8507 // Already existing package. Make sure signatures match 8508 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8509 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8510 if (!match) { 8511 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8512 == PackageManager.SIGNATURE_MATCH; 8513 } 8514 if (!match) { 8515 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8516 == PackageManager.SIGNATURE_MATCH; 8517 } 8518 if (!match) { 8519 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8520 "Package " + pkg.packageName 8521 + " has no signatures that match those in shared user " 8522 + pkgSetting.sharedUser.name + "; ignoring!"); 8523 } 8524 } 8525 } 8526 8527 /** 8528 * Enforces that only the system UID or root's UID can call a method exposed 8529 * via Binder. 8530 * 8531 * @param message used as message if SecurityException is thrown 8532 * @throws SecurityException if the caller is not system or root 8533 */ 8534 private static final void enforceSystemOrRoot(String message) { 8535 final int uid = Binder.getCallingUid(); 8536 if (uid != Process.SYSTEM_UID && uid != 0) { 8537 throw new SecurityException(message); 8538 } 8539 } 8540 8541 @Override 8542 public void performFstrimIfNeeded() { 8543 enforceSystemOrRoot("Only the system can request fstrim"); 8544 8545 // Before everything else, see whether we need to fstrim. 8546 try { 8547 IStorageManager sm = PackageHelper.getStorageManager(); 8548 if (sm != null) { 8549 boolean doTrim = false; 8550 final long interval = android.provider.Settings.Global.getLong( 8551 mContext.getContentResolver(), 8552 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8553 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8554 if (interval > 0) { 8555 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8556 if (timeSinceLast > interval) { 8557 doTrim = true; 8558 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8559 + "; running immediately"); 8560 } 8561 } 8562 if (doTrim) { 8563 final boolean dexOptDialogShown; 8564 synchronized (mPackages) { 8565 dexOptDialogShown = mDexOptDialogShown; 8566 } 8567 if (!isFirstBoot() && dexOptDialogShown) { 8568 try { 8569 ActivityManager.getService().showBootMessage( 8570 mContext.getResources().getString( 8571 R.string.android_upgrading_fstrim), true); 8572 } catch (RemoteException e) { 8573 } 8574 } 8575 sm.runMaintenance(); 8576 } 8577 } else { 8578 Slog.e(TAG, "storageManager service unavailable!"); 8579 } 8580 } catch (RemoteException e) { 8581 // Can't happen; StorageManagerService is local 8582 } 8583 } 8584 8585 @Override 8586 public void updatePackagesIfNeeded() { 8587 enforceSystemOrRoot("Only the system can request package update"); 8588 8589 // We need to re-extract after an OTA. 8590 boolean causeUpgrade = isUpgrade(); 8591 8592 // First boot or factory reset. 8593 // Note: we also handle devices that are upgrading to N right now as if it is their 8594 // first boot, as they do not have profile data. 8595 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8596 8597 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8598 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8599 8600 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8601 return; 8602 } 8603 8604 List<PackageParser.Package> pkgs; 8605 synchronized (mPackages) { 8606 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8607 } 8608 8609 final long startTime = System.nanoTime(); 8610 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8611 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8612 8613 final int elapsedTimeSeconds = 8614 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8615 8616 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8617 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8618 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8619 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8620 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8621 } 8622 8623 /** 8624 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8625 * containing statistics about the invocation. The array consists of three elements, 8626 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8627 * and {@code numberOfPackagesFailed}. 8628 */ 8629 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8630 String compilerFilter) { 8631 8632 int numberOfPackagesVisited = 0; 8633 int numberOfPackagesOptimized = 0; 8634 int numberOfPackagesSkipped = 0; 8635 int numberOfPackagesFailed = 0; 8636 final int numberOfPackagesToDexopt = pkgs.size(); 8637 8638 for (PackageParser.Package pkg : pkgs) { 8639 numberOfPackagesVisited++; 8640 8641 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8642 if (DEBUG_DEXOPT) { 8643 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8644 } 8645 numberOfPackagesSkipped++; 8646 continue; 8647 } 8648 8649 if (DEBUG_DEXOPT) { 8650 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8651 numberOfPackagesToDexopt + ": " + pkg.packageName); 8652 } 8653 8654 if (showDialog) { 8655 try { 8656 ActivityManager.getService().showBootMessage( 8657 mContext.getResources().getString(R.string.android_upgrading_apk, 8658 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8659 } catch (RemoteException e) { 8660 } 8661 synchronized (mPackages) { 8662 mDexOptDialogShown = true; 8663 } 8664 } 8665 8666 // If the OTA updates a system app which was previously preopted to a non-preopted state 8667 // the app might end up being verified at runtime. That's because by default the apps 8668 // are verify-profile but for preopted apps there's no profile. 8669 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8670 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8671 // filter (by default interpret-only). 8672 // Note that at this stage unused apps are already filtered. 8673 if (isSystemApp(pkg) && 8674 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8675 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8676 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8677 } 8678 8679 // checkProfiles is false to avoid merging profiles during boot which 8680 // might interfere with background compilation (b/28612421). 8681 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8682 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8683 // trade-off worth doing to save boot time work. 8684 int dexOptStatus = performDexOptTraced(pkg.packageName, 8685 false /* checkProfiles */, 8686 compilerFilter, 8687 false /* force */); 8688 switch (dexOptStatus) { 8689 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8690 numberOfPackagesOptimized++; 8691 break; 8692 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8693 numberOfPackagesSkipped++; 8694 break; 8695 case PackageDexOptimizer.DEX_OPT_FAILED: 8696 numberOfPackagesFailed++; 8697 break; 8698 default: 8699 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8700 break; 8701 } 8702 } 8703 8704 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8705 numberOfPackagesFailed }; 8706 } 8707 8708 @Override 8709 public void notifyPackageUse(String packageName, int reason) { 8710 synchronized (mPackages) { 8711 PackageParser.Package p = mPackages.get(packageName); 8712 if (p == null) { 8713 return; 8714 } 8715 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8716 } 8717 } 8718 8719 @Override 8720 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8721 int userId = UserHandle.getCallingUserId(); 8722 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8723 if (ai == null) { 8724 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8725 + loadingPackageName + ", user=" + userId); 8726 return; 8727 } 8728 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8729 } 8730 8731 @Override 8732 public boolean performDexOpt(String packageName, 8733 boolean checkProfiles, int compileReason, boolean force) { 8734 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8735 getCompilerFilterForReason(compileReason), force); 8736 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8737 } 8738 8739 @Override 8740 public boolean performDexOptMode(String packageName, 8741 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8742 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8743 targetCompilerFilter, force); 8744 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8745 } 8746 8747 private int performDexOptTraced(String packageName, 8748 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8749 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8750 try { 8751 return performDexOptInternal(packageName, checkProfiles, 8752 targetCompilerFilter, force); 8753 } finally { 8754 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8755 } 8756 } 8757 8758 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8759 // if the package can now be considered up to date for the given filter. 8760 private int performDexOptInternal(String packageName, 8761 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8762 PackageParser.Package p; 8763 synchronized (mPackages) { 8764 p = mPackages.get(packageName); 8765 if (p == null) { 8766 // Package could not be found. Report failure. 8767 return PackageDexOptimizer.DEX_OPT_FAILED; 8768 } 8769 mPackageUsage.maybeWriteAsync(mPackages); 8770 mCompilerStats.maybeWriteAsync(); 8771 } 8772 long callingId = Binder.clearCallingIdentity(); 8773 try { 8774 synchronized (mInstallLock) { 8775 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8776 targetCompilerFilter, force); 8777 } 8778 } finally { 8779 Binder.restoreCallingIdentity(callingId); 8780 } 8781 } 8782 8783 public ArraySet<String> getOptimizablePackages() { 8784 ArraySet<String> pkgs = new ArraySet<String>(); 8785 synchronized (mPackages) { 8786 for (PackageParser.Package p : mPackages.values()) { 8787 if (PackageDexOptimizer.canOptimizePackage(p)) { 8788 pkgs.add(p.packageName); 8789 } 8790 } 8791 } 8792 return pkgs; 8793 } 8794 8795 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8796 boolean checkProfiles, String targetCompilerFilter, 8797 boolean force) { 8798 // Select the dex optimizer based on the force parameter. 8799 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8800 // allocate an object here. 8801 PackageDexOptimizer pdo = force 8802 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8803 : mPackageDexOptimizer; 8804 8805 // Dexopt all dependencies first. Note: we ignore the return value and march on 8806 // on errors. 8807 // Note that we are going to call performDexOpt on those libraries as many times as 8808 // they are referenced in packages. When we do a batch of performDexOpt (for example 8809 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8810 // and the first package that uses the library will dexopt it. The 8811 // others will see that the compiled code for the library is up to date. 8812 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8813 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8814 if (!deps.isEmpty()) { 8815 for (PackageParser.Package depPackage : deps) { 8816 // TODO: Analyze and investigate if we (should) profile libraries. 8817 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8818 false /* checkProfiles */, 8819 targetCompilerFilter, 8820 getOrCreateCompilerPackageStats(depPackage), 8821 true /* isUsedByOtherApps */); 8822 } 8823 } 8824 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8825 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8826 mDexManager.isUsedByOtherApps(p.packageName)); 8827 } 8828 8829 // Performs dexopt on the used secondary dex files belonging to the given package. 8830 // Returns true if all dex files were process successfully (which could mean either dexopt or 8831 // skip). Returns false if any of the files caused errors. 8832 @Override 8833 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8834 boolean force) { 8835 mDexManager.reconcileSecondaryDexFiles(packageName); 8836 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8837 } 8838 8839 public boolean performDexOptSecondary(String packageName, int compileReason, 8840 boolean force) { 8841 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8842 } 8843 8844 /** 8845 * Reconcile the information we have about the secondary dex files belonging to 8846 * {@code packagName} and the actual dex files. For all dex files that were 8847 * deleted, update the internal records and delete the generated oat files. 8848 */ 8849 @Override 8850 public void reconcileSecondaryDexFiles(String packageName) { 8851 mDexManager.reconcileSecondaryDexFiles(packageName); 8852 } 8853 8854 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8855 // a reference there. 8856 /*package*/ DexManager getDexManager() { 8857 return mDexManager; 8858 } 8859 8860 /** 8861 * Execute the background dexopt job immediately. 8862 */ 8863 @Override 8864 public boolean runBackgroundDexoptJob() { 8865 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8866 } 8867 8868 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8869 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8870 || p.usesStaticLibraries != null) { 8871 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8872 Set<String> collectedNames = new HashSet<>(); 8873 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8874 8875 retValue.remove(p); 8876 8877 return retValue; 8878 } else { 8879 return Collections.emptyList(); 8880 } 8881 } 8882 8883 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8884 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8885 if (!collectedNames.contains(p.packageName)) { 8886 collectedNames.add(p.packageName); 8887 collected.add(p); 8888 8889 if (p.usesLibraries != null) { 8890 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8891 null, collected, collectedNames); 8892 } 8893 if (p.usesOptionalLibraries != null) { 8894 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8895 null, collected, collectedNames); 8896 } 8897 if (p.usesStaticLibraries != null) { 8898 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8899 p.usesStaticLibrariesVersions, collected, collectedNames); 8900 } 8901 } 8902 } 8903 8904 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8905 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8906 final int libNameCount = libs.size(); 8907 for (int i = 0; i < libNameCount; i++) { 8908 String libName = libs.get(i); 8909 int version = (versions != null && versions.length == libNameCount) 8910 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8911 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8912 if (libPkg != null) { 8913 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8914 } 8915 } 8916 } 8917 8918 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8919 synchronized (mPackages) { 8920 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8921 if (libEntry != null) { 8922 return mPackages.get(libEntry.apk); 8923 } 8924 return null; 8925 } 8926 } 8927 8928 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8929 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8930 if (versionedLib == null) { 8931 return null; 8932 } 8933 return versionedLib.get(version); 8934 } 8935 8936 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8937 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8938 pkg.staticSharedLibName); 8939 if (versionedLib == null) { 8940 return null; 8941 } 8942 int previousLibVersion = -1; 8943 final int versionCount = versionedLib.size(); 8944 for (int i = 0; i < versionCount; i++) { 8945 final int libVersion = versionedLib.keyAt(i); 8946 if (libVersion < pkg.staticSharedLibVersion) { 8947 previousLibVersion = Math.max(previousLibVersion, libVersion); 8948 } 8949 } 8950 if (previousLibVersion >= 0) { 8951 return versionedLib.get(previousLibVersion); 8952 } 8953 return null; 8954 } 8955 8956 public void shutdown() { 8957 mPackageUsage.writeNow(mPackages); 8958 mCompilerStats.writeNow(); 8959 } 8960 8961 @Override 8962 public void dumpProfiles(String packageName) { 8963 PackageParser.Package pkg; 8964 synchronized (mPackages) { 8965 pkg = mPackages.get(packageName); 8966 if (pkg == null) { 8967 throw new IllegalArgumentException("Unknown package: " + packageName); 8968 } 8969 } 8970 /* Only the shell, root, or the app user should be able to dump profiles. */ 8971 int callingUid = Binder.getCallingUid(); 8972 if (callingUid != Process.SHELL_UID && 8973 callingUid != Process.ROOT_UID && 8974 callingUid != pkg.applicationInfo.uid) { 8975 throw new SecurityException("dumpProfiles"); 8976 } 8977 8978 synchronized (mInstallLock) { 8979 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8980 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8981 try { 8982 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8983 String codePaths = TextUtils.join(";", allCodePaths); 8984 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8985 } catch (InstallerException e) { 8986 Slog.w(TAG, "Failed to dump profiles", e); 8987 } 8988 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8989 } 8990 } 8991 8992 @Override 8993 public void forceDexOpt(String packageName) { 8994 enforceSystemOrRoot("forceDexOpt"); 8995 8996 PackageParser.Package pkg; 8997 synchronized (mPackages) { 8998 pkg = mPackages.get(packageName); 8999 if (pkg == null) { 9000 throw new IllegalArgumentException("Unknown package: " + packageName); 9001 } 9002 } 9003 9004 synchronized (mInstallLock) { 9005 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9006 9007 // Whoever is calling forceDexOpt wants a compiled package. 9008 // Don't use profiles since that may cause compilation to be skipped. 9009 final int res = performDexOptInternalWithDependenciesLI(pkg, 9010 false /* checkProfiles */, getDefaultCompilerFilter(), 9011 true /* force */); 9012 9013 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9014 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9015 throw new IllegalStateException("Failed to dexopt: " + res); 9016 } 9017 } 9018 } 9019 9020 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9021 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9022 Slog.w(TAG, "Unable to update from " + oldPkg.name 9023 + " to " + newPkg.packageName 9024 + ": old package not in system partition"); 9025 return false; 9026 } else if (mPackages.get(oldPkg.name) != null) { 9027 Slog.w(TAG, "Unable to update from " + oldPkg.name 9028 + " to " + newPkg.packageName 9029 + ": old package still exists"); 9030 return false; 9031 } 9032 return true; 9033 } 9034 9035 void removeCodePathLI(File codePath) { 9036 if (codePath.isDirectory()) { 9037 try { 9038 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9039 } catch (InstallerException e) { 9040 Slog.w(TAG, "Failed to remove code path", e); 9041 } 9042 } else { 9043 codePath.delete(); 9044 } 9045 } 9046 9047 private int[] resolveUserIds(int userId) { 9048 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9049 } 9050 9051 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9052 if (pkg == null) { 9053 Slog.wtf(TAG, "Package was null!", new Throwable()); 9054 return; 9055 } 9056 clearAppDataLeafLIF(pkg, userId, flags); 9057 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9058 for (int i = 0; i < childCount; i++) { 9059 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9060 } 9061 } 9062 9063 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9064 final PackageSetting ps; 9065 synchronized (mPackages) { 9066 ps = mSettings.mPackages.get(pkg.packageName); 9067 } 9068 for (int realUserId : resolveUserIds(userId)) { 9069 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9070 try { 9071 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9072 ceDataInode); 9073 } catch (InstallerException e) { 9074 Slog.w(TAG, String.valueOf(e)); 9075 } 9076 } 9077 } 9078 9079 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9080 if (pkg == null) { 9081 Slog.wtf(TAG, "Package was null!", new Throwable()); 9082 return; 9083 } 9084 destroyAppDataLeafLIF(pkg, userId, flags); 9085 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9086 for (int i = 0; i < childCount; i++) { 9087 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9088 } 9089 } 9090 9091 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9092 final PackageSetting ps; 9093 synchronized (mPackages) { 9094 ps = mSettings.mPackages.get(pkg.packageName); 9095 } 9096 for (int realUserId : resolveUserIds(userId)) { 9097 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9098 try { 9099 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9100 ceDataInode); 9101 } catch (InstallerException e) { 9102 Slog.w(TAG, String.valueOf(e)); 9103 } 9104 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9105 } 9106 } 9107 9108 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9109 if (pkg == null) { 9110 Slog.wtf(TAG, "Package was null!", new Throwable()); 9111 return; 9112 } 9113 destroyAppProfilesLeafLIF(pkg); 9114 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9115 for (int i = 0; i < childCount; i++) { 9116 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9117 } 9118 } 9119 9120 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9121 try { 9122 mInstaller.destroyAppProfiles(pkg.packageName); 9123 } catch (InstallerException e) { 9124 Slog.w(TAG, String.valueOf(e)); 9125 } 9126 } 9127 9128 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9129 if (pkg == null) { 9130 Slog.wtf(TAG, "Package was null!", new Throwable()); 9131 return; 9132 } 9133 clearAppProfilesLeafLIF(pkg); 9134 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9135 for (int i = 0; i < childCount; i++) { 9136 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9137 } 9138 } 9139 9140 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9141 try { 9142 mInstaller.clearAppProfiles(pkg.packageName); 9143 } catch (InstallerException e) { 9144 Slog.w(TAG, String.valueOf(e)); 9145 } 9146 } 9147 9148 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9149 long lastUpdateTime) { 9150 // Set parent install/update time 9151 PackageSetting ps = (PackageSetting) pkg.mExtras; 9152 if (ps != null) { 9153 ps.firstInstallTime = firstInstallTime; 9154 ps.lastUpdateTime = lastUpdateTime; 9155 } 9156 // Set children install/update time 9157 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9158 for (int i = 0; i < childCount; i++) { 9159 PackageParser.Package childPkg = pkg.childPackages.get(i); 9160 ps = (PackageSetting) childPkg.mExtras; 9161 if (ps != null) { 9162 ps.firstInstallTime = firstInstallTime; 9163 ps.lastUpdateTime = lastUpdateTime; 9164 } 9165 } 9166 } 9167 9168 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 9169 PackageParser.Package changingLib) { 9170 if (file.path != null) { 9171 usesLibraryFiles.add(file.path); 9172 return; 9173 } 9174 PackageParser.Package p = mPackages.get(file.apk); 9175 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9176 // If we are doing this while in the middle of updating a library apk, 9177 // then we need to make sure to use that new apk for determining the 9178 // dependencies here. (We haven't yet finished committing the new apk 9179 // to the package manager state.) 9180 if (p == null || p.packageName.equals(changingLib.packageName)) { 9181 p = changingLib; 9182 } 9183 } 9184 if (p != null) { 9185 usesLibraryFiles.addAll(p.getAllCodePaths()); 9186 } 9187 } 9188 9189 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9190 PackageParser.Package changingLib) throws PackageManagerException { 9191 if (pkg == null) { 9192 return; 9193 } 9194 ArraySet<String> usesLibraryFiles = null; 9195 if (pkg.usesLibraries != null) { 9196 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9197 null, null, pkg.packageName, changingLib, true, null); 9198 } 9199 if (pkg.usesStaticLibraries != null) { 9200 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9201 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9202 pkg.packageName, changingLib, true, usesLibraryFiles); 9203 } 9204 if (pkg.usesOptionalLibraries != null) { 9205 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9206 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 9207 } 9208 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9209 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9210 } else { 9211 pkg.usesLibraryFiles = null; 9212 } 9213 } 9214 9215 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9216 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 9217 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9218 boolean required, @Nullable ArraySet<String> outUsedLibraries) 9219 throws PackageManagerException { 9220 final int libCount = requestedLibraries.size(); 9221 for (int i = 0; i < libCount; i++) { 9222 final String libName = requestedLibraries.get(i); 9223 final int libVersion = requiredVersions != null ? requiredVersions[i] 9224 : SharedLibraryInfo.VERSION_UNDEFINED; 9225 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9226 if (libEntry == null) { 9227 if (required) { 9228 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9229 "Package " + packageName + " requires unavailable shared library " 9230 + libName + "; failing!"); 9231 } else { 9232 Slog.w(TAG, "Package " + packageName 9233 + " desires unavailable shared library " 9234 + libName + "; ignoring!"); 9235 } 9236 } else { 9237 if (requiredVersions != null && requiredCertDigests != null) { 9238 if (libEntry.info.getVersion() != requiredVersions[i]) { 9239 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9240 "Package " + packageName + " requires unavailable static shared" 9241 + " library " + libName + " version " 9242 + libEntry.info.getVersion() + "; failing!"); 9243 } 9244 9245 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9246 if (libPkg == null) { 9247 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9248 "Package " + packageName + " requires unavailable static shared" 9249 + " library; failing!"); 9250 } 9251 9252 String expectedCertDigest = requiredCertDigests[i]; 9253 String libCertDigest = PackageUtils.computeCertSha256Digest( 9254 libPkg.mSignatures[0]); 9255 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9256 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9257 "Package " + packageName + " requires differently signed" + 9258 " static shared library; failing!"); 9259 } 9260 } 9261 9262 if (outUsedLibraries == null) { 9263 outUsedLibraries = new ArraySet<>(); 9264 } 9265 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9266 } 9267 } 9268 return outUsedLibraries; 9269 } 9270 9271 private static boolean hasString(List<String> list, List<String> which) { 9272 if (list == null) { 9273 return false; 9274 } 9275 for (int i=list.size()-1; i>=0; i--) { 9276 for (int j=which.size()-1; j>=0; j--) { 9277 if (which.get(j).equals(list.get(i))) { 9278 return true; 9279 } 9280 } 9281 } 9282 return false; 9283 } 9284 9285 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9286 PackageParser.Package changingPkg) { 9287 ArrayList<PackageParser.Package> res = null; 9288 for (PackageParser.Package pkg : mPackages.values()) { 9289 if (changingPkg != null 9290 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9291 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9292 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9293 changingPkg.staticSharedLibName)) { 9294 return null; 9295 } 9296 if (res == null) { 9297 res = new ArrayList<>(); 9298 } 9299 res.add(pkg); 9300 try { 9301 updateSharedLibrariesLPr(pkg, changingPkg); 9302 } catch (PackageManagerException e) { 9303 // If a system app update or an app and a required lib missing we 9304 // delete the package and for updated system apps keep the data as 9305 // it is better for the user to reinstall than to be in an limbo 9306 // state. Also libs disappearing under an app should never happen 9307 // - just in case. 9308 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9309 final int flags = pkg.isUpdatedSystemApp() 9310 ? PackageManager.DELETE_KEEP_DATA : 0; 9311 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9312 flags , null, true, null); 9313 } 9314 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9315 } 9316 } 9317 return res; 9318 } 9319 9320 /** 9321 * Derive the value of the {@code cpuAbiOverride} based on the provided 9322 * value and an optional stored value from the package settings. 9323 */ 9324 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9325 String cpuAbiOverride = null; 9326 9327 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9328 cpuAbiOverride = null; 9329 } else if (abiOverride != null) { 9330 cpuAbiOverride = abiOverride; 9331 } else if (settings != null) { 9332 cpuAbiOverride = settings.cpuAbiOverrideString; 9333 } 9334 9335 return cpuAbiOverride; 9336 } 9337 9338 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9339 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9340 throws PackageManagerException { 9341 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9342 // If the package has children and this is the first dive in the function 9343 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9344 // whether all packages (parent and children) would be successfully scanned 9345 // before the actual scan since scanning mutates internal state and we want 9346 // to atomically install the package and its children. 9347 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9348 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9349 scanFlags |= SCAN_CHECK_ONLY; 9350 } 9351 } else { 9352 scanFlags &= ~SCAN_CHECK_ONLY; 9353 } 9354 9355 final PackageParser.Package scannedPkg; 9356 try { 9357 // Scan the parent 9358 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9359 // Scan the children 9360 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9361 for (int i = 0; i < childCount; i++) { 9362 PackageParser.Package childPkg = pkg.childPackages.get(i); 9363 scanPackageLI(childPkg, policyFlags, 9364 scanFlags, currentTime, user); 9365 } 9366 } finally { 9367 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9368 } 9369 9370 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9371 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9372 } 9373 9374 return scannedPkg; 9375 } 9376 9377 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9378 int scanFlags, long currentTime, @Nullable UserHandle user) 9379 throws PackageManagerException { 9380 boolean success = false; 9381 try { 9382 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9383 currentTime, user); 9384 success = true; 9385 return res; 9386 } finally { 9387 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9388 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9389 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9390 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9391 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9392 } 9393 } 9394 } 9395 9396 /** 9397 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9398 */ 9399 private static boolean apkHasCode(String fileName) { 9400 StrictJarFile jarFile = null; 9401 try { 9402 jarFile = new StrictJarFile(fileName, 9403 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9404 return jarFile.findEntry("classes.dex") != null; 9405 } catch (IOException ignore) { 9406 } finally { 9407 try { 9408 if (jarFile != null) { 9409 jarFile.close(); 9410 } 9411 } catch (IOException ignore) {} 9412 } 9413 return false; 9414 } 9415 9416 /** 9417 * Enforces code policy for the package. This ensures that if an APK has 9418 * declared hasCode="true" in its manifest that the APK actually contains 9419 * code. 9420 * 9421 * @throws PackageManagerException If bytecode could not be found when it should exist 9422 */ 9423 private static void assertCodePolicy(PackageParser.Package pkg) 9424 throws PackageManagerException { 9425 final boolean shouldHaveCode = 9426 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9427 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9428 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9429 "Package " + pkg.baseCodePath + " code is missing"); 9430 } 9431 9432 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9433 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9434 final boolean splitShouldHaveCode = 9435 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9436 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9437 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9438 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9439 } 9440 } 9441 } 9442 } 9443 9444 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9445 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9446 throws PackageManagerException { 9447 if (DEBUG_PACKAGE_SCANNING) { 9448 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9449 Log.d(TAG, "Scanning package " + pkg.packageName); 9450 } 9451 9452 applyPolicy(pkg, policyFlags); 9453 9454 assertPackageIsValid(pkg, policyFlags, scanFlags); 9455 9456 // Initialize package source and resource directories 9457 final File scanFile = new File(pkg.codePath); 9458 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9459 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9460 9461 SharedUserSetting suid = null; 9462 PackageSetting pkgSetting = null; 9463 9464 // Getting the package setting may have a side-effect, so if we 9465 // are only checking if scan would succeed, stash a copy of the 9466 // old setting to restore at the end. 9467 PackageSetting nonMutatedPs = null; 9468 9469 // We keep references to the derived CPU Abis from settings in oder to reuse 9470 // them in the case where we're not upgrading or booting for the first time. 9471 String primaryCpuAbiFromSettings = null; 9472 String secondaryCpuAbiFromSettings = null; 9473 9474 // writer 9475 synchronized (mPackages) { 9476 if (pkg.mSharedUserId != null) { 9477 // SIDE EFFECTS; may potentially allocate a new shared user 9478 suid = mSettings.getSharedUserLPw( 9479 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9480 if (DEBUG_PACKAGE_SCANNING) { 9481 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9482 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9483 + "): packages=" + suid.packages); 9484 } 9485 } 9486 9487 // Check if we are renaming from an original package name. 9488 PackageSetting origPackage = null; 9489 String realName = null; 9490 if (pkg.mOriginalPackages != null) { 9491 // This package may need to be renamed to a previously 9492 // installed name. Let's check on that... 9493 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9494 if (pkg.mOriginalPackages.contains(renamed)) { 9495 // This package had originally been installed as the 9496 // original name, and we have already taken care of 9497 // transitioning to the new one. Just update the new 9498 // one to continue using the old name. 9499 realName = pkg.mRealPackage; 9500 if (!pkg.packageName.equals(renamed)) { 9501 // Callers into this function may have already taken 9502 // care of renaming the package; only do it here if 9503 // it is not already done. 9504 pkg.setPackageName(renamed); 9505 } 9506 } else { 9507 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9508 if ((origPackage = mSettings.getPackageLPr( 9509 pkg.mOriginalPackages.get(i))) != null) { 9510 // We do have the package already installed under its 9511 // original name... should we use it? 9512 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9513 // New package is not compatible with original. 9514 origPackage = null; 9515 continue; 9516 } else if (origPackage.sharedUser != null) { 9517 // Make sure uid is compatible between packages. 9518 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9519 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9520 + " to " + pkg.packageName + ": old uid " 9521 + origPackage.sharedUser.name 9522 + " differs from " + pkg.mSharedUserId); 9523 origPackage = null; 9524 continue; 9525 } 9526 // TODO: Add case when shared user id is added [b/28144775] 9527 } else { 9528 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9529 + pkg.packageName + " to old name " + origPackage.name); 9530 } 9531 break; 9532 } 9533 } 9534 } 9535 } 9536 9537 if (mTransferedPackages.contains(pkg.packageName)) { 9538 Slog.w(TAG, "Package " + pkg.packageName 9539 + " was transferred to another, but its .apk remains"); 9540 } 9541 9542 // See comments in nonMutatedPs declaration 9543 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9544 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9545 if (foundPs != null) { 9546 nonMutatedPs = new PackageSetting(foundPs); 9547 } 9548 } 9549 9550 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9551 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9552 if (foundPs != null) { 9553 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9554 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9555 } 9556 } 9557 9558 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9559 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9560 PackageManagerService.reportSettingsProblem(Log.WARN, 9561 "Package " + pkg.packageName + " shared user changed from " 9562 + (pkgSetting.sharedUser != null 9563 ? pkgSetting.sharedUser.name : "<nothing>") 9564 + " to " 9565 + (suid != null ? suid.name : "<nothing>") 9566 + "; replacing with new"); 9567 pkgSetting = null; 9568 } 9569 final PackageSetting oldPkgSetting = 9570 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9571 final PackageSetting disabledPkgSetting = 9572 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9573 9574 String[] usesStaticLibraries = null; 9575 if (pkg.usesStaticLibraries != null) { 9576 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9577 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9578 } 9579 9580 if (pkgSetting == null) { 9581 final String parentPackageName = (pkg.parentPackage != null) 9582 ? pkg.parentPackage.packageName : null; 9583 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9584 // REMOVE SharedUserSetting from method; update in a separate call 9585 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9586 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9587 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9588 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9589 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9590 true /*allowInstall*/, instantApp, parentPackageName, 9591 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9592 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9593 // SIDE EFFECTS; updates system state; move elsewhere 9594 if (origPackage != null) { 9595 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9596 } 9597 mSettings.addUserToSettingLPw(pkgSetting); 9598 } else { 9599 // REMOVE SharedUserSetting from method; update in a separate call. 9600 // 9601 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9602 // secondaryCpuAbi are not known at this point so we always update them 9603 // to null here, only to reset them at a later point. 9604 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9605 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9606 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9607 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9608 UserManagerService.getInstance(), usesStaticLibraries, 9609 pkg.usesStaticLibrariesVersions); 9610 } 9611 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9612 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9613 9614 // SIDE EFFECTS; modifies system state; move elsewhere 9615 if (pkgSetting.origPackage != null) { 9616 // If we are first transitioning from an original package, 9617 // fix up the new package's name now. We need to do this after 9618 // looking up the package under its new name, so getPackageLP 9619 // can take care of fiddling things correctly. 9620 pkg.setPackageName(origPackage.name); 9621 9622 // File a report about this. 9623 String msg = "New package " + pkgSetting.realName 9624 + " renamed to replace old package " + pkgSetting.name; 9625 reportSettingsProblem(Log.WARN, msg); 9626 9627 // Make a note of it. 9628 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9629 mTransferedPackages.add(origPackage.name); 9630 } 9631 9632 // No longer need to retain this. 9633 pkgSetting.origPackage = null; 9634 } 9635 9636 // SIDE EFFECTS; modifies system state; move elsewhere 9637 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9638 // Make a note of it. 9639 mTransferedPackages.add(pkg.packageName); 9640 } 9641 9642 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9643 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9644 } 9645 9646 if ((scanFlags & SCAN_BOOTING) == 0 9647 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9648 // Check all shared libraries and map to their actual file path. 9649 // We only do this here for apps not on a system dir, because those 9650 // are the only ones that can fail an install due to this. We 9651 // will take care of the system apps by updating all of their 9652 // library paths after the scan is done. Also during the initial 9653 // scan don't update any libs as we do this wholesale after all 9654 // apps are scanned to avoid dependency based scanning. 9655 updateSharedLibrariesLPr(pkg, null); 9656 } 9657 9658 if (mFoundPolicyFile) { 9659 SELinuxMMAC.assignSeInfoValue(pkg); 9660 } 9661 pkg.applicationInfo.uid = pkgSetting.appId; 9662 pkg.mExtras = pkgSetting; 9663 9664 9665 // Static shared libs have same package with different versions where 9666 // we internally use a synthetic package name to allow multiple versions 9667 // of the same package, therefore we need to compare signatures against 9668 // the package setting for the latest library version. 9669 PackageSetting signatureCheckPs = pkgSetting; 9670 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9671 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9672 if (libraryEntry != null) { 9673 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9674 } 9675 } 9676 9677 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9678 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9679 // We just determined the app is signed correctly, so bring 9680 // over the latest parsed certs. 9681 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9682 } else { 9683 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9684 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9685 "Package " + pkg.packageName + " upgrade keys do not match the " 9686 + "previously installed version"); 9687 } else { 9688 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9689 String msg = "System package " + pkg.packageName 9690 + " signature changed; retaining data."; 9691 reportSettingsProblem(Log.WARN, msg); 9692 } 9693 } 9694 } else { 9695 try { 9696 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9697 verifySignaturesLP(signatureCheckPs, pkg); 9698 // We just determined the app is signed correctly, so bring 9699 // over the latest parsed certs. 9700 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9701 } catch (PackageManagerException e) { 9702 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9703 throw e; 9704 } 9705 // The signature has changed, but this package is in the system 9706 // image... let's recover! 9707 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9708 // However... if this package is part of a shared user, but it 9709 // doesn't match the signature of the shared user, let's fail. 9710 // What this means is that you can't change the signatures 9711 // associated with an overall shared user, which doesn't seem all 9712 // that unreasonable. 9713 if (signatureCheckPs.sharedUser != null) { 9714 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9715 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9716 throw new PackageManagerException( 9717 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9718 "Signature mismatch for shared user: " 9719 + pkgSetting.sharedUser); 9720 } 9721 } 9722 // File a report about this. 9723 String msg = "System package " + pkg.packageName 9724 + " signature changed; retaining data."; 9725 reportSettingsProblem(Log.WARN, msg); 9726 } 9727 } 9728 9729 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9730 // This package wants to adopt ownership of permissions from 9731 // another package. 9732 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9733 final String origName = pkg.mAdoptPermissions.get(i); 9734 final PackageSetting orig = mSettings.getPackageLPr(origName); 9735 if (orig != null) { 9736 if (verifyPackageUpdateLPr(orig, pkg)) { 9737 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9738 + pkg.packageName); 9739 // SIDE EFFECTS; updates permissions system state; move elsewhere 9740 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9741 } 9742 } 9743 } 9744 } 9745 } 9746 9747 pkg.applicationInfo.processName = fixProcessName( 9748 pkg.applicationInfo.packageName, 9749 pkg.applicationInfo.processName); 9750 9751 if (pkg != mPlatformPackage) { 9752 // Get all of our default paths setup 9753 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9754 } 9755 9756 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9757 9758 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9759 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9761 derivePackageAbi( 9762 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9763 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9764 9765 // Some system apps still use directory structure for native libraries 9766 // in which case we might end up not detecting abi solely based on apk 9767 // structure. Try to detect abi based on directory structure. 9768 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9769 pkg.applicationInfo.primaryCpuAbi == null) { 9770 setBundledAppAbisAndRoots(pkg, pkgSetting); 9771 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9772 } 9773 } else { 9774 // This is not a first boot or an upgrade, don't bother deriving the 9775 // ABI during the scan. Instead, trust the value that was stored in the 9776 // package setting. 9777 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9778 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9779 9780 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9781 9782 if (DEBUG_ABI_SELECTION) { 9783 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9784 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9785 pkg.applicationInfo.secondaryCpuAbi); 9786 } 9787 } 9788 } else { 9789 if ((scanFlags & SCAN_MOVE) != 0) { 9790 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9791 // but we already have this packages package info in the PackageSetting. We just 9792 // use that and derive the native library path based on the new codepath. 9793 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9794 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9795 } 9796 9797 // Set native library paths again. For moves, the path will be updated based on the 9798 // ABIs we've determined above. For non-moves, the path will be updated based on the 9799 // ABIs we determined during compilation, but the path will depend on the final 9800 // package path (after the rename away from the stage path). 9801 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9802 } 9803 9804 // This is a special case for the "system" package, where the ABI is 9805 // dictated by the zygote configuration (and init.rc). We should keep track 9806 // of this ABI so that we can deal with "normal" applications that run under 9807 // the same UID correctly. 9808 if (mPlatformPackage == pkg) { 9809 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9810 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9811 } 9812 9813 // If there's a mismatch between the abi-override in the package setting 9814 // and the abiOverride specified for the install. Warn about this because we 9815 // would've already compiled the app without taking the package setting into 9816 // account. 9817 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9818 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9819 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9820 " for package " + pkg.packageName); 9821 } 9822 } 9823 9824 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9825 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9826 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9827 9828 // Copy the derived override back to the parsed package, so that we can 9829 // update the package settings accordingly. 9830 pkg.cpuAbiOverride = cpuAbiOverride; 9831 9832 if (DEBUG_ABI_SELECTION) { 9833 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9834 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9835 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9836 } 9837 9838 // Push the derived path down into PackageSettings so we know what to 9839 // clean up at uninstall time. 9840 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9841 9842 if (DEBUG_ABI_SELECTION) { 9843 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9844 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9845 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9846 } 9847 9848 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9849 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9850 // We don't do this here during boot because we can do it all 9851 // at once after scanning all existing packages. 9852 // 9853 // We also do this *before* we perform dexopt on this package, so that 9854 // we can avoid redundant dexopts, and also to make sure we've got the 9855 // code and package path correct. 9856 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9857 } 9858 9859 if (mFactoryTest && pkg.requestedPermissions.contains( 9860 android.Manifest.permission.FACTORY_TEST)) { 9861 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9862 } 9863 9864 if (isSystemApp(pkg)) { 9865 pkgSetting.isOrphaned = true; 9866 } 9867 9868 // Take care of first install / last update times. 9869 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9870 if (currentTime != 0) { 9871 if (pkgSetting.firstInstallTime == 0) { 9872 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9873 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9874 pkgSetting.lastUpdateTime = currentTime; 9875 } 9876 } else if (pkgSetting.firstInstallTime == 0) { 9877 // We need *something*. Take time time stamp of the file. 9878 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9879 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9880 if (scanFileTime != pkgSetting.timeStamp) { 9881 // A package on the system image has changed; consider this 9882 // to be an update. 9883 pkgSetting.lastUpdateTime = scanFileTime; 9884 } 9885 } 9886 pkgSetting.setTimeStamp(scanFileTime); 9887 9888 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9889 if (nonMutatedPs != null) { 9890 synchronized (mPackages) { 9891 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9892 } 9893 } 9894 } else { 9895 final int userId = user == null ? 0 : user.getIdentifier(); 9896 // Modify state for the given package setting 9897 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9898 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9899 if (pkgSetting.getInstantApp(userId)) { 9900 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9901 } 9902 } 9903 return pkg; 9904 } 9905 9906 /** 9907 * Applies policy to the parsed package based upon the given policy flags. 9908 * Ensures the package is in a good state. 9909 * <p> 9910 * Implementation detail: This method must NOT have any side effect. It would 9911 * ideally be static, but, it requires locks to read system state. 9912 */ 9913 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9914 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9915 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9916 if (pkg.applicationInfo.isDirectBootAware()) { 9917 // we're direct boot aware; set for all components 9918 for (PackageParser.Service s : pkg.services) { 9919 s.info.encryptionAware = s.info.directBootAware = true; 9920 } 9921 for (PackageParser.Provider p : pkg.providers) { 9922 p.info.encryptionAware = p.info.directBootAware = true; 9923 } 9924 for (PackageParser.Activity a : pkg.activities) { 9925 a.info.encryptionAware = a.info.directBootAware = true; 9926 } 9927 for (PackageParser.Activity r : pkg.receivers) { 9928 r.info.encryptionAware = r.info.directBootAware = true; 9929 } 9930 } 9931 } else { 9932 // Only allow system apps to be flagged as core apps. 9933 pkg.coreApp = false; 9934 // clear flags not applicable to regular apps 9935 pkg.applicationInfo.privateFlags &= 9936 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9937 pkg.applicationInfo.privateFlags &= 9938 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9939 } 9940 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9941 9942 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9943 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9944 } 9945 9946 if (!isSystemApp(pkg)) { 9947 // Only system apps can use these features. 9948 pkg.mOriginalPackages = null; 9949 pkg.mRealPackage = null; 9950 pkg.mAdoptPermissions = null; 9951 } 9952 } 9953 9954 /** 9955 * Asserts the parsed package is valid according to the given policy. If the 9956 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9957 * <p> 9958 * Implementation detail: This method must NOT have any side effects. It would 9959 * ideally be static, but, it requires locks to read system state. 9960 * 9961 * @throws PackageManagerException If the package fails any of the validation checks 9962 */ 9963 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9964 throws PackageManagerException { 9965 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9966 assertCodePolicy(pkg); 9967 } 9968 9969 if (pkg.applicationInfo.getCodePath() == null || 9970 pkg.applicationInfo.getResourcePath() == null) { 9971 // Bail out. The resource and code paths haven't been set. 9972 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9973 "Code and resource paths haven't been set correctly"); 9974 } 9975 9976 // Make sure we're not adding any bogus keyset info 9977 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9978 ksms.assertScannedPackageValid(pkg); 9979 9980 synchronized (mPackages) { 9981 // The special "android" package can only be defined once 9982 if (pkg.packageName.equals("android")) { 9983 if (mAndroidApplication != null) { 9984 Slog.w(TAG, "*************************************************"); 9985 Slog.w(TAG, "Core android package being redefined. Skipping."); 9986 Slog.w(TAG, " codePath=" + pkg.codePath); 9987 Slog.w(TAG, "*************************************************"); 9988 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9989 "Core android package being redefined. Skipping."); 9990 } 9991 } 9992 9993 // A package name must be unique; don't allow duplicates 9994 if (mPackages.containsKey(pkg.packageName)) { 9995 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9996 "Application package " + pkg.packageName 9997 + " already installed. Skipping duplicate."); 9998 } 9999 10000 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10001 // Static libs have a synthetic package name containing the version 10002 // but we still want the base name to be unique. 10003 if (mPackages.containsKey(pkg.manifestPackageName)) { 10004 throw new PackageManagerException( 10005 "Duplicate static shared lib provider package"); 10006 } 10007 10008 // Static shared libraries should have at least O target SDK 10009 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10010 throw new PackageManagerException( 10011 "Packages declaring static-shared libs must target O SDK or higher"); 10012 } 10013 10014 // Package declaring static a shared lib cannot be instant apps 10015 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10016 throw new PackageManagerException( 10017 "Packages declaring static-shared libs cannot be instant apps"); 10018 } 10019 10020 // Package declaring static a shared lib cannot be renamed since the package 10021 // name is synthetic and apps can't code around package manager internals. 10022 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10023 throw new PackageManagerException( 10024 "Packages declaring static-shared libs cannot be renamed"); 10025 } 10026 10027 // Package declaring static a shared lib cannot declare child packages 10028 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10029 throw new PackageManagerException( 10030 "Packages declaring static-shared libs cannot have child packages"); 10031 } 10032 10033 // Package declaring static a shared lib cannot declare dynamic libs 10034 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10035 throw new PackageManagerException( 10036 "Packages declaring static-shared libs cannot declare dynamic libs"); 10037 } 10038 10039 // Package declaring static a shared lib cannot declare shared users 10040 if (pkg.mSharedUserId != null) { 10041 throw new PackageManagerException( 10042 "Packages declaring static-shared libs cannot declare shared users"); 10043 } 10044 10045 // Static shared libs cannot declare activities 10046 if (!pkg.activities.isEmpty()) { 10047 throw new PackageManagerException( 10048 "Static shared libs cannot declare activities"); 10049 } 10050 10051 // Static shared libs cannot declare services 10052 if (!pkg.services.isEmpty()) { 10053 throw new PackageManagerException( 10054 "Static shared libs cannot declare services"); 10055 } 10056 10057 // Static shared libs cannot declare providers 10058 if (!pkg.providers.isEmpty()) { 10059 throw new PackageManagerException( 10060 "Static shared libs cannot declare content providers"); 10061 } 10062 10063 // Static shared libs cannot declare receivers 10064 if (!pkg.receivers.isEmpty()) { 10065 throw new PackageManagerException( 10066 "Static shared libs cannot declare broadcast receivers"); 10067 } 10068 10069 // Static shared libs cannot declare permission groups 10070 if (!pkg.permissionGroups.isEmpty()) { 10071 throw new PackageManagerException( 10072 "Static shared libs cannot declare permission groups"); 10073 } 10074 10075 // Static shared libs cannot declare permissions 10076 if (!pkg.permissions.isEmpty()) { 10077 throw new PackageManagerException( 10078 "Static shared libs cannot declare permissions"); 10079 } 10080 10081 // Static shared libs cannot declare protected broadcasts 10082 if (pkg.protectedBroadcasts != null) { 10083 throw new PackageManagerException( 10084 "Static shared libs cannot declare protected broadcasts"); 10085 } 10086 10087 // Static shared libs cannot be overlay targets 10088 if (pkg.mOverlayTarget != null) { 10089 throw new PackageManagerException( 10090 "Static shared libs cannot be overlay targets"); 10091 } 10092 10093 // The version codes must be ordered as lib versions 10094 int minVersionCode = Integer.MIN_VALUE; 10095 int maxVersionCode = Integer.MAX_VALUE; 10096 10097 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10098 pkg.staticSharedLibName); 10099 if (versionedLib != null) { 10100 final int versionCount = versionedLib.size(); 10101 for (int i = 0; i < versionCount; i++) { 10102 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10103 // TODO: We will change version code to long, so in the new API it is long 10104 final int libVersionCode = (int) libInfo.getDeclaringPackage() 10105 .getVersionCode(); 10106 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 10107 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10108 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 10109 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10110 } else { 10111 minVersionCode = maxVersionCode = libVersionCode; 10112 break; 10113 } 10114 } 10115 } 10116 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 10117 throw new PackageManagerException("Static shared" 10118 + " lib version codes must be ordered as lib versions"); 10119 } 10120 } 10121 10122 // Only privileged apps and updated privileged apps can add child packages. 10123 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10124 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 10125 throw new PackageManagerException("Only privileged apps can add child " 10126 + "packages. Ignoring package " + pkg.packageName); 10127 } 10128 final int childCount = pkg.childPackages.size(); 10129 for (int i = 0; i < childCount; i++) { 10130 PackageParser.Package childPkg = pkg.childPackages.get(i); 10131 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10132 childPkg.packageName)) { 10133 throw new PackageManagerException("Can't override child of " 10134 + "another disabled app. Ignoring package " + pkg.packageName); 10135 } 10136 } 10137 } 10138 10139 // If we're only installing presumed-existing packages, require that the 10140 // scanned APK is both already known and at the path previously established 10141 // for it. Previously unknown packages we pick up normally, but if we have an 10142 // a priori expectation about this package's install presence, enforce it. 10143 // With a singular exception for new system packages. When an OTA contains 10144 // a new system package, we allow the codepath to change from a system location 10145 // to the user-installed location. If we don't allow this change, any newer, 10146 // user-installed version of the application will be ignored. 10147 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10148 if (mExpectingBetter.containsKey(pkg.packageName)) { 10149 logCriticalInfo(Log.WARN, 10150 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10151 } else { 10152 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10153 if (known != null) { 10154 if (DEBUG_PACKAGE_SCANNING) { 10155 Log.d(TAG, "Examining " + pkg.codePath 10156 + " and requiring known paths " + known.codePathString 10157 + " & " + known.resourcePathString); 10158 } 10159 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10160 || !pkg.applicationInfo.getResourcePath().equals( 10161 known.resourcePathString)) { 10162 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10163 "Application package " + pkg.packageName 10164 + " found at " + pkg.applicationInfo.getCodePath() 10165 + " but expected at " + known.codePathString 10166 + "; ignoring."); 10167 } 10168 } 10169 } 10170 } 10171 10172 // Verify that this new package doesn't have any content providers 10173 // that conflict with existing packages. Only do this if the 10174 // package isn't already installed, since we don't want to break 10175 // things that are installed. 10176 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10177 final int N = pkg.providers.size(); 10178 int i; 10179 for (i=0; i<N; i++) { 10180 PackageParser.Provider p = pkg.providers.get(i); 10181 if (p.info.authority != null) { 10182 String names[] = p.info.authority.split(";"); 10183 for (int j = 0; j < names.length; j++) { 10184 if (mProvidersByAuthority.containsKey(names[j])) { 10185 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10186 final String otherPackageName = 10187 ((other != null && other.getComponentName() != null) ? 10188 other.getComponentName().getPackageName() : "?"); 10189 throw new PackageManagerException( 10190 INSTALL_FAILED_CONFLICTING_PROVIDER, 10191 "Can't install because provider name " + names[j] 10192 + " (in package " + pkg.applicationInfo.packageName 10193 + ") is already used by " + otherPackageName); 10194 } 10195 } 10196 } 10197 } 10198 } 10199 } 10200 } 10201 10202 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 10203 int type, String declaringPackageName, int declaringVersionCode) { 10204 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10205 if (versionedLib == null) { 10206 versionedLib = new SparseArray<>(); 10207 mSharedLibraries.put(name, versionedLib); 10208 if (type == SharedLibraryInfo.TYPE_STATIC) { 10209 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10210 } 10211 } else if (versionedLib.indexOfKey(version) >= 0) { 10212 return false; 10213 } 10214 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10215 version, type, declaringPackageName, declaringVersionCode); 10216 versionedLib.put(version, libEntry); 10217 return true; 10218 } 10219 10220 private boolean removeSharedLibraryLPw(String name, int version) { 10221 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10222 if (versionedLib == null) { 10223 return false; 10224 } 10225 final int libIdx = versionedLib.indexOfKey(version); 10226 if (libIdx < 0) { 10227 return false; 10228 } 10229 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10230 versionedLib.remove(version); 10231 if (versionedLib.size() <= 0) { 10232 mSharedLibraries.remove(name); 10233 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10234 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10235 .getPackageName()); 10236 } 10237 } 10238 return true; 10239 } 10240 10241 /** 10242 * Adds a scanned package to the system. When this method is finished, the package will 10243 * be available for query, resolution, etc... 10244 */ 10245 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10246 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 10247 final String pkgName = pkg.packageName; 10248 if (mCustomResolverComponentName != null && 10249 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10250 setUpCustomResolverActivity(pkg); 10251 } 10252 10253 if (pkg.packageName.equals("android")) { 10254 synchronized (mPackages) { 10255 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10256 // Set up information for our fall-back user intent resolution activity. 10257 mPlatformPackage = pkg; 10258 pkg.mVersionCode = mSdkVersion; 10259 mAndroidApplication = pkg.applicationInfo; 10260 if (!mResolverReplaced) { 10261 mResolveActivity.applicationInfo = mAndroidApplication; 10262 mResolveActivity.name = ResolverActivity.class.getName(); 10263 mResolveActivity.packageName = mAndroidApplication.packageName; 10264 mResolveActivity.processName = "system:ui"; 10265 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10266 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10267 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10268 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10269 mResolveActivity.exported = true; 10270 mResolveActivity.enabled = true; 10271 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10272 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10273 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10274 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10275 | ActivityInfo.CONFIG_ORIENTATION 10276 | ActivityInfo.CONFIG_KEYBOARD 10277 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10278 mResolveInfo.activityInfo = mResolveActivity; 10279 mResolveInfo.priority = 0; 10280 mResolveInfo.preferredOrder = 0; 10281 mResolveInfo.match = 0; 10282 mResolveComponentName = new ComponentName( 10283 mAndroidApplication.packageName, mResolveActivity.name); 10284 } 10285 } 10286 } 10287 } 10288 10289 ArrayList<PackageParser.Package> clientLibPkgs = null; 10290 // writer 10291 synchronized (mPackages) { 10292 boolean hasStaticSharedLibs = false; 10293 10294 // Any app can add new static shared libraries 10295 if (pkg.staticSharedLibName != null) { 10296 // Static shared libs don't allow renaming as they have synthetic package 10297 // names to allow install of multiple versions, so use name from manifest. 10298 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10299 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10300 pkg.manifestPackageName, pkg.mVersionCode)) { 10301 hasStaticSharedLibs = true; 10302 } else { 10303 Slog.w(TAG, "Package " + pkg.packageName + " library " 10304 + pkg.staticSharedLibName + " already exists; skipping"); 10305 } 10306 // Static shared libs cannot be updated once installed since they 10307 // use synthetic package name which includes the version code, so 10308 // not need to update other packages's shared lib dependencies. 10309 } 10310 10311 if (!hasStaticSharedLibs 10312 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10313 // Only system apps can add new dynamic shared libraries. 10314 if (pkg.libraryNames != null) { 10315 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10316 String name = pkg.libraryNames.get(i); 10317 boolean allowed = false; 10318 if (pkg.isUpdatedSystemApp()) { 10319 // New library entries can only be added through the 10320 // system image. This is important to get rid of a lot 10321 // of nasty edge cases: for example if we allowed a non- 10322 // system update of the app to add a library, then uninstalling 10323 // the update would make the library go away, and assumptions 10324 // we made such as through app install filtering would now 10325 // have allowed apps on the device which aren't compatible 10326 // with it. Better to just have the restriction here, be 10327 // conservative, and create many fewer cases that can negatively 10328 // impact the user experience. 10329 final PackageSetting sysPs = mSettings 10330 .getDisabledSystemPkgLPr(pkg.packageName); 10331 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10332 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10333 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10334 allowed = true; 10335 break; 10336 } 10337 } 10338 } 10339 } else { 10340 allowed = true; 10341 } 10342 if (allowed) { 10343 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10344 SharedLibraryInfo.VERSION_UNDEFINED, 10345 SharedLibraryInfo.TYPE_DYNAMIC, 10346 pkg.packageName, pkg.mVersionCode)) { 10347 Slog.w(TAG, "Package " + pkg.packageName + " library " 10348 + name + " already exists; skipping"); 10349 } 10350 } else { 10351 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10352 + name + " that is not declared on system image; skipping"); 10353 } 10354 } 10355 10356 if ((scanFlags & SCAN_BOOTING) == 0) { 10357 // If we are not booting, we need to update any applications 10358 // that are clients of our shared library. If we are booting, 10359 // this will all be done once the scan is complete. 10360 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10361 } 10362 } 10363 } 10364 } 10365 10366 if ((scanFlags & SCAN_BOOTING) != 0) { 10367 // No apps can run during boot scan, so they don't need to be frozen 10368 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10369 // Caller asked to not kill app, so it's probably not frozen 10370 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10371 // Caller asked us to ignore frozen check for some reason; they 10372 // probably didn't know the package name 10373 } else { 10374 // We're doing major surgery on this package, so it better be frozen 10375 // right now to keep it from launching 10376 checkPackageFrozen(pkgName); 10377 } 10378 10379 // Also need to kill any apps that are dependent on the library. 10380 if (clientLibPkgs != null) { 10381 for (int i=0; i<clientLibPkgs.size(); i++) { 10382 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10383 killApplication(clientPkg.applicationInfo.packageName, 10384 clientPkg.applicationInfo.uid, "update lib"); 10385 } 10386 } 10387 10388 // writer 10389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10390 10391 synchronized (mPackages) { 10392 // We don't expect installation to fail beyond this point 10393 10394 // Add the new setting to mSettings 10395 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10396 // Add the new setting to mPackages 10397 mPackages.put(pkg.applicationInfo.packageName, pkg); 10398 // Make sure we don't accidentally delete its data. 10399 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10400 while (iter.hasNext()) { 10401 PackageCleanItem item = iter.next(); 10402 if (pkgName.equals(item.packageName)) { 10403 iter.remove(); 10404 } 10405 } 10406 10407 // Add the package's KeySets to the global KeySetManagerService 10408 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10409 ksms.addScannedPackageLPw(pkg); 10410 10411 int N = pkg.providers.size(); 10412 StringBuilder r = null; 10413 int i; 10414 for (i=0; i<N; i++) { 10415 PackageParser.Provider p = pkg.providers.get(i); 10416 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10417 p.info.processName); 10418 mProviders.addProvider(p); 10419 p.syncable = p.info.isSyncable; 10420 if (p.info.authority != null) { 10421 String names[] = p.info.authority.split(";"); 10422 p.info.authority = null; 10423 for (int j = 0; j < names.length; j++) { 10424 if (j == 1 && p.syncable) { 10425 // We only want the first authority for a provider to possibly be 10426 // syncable, so if we already added this provider using a different 10427 // authority clear the syncable flag. We copy the provider before 10428 // changing it because the mProviders object contains a reference 10429 // to a provider that we don't want to change. 10430 // Only do this for the second authority since the resulting provider 10431 // object can be the same for all future authorities for this provider. 10432 p = new PackageParser.Provider(p); 10433 p.syncable = false; 10434 } 10435 if (!mProvidersByAuthority.containsKey(names[j])) { 10436 mProvidersByAuthority.put(names[j], p); 10437 if (p.info.authority == null) { 10438 p.info.authority = names[j]; 10439 } else { 10440 p.info.authority = p.info.authority + ";" + names[j]; 10441 } 10442 if (DEBUG_PACKAGE_SCANNING) { 10443 if (chatty) 10444 Log.d(TAG, "Registered content provider: " + names[j] 10445 + ", className = " + p.info.name + ", isSyncable = " 10446 + p.info.isSyncable); 10447 } 10448 } else { 10449 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10450 Slog.w(TAG, "Skipping provider name " + names[j] + 10451 " (in package " + pkg.applicationInfo.packageName + 10452 "): name already used by " 10453 + ((other != null && other.getComponentName() != null) 10454 ? other.getComponentName().getPackageName() : "?")); 10455 } 10456 } 10457 } 10458 if (chatty) { 10459 if (r == null) { 10460 r = new StringBuilder(256); 10461 } else { 10462 r.append(' '); 10463 } 10464 r.append(p.info.name); 10465 } 10466 } 10467 if (r != null) { 10468 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10469 } 10470 10471 N = pkg.services.size(); 10472 r = null; 10473 for (i=0; i<N; i++) { 10474 PackageParser.Service s = pkg.services.get(i); 10475 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10476 s.info.processName); 10477 mServices.addService(s); 10478 if (chatty) { 10479 if (r == null) { 10480 r = new StringBuilder(256); 10481 } else { 10482 r.append(' '); 10483 } 10484 r.append(s.info.name); 10485 } 10486 } 10487 if (r != null) { 10488 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10489 } 10490 10491 N = pkg.receivers.size(); 10492 r = null; 10493 for (i=0; i<N; i++) { 10494 PackageParser.Activity a = pkg.receivers.get(i); 10495 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10496 a.info.processName); 10497 mReceivers.addActivity(a, "receiver"); 10498 if (chatty) { 10499 if (r == null) { 10500 r = new StringBuilder(256); 10501 } else { 10502 r.append(' '); 10503 } 10504 r.append(a.info.name); 10505 } 10506 } 10507 if (r != null) { 10508 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10509 } 10510 10511 N = pkg.activities.size(); 10512 r = null; 10513 for (i=0; i<N; i++) { 10514 PackageParser.Activity a = pkg.activities.get(i); 10515 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10516 a.info.processName); 10517 mActivities.addActivity(a, "activity"); 10518 if (chatty) { 10519 if (r == null) { 10520 r = new StringBuilder(256); 10521 } else { 10522 r.append(' '); 10523 } 10524 r.append(a.info.name); 10525 } 10526 } 10527 if (r != null) { 10528 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10529 } 10530 10531 N = pkg.permissionGroups.size(); 10532 r = null; 10533 for (i=0; i<N; i++) { 10534 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10535 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10536 final String curPackageName = cur == null ? null : cur.info.packageName; 10537 // Dont allow ephemeral apps to define new permission groups. 10538 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10539 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10540 + pg.info.packageName 10541 + " ignored: instant apps cannot define new permission groups."); 10542 continue; 10543 } 10544 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10545 if (cur == null || isPackageUpdate) { 10546 mPermissionGroups.put(pg.info.name, pg); 10547 if (chatty) { 10548 if (r == null) { 10549 r = new StringBuilder(256); 10550 } else { 10551 r.append(' '); 10552 } 10553 if (isPackageUpdate) { 10554 r.append("UPD:"); 10555 } 10556 r.append(pg.info.name); 10557 } 10558 } else { 10559 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10560 + pg.info.packageName + " ignored: original from " 10561 + cur.info.packageName); 10562 if (chatty) { 10563 if (r == null) { 10564 r = new StringBuilder(256); 10565 } else { 10566 r.append(' '); 10567 } 10568 r.append("DUP:"); 10569 r.append(pg.info.name); 10570 } 10571 } 10572 } 10573 if (r != null) { 10574 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10575 } 10576 10577 N = pkg.permissions.size(); 10578 r = null; 10579 for (i=0; i<N; i++) { 10580 PackageParser.Permission p = pkg.permissions.get(i); 10581 10582 // Dont allow ephemeral apps to define new permissions. 10583 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10584 Slog.w(TAG, "Permission " + p.info.name + " from package " 10585 + p.info.packageName 10586 + " ignored: instant apps cannot define new permissions."); 10587 continue; 10588 } 10589 10590 // Assume by default that we did not install this permission into the system. 10591 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10592 10593 // Now that permission groups have a special meaning, we ignore permission 10594 // groups for legacy apps to prevent unexpected behavior. In particular, 10595 // permissions for one app being granted to someone just becase they happen 10596 // to be in a group defined by another app (before this had no implications). 10597 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10598 p.group = mPermissionGroups.get(p.info.group); 10599 // Warn for a permission in an unknown group. 10600 if (p.info.group != null && p.group == null) { 10601 Slog.w(TAG, "Permission " + p.info.name + " from package " 10602 + p.info.packageName + " in an unknown group " + p.info.group); 10603 } 10604 } 10605 10606 ArrayMap<String, BasePermission> permissionMap = 10607 p.tree ? mSettings.mPermissionTrees 10608 : mSettings.mPermissions; 10609 BasePermission bp = permissionMap.get(p.info.name); 10610 10611 // Allow system apps to redefine non-system permissions 10612 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10613 final boolean currentOwnerIsSystem = (bp.perm != null 10614 && isSystemApp(bp.perm.owner)); 10615 if (isSystemApp(p.owner)) { 10616 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10617 // It's a built-in permission and no owner, take ownership now 10618 bp.packageSetting = pkgSetting; 10619 bp.perm = p; 10620 bp.uid = pkg.applicationInfo.uid; 10621 bp.sourcePackage = p.info.packageName; 10622 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10623 } else if (!currentOwnerIsSystem) { 10624 String msg = "New decl " + p.owner + " of permission " 10625 + p.info.name + " is system; overriding " + bp.sourcePackage; 10626 reportSettingsProblem(Log.WARN, msg); 10627 bp = null; 10628 } 10629 } 10630 } 10631 10632 if (bp == null) { 10633 bp = new BasePermission(p.info.name, p.info.packageName, 10634 BasePermission.TYPE_NORMAL); 10635 permissionMap.put(p.info.name, bp); 10636 } 10637 10638 if (bp.perm == null) { 10639 if (bp.sourcePackage == null 10640 || bp.sourcePackage.equals(p.info.packageName)) { 10641 BasePermission tree = findPermissionTreeLP(p.info.name); 10642 if (tree == null 10643 || tree.sourcePackage.equals(p.info.packageName)) { 10644 bp.packageSetting = pkgSetting; 10645 bp.perm = p; 10646 bp.uid = pkg.applicationInfo.uid; 10647 bp.sourcePackage = p.info.packageName; 10648 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10649 if (chatty) { 10650 if (r == null) { 10651 r = new StringBuilder(256); 10652 } else { 10653 r.append(' '); 10654 } 10655 r.append(p.info.name); 10656 } 10657 } else { 10658 Slog.w(TAG, "Permission " + p.info.name + " from package " 10659 + p.info.packageName + " ignored: base tree " 10660 + tree.name + " is from package " 10661 + tree.sourcePackage); 10662 } 10663 } else { 10664 Slog.w(TAG, "Permission " + p.info.name + " from package " 10665 + p.info.packageName + " ignored: original from " 10666 + bp.sourcePackage); 10667 } 10668 } else if (chatty) { 10669 if (r == null) { 10670 r = new StringBuilder(256); 10671 } else { 10672 r.append(' '); 10673 } 10674 r.append("DUP:"); 10675 r.append(p.info.name); 10676 } 10677 if (bp.perm == p) { 10678 bp.protectionLevel = p.info.protectionLevel; 10679 } 10680 } 10681 10682 if (r != null) { 10683 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10684 } 10685 10686 N = pkg.instrumentation.size(); 10687 r = null; 10688 for (i=0; i<N; i++) { 10689 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10690 a.info.packageName = pkg.applicationInfo.packageName; 10691 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10692 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10693 a.info.splitNames = pkg.splitNames; 10694 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10695 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10696 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10697 a.info.dataDir = pkg.applicationInfo.dataDir; 10698 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10699 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10700 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10701 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10702 mInstrumentation.put(a.getComponentName(), a); 10703 if (chatty) { 10704 if (r == null) { 10705 r = new StringBuilder(256); 10706 } else { 10707 r.append(' '); 10708 } 10709 r.append(a.info.name); 10710 } 10711 } 10712 if (r != null) { 10713 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10714 } 10715 10716 if (pkg.protectedBroadcasts != null) { 10717 N = pkg.protectedBroadcasts.size(); 10718 for (i=0; i<N; i++) { 10719 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10720 } 10721 } 10722 } 10723 10724 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10725 } 10726 10727 /** 10728 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10729 * is derived purely on the basis of the contents of {@code scanFile} and 10730 * {@code cpuAbiOverride}. 10731 * 10732 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10733 */ 10734 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10735 String cpuAbiOverride, boolean extractLibs, 10736 File appLib32InstallDir) 10737 throws PackageManagerException { 10738 // Give ourselves some initial paths; we'll come back for another 10739 // pass once we've determined ABI below. 10740 setNativeLibraryPaths(pkg, appLib32InstallDir); 10741 10742 // We would never need to extract libs for forward-locked and external packages, 10743 // since the container service will do it for us. We shouldn't attempt to 10744 // extract libs from system app when it was not updated. 10745 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10746 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10747 extractLibs = false; 10748 } 10749 10750 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10751 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10752 10753 NativeLibraryHelper.Handle handle = null; 10754 try { 10755 handle = NativeLibraryHelper.Handle.create(pkg); 10756 // TODO(multiArch): This can be null for apps that didn't go through the 10757 // usual installation process. We can calculate it again, like we 10758 // do during install time. 10759 // 10760 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10761 // unnecessary. 10762 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10763 10764 // Null out the abis so that they can be recalculated. 10765 pkg.applicationInfo.primaryCpuAbi = null; 10766 pkg.applicationInfo.secondaryCpuAbi = null; 10767 if (isMultiArch(pkg.applicationInfo)) { 10768 // Warn if we've set an abiOverride for multi-lib packages.. 10769 // By definition, we need to copy both 32 and 64 bit libraries for 10770 // such packages. 10771 if (pkg.cpuAbiOverride != null 10772 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10773 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10774 } 10775 10776 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10777 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10778 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10779 if (extractLibs) { 10780 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10781 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10782 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10783 useIsaSpecificSubdirs); 10784 } else { 10785 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10786 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10787 } 10788 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10789 } 10790 10791 maybeThrowExceptionForMultiArchCopy( 10792 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10793 10794 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10795 if (extractLibs) { 10796 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10797 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10798 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10799 useIsaSpecificSubdirs); 10800 } else { 10801 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10802 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10803 } 10804 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10805 } 10806 10807 maybeThrowExceptionForMultiArchCopy( 10808 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10809 10810 if (abi64 >= 0) { 10811 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10812 } 10813 10814 if (abi32 >= 0) { 10815 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10816 if (abi64 >= 0) { 10817 if (pkg.use32bitAbi) { 10818 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10819 pkg.applicationInfo.primaryCpuAbi = abi; 10820 } else { 10821 pkg.applicationInfo.secondaryCpuAbi = abi; 10822 } 10823 } else { 10824 pkg.applicationInfo.primaryCpuAbi = abi; 10825 } 10826 } 10827 10828 } else { 10829 String[] abiList = (cpuAbiOverride != null) ? 10830 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10831 10832 // Enable gross and lame hacks for apps that are built with old 10833 // SDK tools. We must scan their APKs for renderscript bitcode and 10834 // not launch them if it's present. Don't bother checking on devices 10835 // that don't have 64 bit support. 10836 boolean needsRenderScriptOverride = false; 10837 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10838 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10839 abiList = Build.SUPPORTED_32_BIT_ABIS; 10840 needsRenderScriptOverride = true; 10841 } 10842 10843 final int copyRet; 10844 if (extractLibs) { 10845 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10846 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10847 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10848 } else { 10849 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10850 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10851 } 10852 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10853 10854 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10855 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10856 "Error unpackaging native libs for app, errorCode=" + copyRet); 10857 } 10858 10859 if (copyRet >= 0) { 10860 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10861 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10862 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10863 } else if (needsRenderScriptOverride) { 10864 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10865 } 10866 } 10867 } catch (IOException ioe) { 10868 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10869 } finally { 10870 IoUtils.closeQuietly(handle); 10871 } 10872 10873 // Now that we've calculated the ABIs and determined if it's an internal app, 10874 // we will go ahead and populate the nativeLibraryPath. 10875 setNativeLibraryPaths(pkg, appLib32InstallDir); 10876 } 10877 10878 /** 10879 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10880 * i.e, so that all packages can be run inside a single process if required. 10881 * 10882 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10883 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10884 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10885 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10886 * updating a package that belongs to a shared user. 10887 * 10888 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10889 * adds unnecessary complexity. 10890 */ 10891 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10892 PackageParser.Package scannedPackage) { 10893 String requiredInstructionSet = null; 10894 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10895 requiredInstructionSet = VMRuntime.getInstructionSet( 10896 scannedPackage.applicationInfo.primaryCpuAbi); 10897 } 10898 10899 PackageSetting requirer = null; 10900 for (PackageSetting ps : packagesForUser) { 10901 // If packagesForUser contains scannedPackage, we skip it. This will happen 10902 // when scannedPackage is an update of an existing package. Without this check, 10903 // we will never be able to change the ABI of any package belonging to a shared 10904 // user, even if it's compatible with other packages. 10905 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10906 if (ps.primaryCpuAbiString == null) { 10907 continue; 10908 } 10909 10910 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10911 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10912 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10913 // this but there's not much we can do. 10914 String errorMessage = "Instruction set mismatch, " 10915 + ((requirer == null) ? "[caller]" : requirer) 10916 + " requires " + requiredInstructionSet + " whereas " + ps 10917 + " requires " + instructionSet; 10918 Slog.w(TAG, errorMessage); 10919 } 10920 10921 if (requiredInstructionSet == null) { 10922 requiredInstructionSet = instructionSet; 10923 requirer = ps; 10924 } 10925 } 10926 } 10927 10928 if (requiredInstructionSet != null) { 10929 String adjustedAbi; 10930 if (requirer != null) { 10931 // requirer != null implies that either scannedPackage was null or that scannedPackage 10932 // did not require an ABI, in which case we have to adjust scannedPackage to match 10933 // the ABI of the set (which is the same as requirer's ABI) 10934 adjustedAbi = requirer.primaryCpuAbiString; 10935 if (scannedPackage != null) { 10936 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10937 } 10938 } else { 10939 // requirer == null implies that we're updating all ABIs in the set to 10940 // match scannedPackage. 10941 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10942 } 10943 10944 for (PackageSetting ps : packagesForUser) { 10945 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10946 if (ps.primaryCpuAbiString != null) { 10947 continue; 10948 } 10949 10950 ps.primaryCpuAbiString = adjustedAbi; 10951 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10952 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10953 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10954 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10955 + " (requirer=" 10956 + (requirer != null ? requirer.pkg : "null") 10957 + ", scannedPackage=" 10958 + (scannedPackage != null ? scannedPackage : "null") 10959 + ")"); 10960 try { 10961 mInstaller.rmdex(ps.codePathString, 10962 getDexCodeInstructionSet(getPreferredInstructionSet())); 10963 } catch (InstallerException ignored) { 10964 } 10965 } 10966 } 10967 } 10968 } 10969 } 10970 10971 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10972 synchronized (mPackages) { 10973 mResolverReplaced = true; 10974 // Set up information for custom user intent resolution activity. 10975 mResolveActivity.applicationInfo = pkg.applicationInfo; 10976 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10977 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10978 mResolveActivity.processName = pkg.applicationInfo.packageName; 10979 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10980 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10981 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10982 mResolveActivity.theme = 0; 10983 mResolveActivity.exported = true; 10984 mResolveActivity.enabled = true; 10985 mResolveInfo.activityInfo = mResolveActivity; 10986 mResolveInfo.priority = 0; 10987 mResolveInfo.preferredOrder = 0; 10988 mResolveInfo.match = 0; 10989 mResolveComponentName = mCustomResolverComponentName; 10990 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10991 mResolveComponentName); 10992 } 10993 } 10994 10995 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10996 if (installerActivity == null) { 10997 if (DEBUG_EPHEMERAL) { 10998 Slog.d(TAG, "Clear ephemeral installer activity"); 10999 } 11000 mInstantAppInstallerActivity = null; 11001 return; 11002 } 11003 11004 if (DEBUG_EPHEMERAL) { 11005 Slog.d(TAG, "Set ephemeral installer activity: " 11006 + installerActivity.getComponentName()); 11007 } 11008 // Set up information for ephemeral installer activity 11009 mInstantAppInstallerActivity = installerActivity; 11010 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11011 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11012 mInstantAppInstallerActivity.exported = true; 11013 mInstantAppInstallerActivity.enabled = true; 11014 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11015 mInstantAppInstallerInfo.priority = 0; 11016 mInstantAppInstallerInfo.preferredOrder = 1; 11017 mInstantAppInstallerInfo.isDefault = true; 11018 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11019 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11020 } 11021 11022 private static String calculateBundledApkRoot(final String codePathString) { 11023 final File codePath = new File(codePathString); 11024 final File codeRoot; 11025 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11026 codeRoot = Environment.getRootDirectory(); 11027 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11028 codeRoot = Environment.getOemDirectory(); 11029 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11030 codeRoot = Environment.getVendorDirectory(); 11031 } else { 11032 // Unrecognized code path; take its top real segment as the apk root: 11033 // e.g. /something/app/blah.apk => /something 11034 try { 11035 File f = codePath.getCanonicalFile(); 11036 File parent = f.getParentFile(); // non-null because codePath is a file 11037 File tmp; 11038 while ((tmp = parent.getParentFile()) != null) { 11039 f = parent; 11040 parent = tmp; 11041 } 11042 codeRoot = f; 11043 Slog.w(TAG, "Unrecognized code path " 11044 + codePath + " - using " + codeRoot); 11045 } catch (IOException e) { 11046 // Can't canonicalize the code path -- shenanigans? 11047 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11048 return Environment.getRootDirectory().getPath(); 11049 } 11050 } 11051 return codeRoot.getPath(); 11052 } 11053 11054 /** 11055 * Derive and set the location of native libraries for the given package, 11056 * which varies depending on where and how the package was installed. 11057 */ 11058 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11059 final ApplicationInfo info = pkg.applicationInfo; 11060 final String codePath = pkg.codePath; 11061 final File codeFile = new File(codePath); 11062 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11063 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11064 11065 info.nativeLibraryRootDir = null; 11066 info.nativeLibraryRootRequiresIsa = false; 11067 info.nativeLibraryDir = null; 11068 info.secondaryNativeLibraryDir = null; 11069 11070 if (isApkFile(codeFile)) { 11071 // Monolithic install 11072 if (bundledApp) { 11073 // If "/system/lib64/apkname" exists, assume that is the per-package 11074 // native library directory to use; otherwise use "/system/lib/apkname". 11075 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11076 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11077 getPrimaryInstructionSet(info)); 11078 11079 // This is a bundled system app so choose the path based on the ABI. 11080 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11081 // is just the default path. 11082 final String apkName = deriveCodePathName(codePath); 11083 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11084 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11085 apkName).getAbsolutePath(); 11086 11087 if (info.secondaryCpuAbi != null) { 11088 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11089 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11090 secondaryLibDir, apkName).getAbsolutePath(); 11091 } 11092 } else if (asecApp) { 11093 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11094 .getAbsolutePath(); 11095 } else { 11096 final String apkName = deriveCodePathName(codePath); 11097 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11098 .getAbsolutePath(); 11099 } 11100 11101 info.nativeLibraryRootRequiresIsa = false; 11102 info.nativeLibraryDir = info.nativeLibraryRootDir; 11103 } else { 11104 // Cluster install 11105 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11106 info.nativeLibraryRootRequiresIsa = true; 11107 11108 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11109 getPrimaryInstructionSet(info)).getAbsolutePath(); 11110 11111 if (info.secondaryCpuAbi != null) { 11112 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11113 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11114 } 11115 } 11116 } 11117 11118 /** 11119 * Calculate the abis and roots for a bundled app. These can uniquely 11120 * be determined from the contents of the system partition, i.e whether 11121 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11122 * of this information, and instead assume that the system was built 11123 * sensibly. 11124 */ 11125 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11126 PackageSetting pkgSetting) { 11127 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11128 11129 // If "/system/lib64/apkname" exists, assume that is the per-package 11130 // native library directory to use; otherwise use "/system/lib/apkname". 11131 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11132 setBundledAppAbi(pkg, apkRoot, apkName); 11133 // pkgSetting might be null during rescan following uninstall of updates 11134 // to a bundled app, so accommodate that possibility. The settings in 11135 // that case will be established later from the parsed package. 11136 // 11137 // If the settings aren't null, sync them up with what we've just derived. 11138 // note that apkRoot isn't stored in the package settings. 11139 if (pkgSetting != null) { 11140 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11141 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11142 } 11143 } 11144 11145 /** 11146 * Deduces the ABI of a bundled app and sets the relevant fields on the 11147 * parsed pkg object. 11148 * 11149 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11150 * under which system libraries are installed. 11151 * @param apkName the name of the installed package. 11152 */ 11153 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11154 final File codeFile = new File(pkg.codePath); 11155 11156 final boolean has64BitLibs; 11157 final boolean has32BitLibs; 11158 if (isApkFile(codeFile)) { 11159 // Monolithic install 11160 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11161 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11162 } else { 11163 // Cluster install 11164 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11165 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11166 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11167 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11168 has64BitLibs = (new File(rootDir, isa)).exists(); 11169 } else { 11170 has64BitLibs = false; 11171 } 11172 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11173 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11174 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11175 has32BitLibs = (new File(rootDir, isa)).exists(); 11176 } else { 11177 has32BitLibs = false; 11178 } 11179 } 11180 11181 if (has64BitLibs && !has32BitLibs) { 11182 // The package has 64 bit libs, but not 32 bit libs. Its primary 11183 // ABI should be 64 bit. We can safely assume here that the bundled 11184 // native libraries correspond to the most preferred ABI in the list. 11185 11186 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11187 pkg.applicationInfo.secondaryCpuAbi = null; 11188 } else if (has32BitLibs && !has64BitLibs) { 11189 // The package has 32 bit libs but not 64 bit libs. Its primary 11190 // ABI should be 32 bit. 11191 11192 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11193 pkg.applicationInfo.secondaryCpuAbi = null; 11194 } else if (has32BitLibs && has64BitLibs) { 11195 // The application has both 64 and 32 bit bundled libraries. We check 11196 // here that the app declares multiArch support, and warn if it doesn't. 11197 // 11198 // We will be lenient here and record both ABIs. The primary will be the 11199 // ABI that's higher on the list, i.e, a device that's configured to prefer 11200 // 64 bit apps will see a 64 bit primary ABI, 11201 11202 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11203 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11204 } 11205 11206 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11207 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11208 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11209 } else { 11210 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11211 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11212 } 11213 } else { 11214 pkg.applicationInfo.primaryCpuAbi = null; 11215 pkg.applicationInfo.secondaryCpuAbi = null; 11216 } 11217 } 11218 11219 private void killApplication(String pkgName, int appId, String reason) { 11220 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11221 } 11222 11223 private void killApplication(String pkgName, int appId, int userId, String reason) { 11224 // Request the ActivityManager to kill the process(only for existing packages) 11225 // so that we do not end up in a confused state while the user is still using the older 11226 // version of the application while the new one gets installed. 11227 final long token = Binder.clearCallingIdentity(); 11228 try { 11229 IActivityManager am = ActivityManager.getService(); 11230 if (am != null) { 11231 try { 11232 am.killApplication(pkgName, appId, userId, reason); 11233 } catch (RemoteException e) { 11234 } 11235 } 11236 } finally { 11237 Binder.restoreCallingIdentity(token); 11238 } 11239 } 11240 11241 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11242 // Remove the parent package setting 11243 PackageSetting ps = (PackageSetting) pkg.mExtras; 11244 if (ps != null) { 11245 removePackageLI(ps, chatty); 11246 } 11247 // Remove the child package setting 11248 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11249 for (int i = 0; i < childCount; i++) { 11250 PackageParser.Package childPkg = pkg.childPackages.get(i); 11251 ps = (PackageSetting) childPkg.mExtras; 11252 if (ps != null) { 11253 removePackageLI(ps, chatty); 11254 } 11255 } 11256 } 11257 11258 void removePackageLI(PackageSetting ps, boolean chatty) { 11259 if (DEBUG_INSTALL) { 11260 if (chatty) 11261 Log.d(TAG, "Removing package " + ps.name); 11262 } 11263 11264 // writer 11265 synchronized (mPackages) { 11266 mPackages.remove(ps.name); 11267 final PackageParser.Package pkg = ps.pkg; 11268 if (pkg != null) { 11269 cleanPackageDataStructuresLILPw(pkg, chatty); 11270 } 11271 } 11272 } 11273 11274 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11275 if (DEBUG_INSTALL) { 11276 if (chatty) 11277 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11278 } 11279 11280 // writer 11281 synchronized (mPackages) { 11282 // Remove the parent package 11283 mPackages.remove(pkg.applicationInfo.packageName); 11284 cleanPackageDataStructuresLILPw(pkg, chatty); 11285 11286 // Remove the child packages 11287 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11288 for (int i = 0; i < childCount; i++) { 11289 PackageParser.Package childPkg = pkg.childPackages.get(i); 11290 mPackages.remove(childPkg.applicationInfo.packageName); 11291 cleanPackageDataStructuresLILPw(childPkg, chatty); 11292 } 11293 } 11294 } 11295 11296 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11297 int N = pkg.providers.size(); 11298 StringBuilder r = null; 11299 int i; 11300 for (i=0; i<N; i++) { 11301 PackageParser.Provider p = pkg.providers.get(i); 11302 mProviders.removeProvider(p); 11303 if (p.info.authority == null) { 11304 11305 /* There was another ContentProvider with this authority when 11306 * this app was installed so this authority is null, 11307 * Ignore it as we don't have to unregister the provider. 11308 */ 11309 continue; 11310 } 11311 String names[] = p.info.authority.split(";"); 11312 for (int j = 0; j < names.length; j++) { 11313 if (mProvidersByAuthority.get(names[j]) == p) { 11314 mProvidersByAuthority.remove(names[j]); 11315 if (DEBUG_REMOVE) { 11316 if (chatty) 11317 Log.d(TAG, "Unregistered content provider: " + names[j] 11318 + ", className = " + p.info.name + ", isSyncable = " 11319 + p.info.isSyncable); 11320 } 11321 } 11322 } 11323 if (DEBUG_REMOVE && chatty) { 11324 if (r == null) { 11325 r = new StringBuilder(256); 11326 } else { 11327 r.append(' '); 11328 } 11329 r.append(p.info.name); 11330 } 11331 } 11332 if (r != null) { 11333 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11334 } 11335 11336 N = pkg.services.size(); 11337 r = null; 11338 for (i=0; i<N; i++) { 11339 PackageParser.Service s = pkg.services.get(i); 11340 mServices.removeService(s); 11341 if (chatty) { 11342 if (r == null) { 11343 r = new StringBuilder(256); 11344 } else { 11345 r.append(' '); 11346 } 11347 r.append(s.info.name); 11348 } 11349 } 11350 if (r != null) { 11351 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11352 } 11353 11354 N = pkg.receivers.size(); 11355 r = null; 11356 for (i=0; i<N; i++) { 11357 PackageParser.Activity a = pkg.receivers.get(i); 11358 mReceivers.removeActivity(a, "receiver"); 11359 if (DEBUG_REMOVE && chatty) { 11360 if (r == null) { 11361 r = new StringBuilder(256); 11362 } else { 11363 r.append(' '); 11364 } 11365 r.append(a.info.name); 11366 } 11367 } 11368 if (r != null) { 11369 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11370 } 11371 11372 N = pkg.activities.size(); 11373 r = null; 11374 for (i=0; i<N; i++) { 11375 PackageParser.Activity a = pkg.activities.get(i); 11376 mActivities.removeActivity(a, "activity"); 11377 if (DEBUG_REMOVE && chatty) { 11378 if (r == null) { 11379 r = new StringBuilder(256); 11380 } else { 11381 r.append(' '); 11382 } 11383 r.append(a.info.name); 11384 } 11385 } 11386 if (r != null) { 11387 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11388 } 11389 11390 N = pkg.permissions.size(); 11391 r = null; 11392 for (i=0; i<N; i++) { 11393 PackageParser.Permission p = pkg.permissions.get(i); 11394 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11395 if (bp == null) { 11396 bp = mSettings.mPermissionTrees.get(p.info.name); 11397 } 11398 if (bp != null && bp.perm == p) { 11399 bp.perm = null; 11400 if (DEBUG_REMOVE && chatty) { 11401 if (r == null) { 11402 r = new StringBuilder(256); 11403 } else { 11404 r.append(' '); 11405 } 11406 r.append(p.info.name); 11407 } 11408 } 11409 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11410 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11411 if (appOpPkgs != null) { 11412 appOpPkgs.remove(pkg.packageName); 11413 } 11414 } 11415 } 11416 if (r != null) { 11417 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11418 } 11419 11420 N = pkg.requestedPermissions.size(); 11421 r = null; 11422 for (i=0; i<N; i++) { 11423 String perm = pkg.requestedPermissions.get(i); 11424 BasePermission bp = mSettings.mPermissions.get(perm); 11425 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11426 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11427 if (appOpPkgs != null) { 11428 appOpPkgs.remove(pkg.packageName); 11429 if (appOpPkgs.isEmpty()) { 11430 mAppOpPermissionPackages.remove(perm); 11431 } 11432 } 11433 } 11434 } 11435 if (r != null) { 11436 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11437 } 11438 11439 N = pkg.instrumentation.size(); 11440 r = null; 11441 for (i=0; i<N; i++) { 11442 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11443 mInstrumentation.remove(a.getComponentName()); 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, " Instrumentation: " + r); 11455 } 11456 11457 r = null; 11458 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11459 // Only system apps can hold shared libraries. 11460 if (pkg.libraryNames != null) { 11461 for (i = 0; i < pkg.libraryNames.size(); i++) { 11462 String name = pkg.libraryNames.get(i); 11463 if (removeSharedLibraryLPw(name, 0)) { 11464 if (DEBUG_REMOVE && chatty) { 11465 if (r == null) { 11466 r = new StringBuilder(256); 11467 } else { 11468 r.append(' '); 11469 } 11470 r.append(name); 11471 } 11472 } 11473 } 11474 } 11475 } 11476 11477 r = null; 11478 11479 // Any package can hold static shared libraries. 11480 if (pkg.staticSharedLibName != null) { 11481 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11482 if (DEBUG_REMOVE && chatty) { 11483 if (r == null) { 11484 r = new StringBuilder(256); 11485 } else { 11486 r.append(' '); 11487 } 11488 r.append(pkg.staticSharedLibName); 11489 } 11490 } 11491 } 11492 11493 if (r != null) { 11494 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11495 } 11496 } 11497 11498 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11499 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11500 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11501 return true; 11502 } 11503 } 11504 return false; 11505 } 11506 11507 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11508 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11509 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11510 11511 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11512 // Update the parent permissions 11513 updatePermissionsLPw(pkg.packageName, pkg, flags); 11514 // Update the child permissions 11515 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11516 for (int i = 0; i < childCount; i++) { 11517 PackageParser.Package childPkg = pkg.childPackages.get(i); 11518 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11519 } 11520 } 11521 11522 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11523 int flags) { 11524 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11525 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11526 } 11527 11528 private void updatePermissionsLPw(String changingPkg, 11529 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11530 // Make sure there are no dangling permission trees. 11531 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11532 while (it.hasNext()) { 11533 final BasePermission bp = it.next(); 11534 if (bp.packageSetting == null) { 11535 // We may not yet have parsed the package, so just see if 11536 // we still know about its settings. 11537 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11538 } 11539 if (bp.packageSetting == null) { 11540 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11541 + " from package " + bp.sourcePackage); 11542 it.remove(); 11543 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11544 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11545 Slog.i(TAG, "Removing old permission tree: " + bp.name 11546 + " from package " + bp.sourcePackage); 11547 flags |= UPDATE_PERMISSIONS_ALL; 11548 it.remove(); 11549 } 11550 } 11551 } 11552 11553 // Make sure all dynamic permissions have been assigned to a package, 11554 // and make sure there are no dangling permissions. 11555 it = mSettings.mPermissions.values().iterator(); 11556 while (it.hasNext()) { 11557 final BasePermission bp = it.next(); 11558 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11559 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11560 + bp.name + " pkg=" + bp.sourcePackage 11561 + " info=" + bp.pendingInfo); 11562 if (bp.packageSetting == null && bp.pendingInfo != null) { 11563 final BasePermission tree = findPermissionTreeLP(bp.name); 11564 if (tree != null && tree.perm != null) { 11565 bp.packageSetting = tree.packageSetting; 11566 bp.perm = new PackageParser.Permission(tree.perm.owner, 11567 new PermissionInfo(bp.pendingInfo)); 11568 bp.perm.info.packageName = tree.perm.info.packageName; 11569 bp.perm.info.name = bp.name; 11570 bp.uid = tree.uid; 11571 } 11572 } 11573 } 11574 if (bp.packageSetting == null) { 11575 // We may not yet have parsed the package, so just see if 11576 // we still know about its settings. 11577 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11578 } 11579 if (bp.packageSetting == null) { 11580 Slog.w(TAG, "Removing dangling permission: " + bp.name 11581 + " from package " + bp.sourcePackage); 11582 it.remove(); 11583 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11584 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11585 Slog.i(TAG, "Removing old permission: " + bp.name 11586 + " from package " + bp.sourcePackage); 11587 flags |= UPDATE_PERMISSIONS_ALL; 11588 it.remove(); 11589 } 11590 } 11591 } 11592 11593 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11594 // Now update the permissions for all packages, in particular 11595 // replace the granted permissions of the system packages. 11596 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11597 for (PackageParser.Package pkg : mPackages.values()) { 11598 if (pkg != pkgInfo) { 11599 // Only replace for packages on requested volume 11600 final String volumeUuid = getVolumeUuidForPackage(pkg); 11601 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11602 && Objects.equals(replaceVolumeUuid, volumeUuid); 11603 grantPermissionsLPw(pkg, replace, changingPkg); 11604 } 11605 } 11606 } 11607 11608 if (pkgInfo != null) { 11609 // Only replace for packages on requested volume 11610 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11611 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11612 && Objects.equals(replaceVolumeUuid, volumeUuid); 11613 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11614 } 11615 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11616 } 11617 11618 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11619 String packageOfInterest) { 11620 // IMPORTANT: There are two types of permissions: install and runtime. 11621 // Install time permissions are granted when the app is installed to 11622 // all device users and users added in the future. Runtime permissions 11623 // are granted at runtime explicitly to specific users. Normal and signature 11624 // protected permissions are install time permissions. Dangerous permissions 11625 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11626 // otherwise they are runtime permissions. This function does not manage 11627 // runtime permissions except for the case an app targeting Lollipop MR1 11628 // being upgraded to target a newer SDK, in which case dangerous permissions 11629 // are transformed from install time to runtime ones. 11630 11631 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11632 if (ps == null) { 11633 return; 11634 } 11635 11636 PermissionsState permissionsState = ps.getPermissionsState(); 11637 PermissionsState origPermissions = permissionsState; 11638 11639 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11640 11641 boolean runtimePermissionsRevoked = false; 11642 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11643 11644 boolean changedInstallPermission = false; 11645 11646 if (replace) { 11647 ps.installPermissionsFixed = false; 11648 if (!ps.isSharedUser()) { 11649 origPermissions = new PermissionsState(permissionsState); 11650 permissionsState.reset(); 11651 } else { 11652 // We need to know only about runtime permission changes since the 11653 // calling code always writes the install permissions state but 11654 // the runtime ones are written only if changed. The only cases of 11655 // changed runtime permissions here are promotion of an install to 11656 // runtime and revocation of a runtime from a shared user. 11657 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11658 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11659 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11660 runtimePermissionsRevoked = true; 11661 } 11662 } 11663 } 11664 11665 permissionsState.setGlobalGids(mGlobalGids); 11666 11667 final int N = pkg.requestedPermissions.size(); 11668 for (int i=0; i<N; i++) { 11669 final String name = pkg.requestedPermissions.get(i); 11670 final BasePermission bp = mSettings.mPermissions.get(name); 11671 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11672 >= Build.VERSION_CODES.M; 11673 11674 if (DEBUG_INSTALL) { 11675 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11676 } 11677 11678 if (bp == null || bp.packageSetting == null) { 11679 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11680 Slog.w(TAG, "Unknown permission " + name 11681 + " in package " + pkg.packageName); 11682 } 11683 continue; 11684 } 11685 11686 11687 // Limit ephemeral apps to ephemeral allowed permissions. 11688 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11689 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11690 + pkg.packageName); 11691 continue; 11692 } 11693 11694 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 11695 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 11696 + pkg.packageName); 11697 continue; 11698 } 11699 11700 final String perm = bp.name; 11701 boolean allowedSig = false; 11702 int grant = GRANT_DENIED; 11703 11704 // Keep track of app op permissions. 11705 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11706 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11707 if (pkgs == null) { 11708 pkgs = new ArraySet<>(); 11709 mAppOpPermissionPackages.put(bp.name, pkgs); 11710 } 11711 pkgs.add(pkg.packageName); 11712 } 11713 11714 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11715 switch (level) { 11716 case PermissionInfo.PROTECTION_NORMAL: { 11717 // For all apps normal permissions are install time ones. 11718 grant = GRANT_INSTALL; 11719 } break; 11720 11721 case PermissionInfo.PROTECTION_DANGEROUS: { 11722 // If a permission review is required for legacy apps we represent 11723 // their permissions as always granted runtime ones since we need 11724 // to keep the review required permission flag per user while an 11725 // install permission's state is shared across all users. 11726 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11727 // For legacy apps dangerous permissions are install time ones. 11728 grant = GRANT_INSTALL; 11729 } else if (origPermissions.hasInstallPermission(bp.name)) { 11730 // For legacy apps that became modern, install becomes runtime. 11731 grant = GRANT_UPGRADE; 11732 } else if (mPromoteSystemApps 11733 && isSystemApp(ps) 11734 && mExistingSystemPackages.contains(ps.name)) { 11735 // For legacy system apps, install becomes runtime. 11736 // We cannot check hasInstallPermission() for system apps since those 11737 // permissions were granted implicitly and not persisted pre-M. 11738 grant = GRANT_UPGRADE; 11739 } else { 11740 // For modern apps keep runtime permissions unchanged. 11741 grant = GRANT_RUNTIME; 11742 } 11743 } break; 11744 11745 case PermissionInfo.PROTECTION_SIGNATURE: { 11746 // For all apps signature permissions are install time ones. 11747 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11748 if (allowedSig) { 11749 grant = GRANT_INSTALL; 11750 } 11751 } break; 11752 } 11753 11754 if (DEBUG_INSTALL) { 11755 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11756 } 11757 11758 if (grant != GRANT_DENIED) { 11759 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11760 // If this is an existing, non-system package, then 11761 // we can't add any new permissions to it. 11762 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11763 // Except... if this is a permission that was added 11764 // to the platform (note: need to only do this when 11765 // updating the platform). 11766 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11767 grant = GRANT_DENIED; 11768 } 11769 } 11770 } 11771 11772 switch (grant) { 11773 case GRANT_INSTALL: { 11774 // Revoke this as runtime permission to handle the case of 11775 // a runtime permission being downgraded to an install one. 11776 // Also in permission review mode we keep dangerous permissions 11777 // for legacy apps 11778 for (int userId : UserManagerService.getInstance().getUserIds()) { 11779 if (origPermissions.getRuntimePermissionState( 11780 bp.name, userId) != null) { 11781 // Revoke the runtime permission and clear the flags. 11782 origPermissions.revokeRuntimePermission(bp, userId); 11783 origPermissions.updatePermissionFlags(bp, userId, 11784 PackageManager.MASK_PERMISSION_FLAGS, 0); 11785 // If we revoked a permission permission, we have to write. 11786 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11787 changedRuntimePermissionUserIds, userId); 11788 } 11789 } 11790 // Grant an install permission. 11791 if (permissionsState.grantInstallPermission(bp) != 11792 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11793 changedInstallPermission = true; 11794 } 11795 } break; 11796 11797 case GRANT_RUNTIME: { 11798 // Grant previously granted runtime permissions. 11799 for (int userId : UserManagerService.getInstance().getUserIds()) { 11800 PermissionState permissionState = origPermissions 11801 .getRuntimePermissionState(bp.name, userId); 11802 int flags = permissionState != null 11803 ? permissionState.getFlags() : 0; 11804 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11805 // Don't propagate the permission in a permission review mode if 11806 // the former was revoked, i.e. marked to not propagate on upgrade. 11807 // Note that in a permission review mode install permissions are 11808 // represented as constantly granted runtime ones since we need to 11809 // keep a per user state associated with the permission. Also the 11810 // revoke on upgrade flag is no longer applicable and is reset. 11811 final boolean revokeOnUpgrade = (flags & PackageManager 11812 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11813 if (revokeOnUpgrade) { 11814 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11815 // Since we changed the flags, we have to write. 11816 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11817 changedRuntimePermissionUserIds, userId); 11818 } 11819 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11820 if (permissionsState.grantRuntimePermission(bp, userId) == 11821 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11822 // If we cannot put the permission as it was, 11823 // we have to write. 11824 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11825 changedRuntimePermissionUserIds, userId); 11826 } 11827 } 11828 11829 // If the app supports runtime permissions no need for a review. 11830 if (mPermissionReviewRequired 11831 && appSupportsRuntimePermissions 11832 && (flags & PackageManager 11833 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11834 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11835 // Since we changed the flags, we have to write. 11836 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11837 changedRuntimePermissionUserIds, userId); 11838 } 11839 } else if (mPermissionReviewRequired 11840 && !appSupportsRuntimePermissions) { 11841 // For legacy apps that need a permission review, every new 11842 // runtime permission is granted but it is pending a review. 11843 // We also need to review only platform defined runtime 11844 // permissions as these are the only ones the platform knows 11845 // how to disable the API to simulate revocation as legacy 11846 // apps don't expect to run with revoked permissions. 11847 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11848 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11849 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11850 // We changed the flags, hence have to write. 11851 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11852 changedRuntimePermissionUserIds, userId); 11853 } 11854 } 11855 if (permissionsState.grantRuntimePermission(bp, userId) 11856 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11857 // We changed the permission, hence have to write. 11858 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11859 changedRuntimePermissionUserIds, userId); 11860 } 11861 } 11862 // Propagate the permission flags. 11863 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11864 } 11865 } break; 11866 11867 case GRANT_UPGRADE: { 11868 // Grant runtime permissions for a previously held install permission. 11869 PermissionState permissionState = origPermissions 11870 .getInstallPermissionState(bp.name); 11871 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11872 11873 if (origPermissions.revokeInstallPermission(bp) 11874 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11875 // We will be transferring the permission flags, so clear them. 11876 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11877 PackageManager.MASK_PERMISSION_FLAGS, 0); 11878 changedInstallPermission = true; 11879 } 11880 11881 // If the permission is not to be promoted to runtime we ignore it and 11882 // also its other flags as they are not applicable to install permissions. 11883 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11884 for (int userId : currentUserIds) { 11885 if (permissionsState.grantRuntimePermission(bp, userId) != 11886 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11887 // Transfer the permission flags. 11888 permissionsState.updatePermissionFlags(bp, userId, 11889 flags, flags); 11890 // If we granted the permission, we have to write. 11891 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11892 changedRuntimePermissionUserIds, userId); 11893 } 11894 } 11895 } 11896 } break; 11897 11898 default: { 11899 if (packageOfInterest == null 11900 || packageOfInterest.equals(pkg.packageName)) { 11901 Slog.w(TAG, "Not granting permission " + perm 11902 + " to package " + pkg.packageName 11903 + " because it was previously installed without"); 11904 } 11905 } break; 11906 } 11907 } else { 11908 if (permissionsState.revokeInstallPermission(bp) != 11909 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11910 // Also drop the permission flags. 11911 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11912 PackageManager.MASK_PERMISSION_FLAGS, 0); 11913 changedInstallPermission = true; 11914 Slog.i(TAG, "Un-granting permission " + perm 11915 + " from package " + pkg.packageName 11916 + " (protectionLevel=" + bp.protectionLevel 11917 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11918 + ")"); 11919 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11920 // Don't print warning for app op permissions, since it is fine for them 11921 // not to be granted, there is a UI for the user to decide. 11922 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11923 Slog.w(TAG, "Not granting permission " + perm 11924 + " to package " + pkg.packageName 11925 + " (protectionLevel=" + bp.protectionLevel 11926 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11927 + ")"); 11928 } 11929 } 11930 } 11931 } 11932 11933 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11934 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11935 // This is the first that we have heard about this package, so the 11936 // permissions we have now selected are fixed until explicitly 11937 // changed. 11938 ps.installPermissionsFixed = true; 11939 } 11940 11941 // Persist the runtime permissions state for users with changes. If permissions 11942 // were revoked because no app in the shared user declares them we have to 11943 // write synchronously to avoid losing runtime permissions state. 11944 for (int userId : changedRuntimePermissionUserIds) { 11945 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11946 } 11947 } 11948 11949 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11950 boolean allowed = false; 11951 final int NP = PackageParser.NEW_PERMISSIONS.length; 11952 for (int ip=0; ip<NP; ip++) { 11953 final PackageParser.NewPermissionInfo npi 11954 = PackageParser.NEW_PERMISSIONS[ip]; 11955 if (npi.name.equals(perm) 11956 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11957 allowed = true; 11958 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11959 + pkg.packageName); 11960 break; 11961 } 11962 } 11963 return allowed; 11964 } 11965 11966 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11967 BasePermission bp, PermissionsState origPermissions) { 11968 boolean privilegedPermission = (bp.protectionLevel 11969 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11970 boolean privappPermissionsDisable = 11971 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11972 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11973 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11974 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11975 && !platformPackage && platformPermission) { 11976 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11977 .getPrivAppPermissions(pkg.packageName); 11978 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11979 if (!whitelisted) { 11980 Slog.w(TAG, "Privileged permission " + perm + " for package " 11981 + pkg.packageName + " - not in privapp-permissions whitelist"); 11982 // Only report violations for apps on system image 11983 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11984 if (mPrivappPermissionsViolations == null) { 11985 mPrivappPermissionsViolations = new ArraySet<>(); 11986 } 11987 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11988 } 11989 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11990 return false; 11991 } 11992 } 11993 } 11994 boolean allowed = (compareSignatures( 11995 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11996 == PackageManager.SIGNATURE_MATCH) 11997 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11998 == PackageManager.SIGNATURE_MATCH); 11999 if (!allowed && privilegedPermission) { 12000 if (isSystemApp(pkg)) { 12001 // For updated system applications, a system permission 12002 // is granted only if it had been defined by the original application. 12003 if (pkg.isUpdatedSystemApp()) { 12004 final PackageSetting sysPs = mSettings 12005 .getDisabledSystemPkgLPr(pkg.packageName); 12006 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 12007 // If the original was granted this permission, we take 12008 // that grant decision as read and propagate it to the 12009 // update. 12010 if (sysPs.isPrivileged()) { 12011 allowed = true; 12012 } 12013 } else { 12014 // The system apk may have been updated with an older 12015 // version of the one on the data partition, but which 12016 // granted a new system permission that it didn't have 12017 // before. In this case we do want to allow the app to 12018 // now get the new permission if the ancestral apk is 12019 // privileged to get it. 12020 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 12021 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 12022 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 12023 allowed = true; 12024 break; 12025 } 12026 } 12027 } 12028 // Also if a privileged parent package on the system image or any of 12029 // its children requested a privileged permission, the updated child 12030 // packages can also get the permission. 12031 if (pkg.parentPackage != null) { 12032 final PackageSetting disabledSysParentPs = mSettings 12033 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 12034 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 12035 && disabledSysParentPs.isPrivileged()) { 12036 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 12037 allowed = true; 12038 } else if (disabledSysParentPs.pkg.childPackages != null) { 12039 final int count = disabledSysParentPs.pkg.childPackages.size(); 12040 for (int i = 0; i < count; i++) { 12041 PackageParser.Package disabledSysChildPkg = 12042 disabledSysParentPs.pkg.childPackages.get(i); 12043 if (isPackageRequestingPermission(disabledSysChildPkg, 12044 perm)) { 12045 allowed = true; 12046 break; 12047 } 12048 } 12049 } 12050 } 12051 } 12052 } 12053 } else { 12054 allowed = isPrivilegedApp(pkg); 12055 } 12056 } 12057 } 12058 if (!allowed) { 12059 if (!allowed && (bp.protectionLevel 12060 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 12061 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 12062 // If this was a previously normal/dangerous permission that got moved 12063 // to a system permission as part of the runtime permission redesign, then 12064 // we still want to blindly grant it to old apps. 12065 allowed = true; 12066 } 12067 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 12068 && pkg.packageName.equals(mRequiredInstallerPackage)) { 12069 // If this permission is to be granted to the system installer and 12070 // this app is an installer, then it gets the permission. 12071 allowed = true; 12072 } 12073 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 12074 && pkg.packageName.equals(mRequiredVerifierPackage)) { 12075 // If this permission is to be granted to the system verifier and 12076 // this app is a verifier, then it gets the permission. 12077 allowed = true; 12078 } 12079 if (!allowed && (bp.protectionLevel 12080 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 12081 && isSystemApp(pkg)) { 12082 // Any pre-installed system app is allowed to get this permission. 12083 allowed = true; 12084 } 12085 if (!allowed && (bp.protectionLevel 12086 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 12087 // For development permissions, a development permission 12088 // is granted only if it was already granted. 12089 allowed = origPermissions.hasInstallPermission(perm); 12090 } 12091 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 12092 && pkg.packageName.equals(mSetupWizardPackage)) { 12093 // If this permission is to be granted to the system setup wizard and 12094 // this app is a setup wizard, then it gets the permission. 12095 allowed = true; 12096 } 12097 } 12098 return allowed; 12099 } 12100 12101 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 12102 final int permCount = pkg.requestedPermissions.size(); 12103 for (int j = 0; j < permCount; j++) { 12104 String requestedPermission = pkg.requestedPermissions.get(j); 12105 if (permission.equals(requestedPermission)) { 12106 return true; 12107 } 12108 } 12109 return false; 12110 } 12111 12112 final class ActivityIntentResolver 12113 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12114 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12115 boolean defaultOnly, int userId) { 12116 if (!sUserManager.exists(userId)) return null; 12117 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12118 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12119 } 12120 12121 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12122 int userId) { 12123 if (!sUserManager.exists(userId)) return null; 12124 mFlags = flags; 12125 return super.queryIntent(intent, resolvedType, 12126 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12127 userId); 12128 } 12129 12130 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12131 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12132 if (!sUserManager.exists(userId)) return null; 12133 if (packageActivities == null) { 12134 return null; 12135 } 12136 mFlags = flags; 12137 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12138 final int N = packageActivities.size(); 12139 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12140 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12141 12142 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12143 for (int i = 0; i < N; ++i) { 12144 intentFilters = packageActivities.get(i).intents; 12145 if (intentFilters != null && intentFilters.size() > 0) { 12146 PackageParser.ActivityIntentInfo[] array = 12147 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12148 intentFilters.toArray(array); 12149 listCut.add(array); 12150 } 12151 } 12152 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12153 } 12154 12155 /** 12156 * Finds a privileged activity that matches the specified activity names. 12157 */ 12158 private PackageParser.Activity findMatchingActivity( 12159 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12160 for (PackageParser.Activity sysActivity : activityList) { 12161 if (sysActivity.info.name.equals(activityInfo.name)) { 12162 return sysActivity; 12163 } 12164 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12165 return sysActivity; 12166 } 12167 if (sysActivity.info.targetActivity != null) { 12168 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12169 return sysActivity; 12170 } 12171 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12172 return sysActivity; 12173 } 12174 } 12175 } 12176 return null; 12177 } 12178 12179 public class IterGenerator<E> { 12180 public Iterator<E> generate(ActivityIntentInfo info) { 12181 return null; 12182 } 12183 } 12184 12185 public class ActionIterGenerator extends IterGenerator<String> { 12186 @Override 12187 public Iterator<String> generate(ActivityIntentInfo info) { 12188 return info.actionsIterator(); 12189 } 12190 } 12191 12192 public class CategoriesIterGenerator extends IterGenerator<String> { 12193 @Override 12194 public Iterator<String> generate(ActivityIntentInfo info) { 12195 return info.categoriesIterator(); 12196 } 12197 } 12198 12199 public class SchemesIterGenerator extends IterGenerator<String> { 12200 @Override 12201 public Iterator<String> generate(ActivityIntentInfo info) { 12202 return info.schemesIterator(); 12203 } 12204 } 12205 12206 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12207 @Override 12208 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12209 return info.authoritiesIterator(); 12210 } 12211 } 12212 12213 /** 12214 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12215 * MODIFIED. Do not pass in a list that should not be changed. 12216 */ 12217 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12218 IterGenerator<T> generator, Iterator<T> searchIterator) { 12219 // loop through the set of actions; every one must be found in the intent filter 12220 while (searchIterator.hasNext()) { 12221 // we must have at least one filter in the list to consider a match 12222 if (intentList.size() == 0) { 12223 break; 12224 } 12225 12226 final T searchAction = searchIterator.next(); 12227 12228 // loop through the set of intent filters 12229 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12230 while (intentIter.hasNext()) { 12231 final ActivityIntentInfo intentInfo = intentIter.next(); 12232 boolean selectionFound = false; 12233 12234 // loop through the intent filter's selection criteria; at least one 12235 // of them must match the searched criteria 12236 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12237 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12238 final T intentSelection = intentSelectionIter.next(); 12239 if (intentSelection != null && intentSelection.equals(searchAction)) { 12240 selectionFound = true; 12241 break; 12242 } 12243 } 12244 12245 // the selection criteria wasn't found in this filter's set; this filter 12246 // is not a potential match 12247 if (!selectionFound) { 12248 intentIter.remove(); 12249 } 12250 } 12251 } 12252 } 12253 12254 private boolean isProtectedAction(ActivityIntentInfo filter) { 12255 final Iterator<String> actionsIter = filter.actionsIterator(); 12256 while (actionsIter != null && actionsIter.hasNext()) { 12257 final String filterAction = actionsIter.next(); 12258 if (PROTECTED_ACTIONS.contains(filterAction)) { 12259 return true; 12260 } 12261 } 12262 return false; 12263 } 12264 12265 /** 12266 * Adjusts the priority of the given intent filter according to policy. 12267 * <p> 12268 * <ul> 12269 * <li>The priority for non privileged applications is capped to '0'</li> 12270 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12271 * <li>The priority for unbundled updates to privileged applications is capped to the 12272 * priority defined on the system partition</li> 12273 * </ul> 12274 * <p> 12275 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12276 * allowed to obtain any priority on any action. 12277 */ 12278 private void adjustPriority( 12279 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12280 // nothing to do; priority is fine as-is 12281 if (intent.getPriority() <= 0) { 12282 return; 12283 } 12284 12285 final ActivityInfo activityInfo = intent.activity.info; 12286 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12287 12288 final boolean privilegedApp = 12289 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12290 if (!privilegedApp) { 12291 // non-privileged applications can never define a priority >0 12292 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12293 + " package: " + applicationInfo.packageName 12294 + " activity: " + intent.activity.className 12295 + " origPrio: " + intent.getPriority()); 12296 intent.setPriority(0); 12297 return; 12298 } 12299 12300 if (systemActivities == null) { 12301 // the system package is not disabled; we're parsing the system partition 12302 if (isProtectedAction(intent)) { 12303 if (mDeferProtectedFilters) { 12304 // We can't deal with these just yet. No component should ever obtain a 12305 // >0 priority for a protected actions, with ONE exception -- the setup 12306 // wizard. The setup wizard, however, cannot be known until we're able to 12307 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12308 // until all intent filters have been processed. Chicken, meet egg. 12309 // Let the filter temporarily have a high priority and rectify the 12310 // priorities after all system packages have been scanned. 12311 mProtectedFilters.add(intent); 12312 if (DEBUG_FILTERS) { 12313 Slog.i(TAG, "Protected action; save for later;" 12314 + " package: " + applicationInfo.packageName 12315 + " activity: " + intent.activity.className 12316 + " origPrio: " + intent.getPriority()); 12317 } 12318 return; 12319 } else { 12320 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12321 Slog.i(TAG, "No setup wizard;" 12322 + " All protected intents capped to priority 0"); 12323 } 12324 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12325 if (DEBUG_FILTERS) { 12326 Slog.i(TAG, "Found setup wizard;" 12327 + " allow priority " + intent.getPriority() + ";" 12328 + " package: " + intent.activity.info.packageName 12329 + " activity: " + intent.activity.className 12330 + " priority: " + intent.getPriority()); 12331 } 12332 // setup wizard gets whatever it wants 12333 return; 12334 } 12335 Slog.w(TAG, "Protected action; cap priority to 0;" 12336 + " package: " + intent.activity.info.packageName 12337 + " activity: " + intent.activity.className 12338 + " origPrio: " + intent.getPriority()); 12339 intent.setPriority(0); 12340 return; 12341 } 12342 } 12343 // privileged apps on the system image get whatever priority they request 12344 return; 12345 } 12346 12347 // privileged app unbundled update ... try to find the same activity 12348 final PackageParser.Activity foundActivity = 12349 findMatchingActivity(systemActivities, activityInfo); 12350 if (foundActivity == null) { 12351 // this is a new activity; it cannot obtain >0 priority 12352 if (DEBUG_FILTERS) { 12353 Slog.i(TAG, "New activity; cap priority to 0;" 12354 + " package: " + applicationInfo.packageName 12355 + " activity: " + intent.activity.className 12356 + " origPrio: " + intent.getPriority()); 12357 } 12358 intent.setPriority(0); 12359 return; 12360 } 12361 12362 // found activity, now check for filter equivalence 12363 12364 // a shallow copy is enough; we modify the list, not its contents 12365 final List<ActivityIntentInfo> intentListCopy = 12366 new ArrayList<>(foundActivity.intents); 12367 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12368 12369 // find matching action subsets 12370 final Iterator<String> actionsIterator = intent.actionsIterator(); 12371 if (actionsIterator != null) { 12372 getIntentListSubset( 12373 intentListCopy, new ActionIterGenerator(), actionsIterator); 12374 if (intentListCopy.size() == 0) { 12375 // no more intents to match; we're not equivalent 12376 if (DEBUG_FILTERS) { 12377 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12378 + " package: " + applicationInfo.packageName 12379 + " activity: " + intent.activity.className 12380 + " origPrio: " + intent.getPriority()); 12381 } 12382 intent.setPriority(0); 12383 return; 12384 } 12385 } 12386 12387 // find matching category subsets 12388 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12389 if (categoriesIterator != null) { 12390 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12391 categoriesIterator); 12392 if (intentListCopy.size() == 0) { 12393 // no more intents to match; we're not equivalent 12394 if (DEBUG_FILTERS) { 12395 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12396 + " package: " + applicationInfo.packageName 12397 + " activity: " + intent.activity.className 12398 + " origPrio: " + intent.getPriority()); 12399 } 12400 intent.setPriority(0); 12401 return; 12402 } 12403 } 12404 12405 // find matching schemes subsets 12406 final Iterator<String> schemesIterator = intent.schemesIterator(); 12407 if (schemesIterator != null) { 12408 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12409 schemesIterator); 12410 if (intentListCopy.size() == 0) { 12411 // no more intents to match; we're not equivalent 12412 if (DEBUG_FILTERS) { 12413 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12414 + " package: " + applicationInfo.packageName 12415 + " activity: " + intent.activity.className 12416 + " origPrio: " + intent.getPriority()); 12417 } 12418 intent.setPriority(0); 12419 return; 12420 } 12421 } 12422 12423 // find matching authorities subsets 12424 final Iterator<IntentFilter.AuthorityEntry> 12425 authoritiesIterator = intent.authoritiesIterator(); 12426 if (authoritiesIterator != null) { 12427 getIntentListSubset(intentListCopy, 12428 new AuthoritiesIterGenerator(), 12429 authoritiesIterator); 12430 if (intentListCopy.size() == 0) { 12431 // no more intents to match; we're not equivalent 12432 if (DEBUG_FILTERS) { 12433 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12434 + " package: " + applicationInfo.packageName 12435 + " activity: " + intent.activity.className 12436 + " origPrio: " + intent.getPriority()); 12437 } 12438 intent.setPriority(0); 12439 return; 12440 } 12441 } 12442 12443 // we found matching filter(s); app gets the max priority of all intents 12444 int cappedPriority = 0; 12445 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12446 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12447 } 12448 if (intent.getPriority() > cappedPriority) { 12449 if (DEBUG_FILTERS) { 12450 Slog.i(TAG, "Found matching filter(s);" 12451 + " cap priority to " + cappedPriority + ";" 12452 + " package: " + applicationInfo.packageName 12453 + " activity: " + intent.activity.className 12454 + " origPrio: " + intent.getPriority()); 12455 } 12456 intent.setPriority(cappedPriority); 12457 return; 12458 } 12459 // all this for nothing; the requested priority was <= what was on the system 12460 } 12461 12462 public final void addActivity(PackageParser.Activity a, String type) { 12463 mActivities.put(a.getComponentName(), a); 12464 if (DEBUG_SHOW_INFO) 12465 Log.v( 12466 TAG, " " + type + " " + 12467 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12468 if (DEBUG_SHOW_INFO) 12469 Log.v(TAG, " Class=" + a.info.name); 12470 final int NI = a.intents.size(); 12471 for (int j=0; j<NI; j++) { 12472 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12473 if ("activity".equals(type)) { 12474 final PackageSetting ps = 12475 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12476 final List<PackageParser.Activity> systemActivities = 12477 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12478 adjustPriority(systemActivities, intent); 12479 } 12480 if (DEBUG_SHOW_INFO) { 12481 Log.v(TAG, " IntentFilter:"); 12482 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12483 } 12484 if (!intent.debugCheck()) { 12485 Log.w(TAG, "==> For Activity " + a.info.name); 12486 } 12487 addFilter(intent); 12488 } 12489 } 12490 12491 public final void removeActivity(PackageParser.Activity a, String type) { 12492 mActivities.remove(a.getComponentName()); 12493 if (DEBUG_SHOW_INFO) { 12494 Log.v(TAG, " " + type + " " 12495 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12496 : a.info.name) + ":"); 12497 Log.v(TAG, " Class=" + a.info.name); 12498 } 12499 final int NI = a.intents.size(); 12500 for (int j=0; j<NI; j++) { 12501 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12502 if (DEBUG_SHOW_INFO) { 12503 Log.v(TAG, " IntentFilter:"); 12504 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12505 } 12506 removeFilter(intent); 12507 } 12508 } 12509 12510 @Override 12511 protected boolean allowFilterResult( 12512 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12513 ActivityInfo filterAi = filter.activity.info; 12514 for (int i=dest.size()-1; i>=0; i--) { 12515 ActivityInfo destAi = dest.get(i).activityInfo; 12516 if (destAi.name == filterAi.name 12517 && destAi.packageName == filterAi.packageName) { 12518 return false; 12519 } 12520 } 12521 return true; 12522 } 12523 12524 @Override 12525 protected ActivityIntentInfo[] newArray(int size) { 12526 return new ActivityIntentInfo[size]; 12527 } 12528 12529 @Override 12530 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12531 if (!sUserManager.exists(userId)) return true; 12532 PackageParser.Package p = filter.activity.owner; 12533 if (p != null) { 12534 PackageSetting ps = (PackageSetting)p.mExtras; 12535 if (ps != null) { 12536 // System apps are never considered stopped for purposes of 12537 // filtering, because there may be no way for the user to 12538 // actually re-launch them. 12539 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12540 && ps.getStopped(userId); 12541 } 12542 } 12543 return false; 12544 } 12545 12546 @Override 12547 protected boolean isPackageForFilter(String packageName, 12548 PackageParser.ActivityIntentInfo info) { 12549 return packageName.equals(info.activity.owner.packageName); 12550 } 12551 12552 @Override 12553 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12554 int match, int userId) { 12555 if (!sUserManager.exists(userId)) return null; 12556 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12557 return null; 12558 } 12559 final PackageParser.Activity activity = info.activity; 12560 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12561 if (ps == null) { 12562 return null; 12563 } 12564 final PackageUserState userState = ps.readUserState(userId); 12565 ActivityInfo ai = generateActivityInfo(activity, mFlags, userState, userId); 12566 if (ai == null) { 12567 return null; 12568 } 12569 final boolean matchExplicitlyVisibleOnly = 12570 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12571 final boolean matchVisibleToInstantApp = 12572 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12573 final boolean componentVisible = 12574 matchVisibleToInstantApp 12575 && info.isVisibleToInstantApp() 12576 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12577 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12578 // throw out filters that aren't visible to ephemeral apps 12579 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12580 return null; 12581 } 12582 // throw out instant app filters if we're not explicitly requesting them 12583 if (!matchInstantApp && userState.instantApp) { 12584 return null; 12585 } 12586 // throw out instant app filters if updates are available; will trigger 12587 // instant app resolution 12588 if (userState.instantApp && ps.isUpdateAvailable()) { 12589 return null; 12590 } 12591 final ResolveInfo res = new ResolveInfo(); 12592 res.activityInfo = ai; 12593 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12594 res.filter = info; 12595 } 12596 if (info != null) { 12597 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12598 } 12599 res.priority = info.getPriority(); 12600 res.preferredOrder = activity.owner.mPreferredOrder; 12601 //System.out.println("Result: " + res.activityInfo.className + 12602 // " = " + res.priority); 12603 res.match = match; 12604 res.isDefault = info.hasDefault; 12605 res.labelRes = info.labelRes; 12606 res.nonLocalizedLabel = info.nonLocalizedLabel; 12607 if (userNeedsBadging(userId)) { 12608 res.noResourceId = true; 12609 } else { 12610 res.icon = info.icon; 12611 } 12612 res.iconResourceId = info.icon; 12613 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12614 res.instantAppAvailable = userState.instantApp; 12615 return res; 12616 } 12617 12618 @Override 12619 protected void sortResults(List<ResolveInfo> results) { 12620 Collections.sort(results, mResolvePrioritySorter); 12621 } 12622 12623 @Override 12624 protected void dumpFilter(PrintWriter out, String prefix, 12625 PackageParser.ActivityIntentInfo filter) { 12626 out.print(prefix); out.print( 12627 Integer.toHexString(System.identityHashCode(filter.activity))); 12628 out.print(' '); 12629 filter.activity.printComponentShortName(out); 12630 out.print(" filter "); 12631 out.println(Integer.toHexString(System.identityHashCode(filter))); 12632 } 12633 12634 @Override 12635 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12636 return filter.activity; 12637 } 12638 12639 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12640 PackageParser.Activity activity = (PackageParser.Activity)label; 12641 out.print(prefix); out.print( 12642 Integer.toHexString(System.identityHashCode(activity))); 12643 out.print(' '); 12644 activity.printComponentShortName(out); 12645 if (count > 1) { 12646 out.print(" ("); out.print(count); out.print(" filters)"); 12647 } 12648 out.println(); 12649 } 12650 12651 // Keys are String (activity class name), values are Activity. 12652 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12653 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12654 private int mFlags; 12655 } 12656 12657 private final class ServiceIntentResolver 12658 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12659 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12660 boolean defaultOnly, int userId) { 12661 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12662 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12663 } 12664 12665 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12666 int userId) { 12667 if (!sUserManager.exists(userId)) return null; 12668 mFlags = flags; 12669 return super.queryIntent(intent, resolvedType, 12670 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12671 userId); 12672 } 12673 12674 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12675 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12676 if (!sUserManager.exists(userId)) return null; 12677 if (packageServices == null) { 12678 return null; 12679 } 12680 mFlags = flags; 12681 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12682 final int N = packageServices.size(); 12683 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12684 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12685 12686 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12687 for (int i = 0; i < N; ++i) { 12688 intentFilters = packageServices.get(i).intents; 12689 if (intentFilters != null && intentFilters.size() > 0) { 12690 PackageParser.ServiceIntentInfo[] array = 12691 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12692 intentFilters.toArray(array); 12693 listCut.add(array); 12694 } 12695 } 12696 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12697 } 12698 12699 public final void addService(PackageParser.Service s) { 12700 mServices.put(s.getComponentName(), s); 12701 if (DEBUG_SHOW_INFO) { 12702 Log.v(TAG, " " 12703 + (s.info.nonLocalizedLabel != null 12704 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12705 Log.v(TAG, " Class=" + s.info.name); 12706 } 12707 final int NI = s.intents.size(); 12708 int j; 12709 for (j=0; j<NI; j++) { 12710 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12711 if (DEBUG_SHOW_INFO) { 12712 Log.v(TAG, " IntentFilter:"); 12713 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12714 } 12715 if (!intent.debugCheck()) { 12716 Log.w(TAG, "==> For Service " + s.info.name); 12717 } 12718 addFilter(intent); 12719 } 12720 } 12721 12722 public final void removeService(PackageParser.Service s) { 12723 mServices.remove(s.getComponentName()); 12724 if (DEBUG_SHOW_INFO) { 12725 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12726 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12727 Log.v(TAG, " Class=" + s.info.name); 12728 } 12729 final int NI = s.intents.size(); 12730 int j; 12731 for (j=0; j<NI; j++) { 12732 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12733 if (DEBUG_SHOW_INFO) { 12734 Log.v(TAG, " IntentFilter:"); 12735 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12736 } 12737 removeFilter(intent); 12738 } 12739 } 12740 12741 @Override 12742 protected boolean allowFilterResult( 12743 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12744 ServiceInfo filterSi = filter.service.info; 12745 for (int i=dest.size()-1; i>=0; i--) { 12746 ServiceInfo destAi = dest.get(i).serviceInfo; 12747 if (destAi.name == filterSi.name 12748 && destAi.packageName == filterSi.packageName) { 12749 return false; 12750 } 12751 } 12752 return true; 12753 } 12754 12755 @Override 12756 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12757 return new PackageParser.ServiceIntentInfo[size]; 12758 } 12759 12760 @Override 12761 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12762 if (!sUserManager.exists(userId)) return true; 12763 PackageParser.Package p = filter.service.owner; 12764 if (p != null) { 12765 PackageSetting ps = (PackageSetting)p.mExtras; 12766 if (ps != null) { 12767 // System apps are never considered stopped for purposes of 12768 // filtering, because there may be no way for the user to 12769 // actually re-launch them. 12770 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12771 && ps.getStopped(userId); 12772 } 12773 } 12774 return false; 12775 } 12776 12777 @Override 12778 protected boolean isPackageForFilter(String packageName, 12779 PackageParser.ServiceIntentInfo info) { 12780 return packageName.equals(info.service.owner.packageName); 12781 } 12782 12783 @Override 12784 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12785 int match, int userId) { 12786 if (!sUserManager.exists(userId)) return null; 12787 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12788 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12789 return null; 12790 } 12791 final PackageParser.Service service = info.service; 12792 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12793 if (ps == null) { 12794 return null; 12795 } 12796 final PackageUserState userState = ps.readUserState(userId); 12797 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12798 userState, userId); 12799 if (si == null) { 12800 return null; 12801 } 12802 final boolean matchVisibleToInstantApp = 12803 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12804 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12805 // throw out filters that aren't visible to ephemeral apps 12806 if (matchVisibleToInstantApp 12807 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12808 return null; 12809 } 12810 // throw out ephemeral filters if we're not explicitly requesting them 12811 if (!isInstantApp && userState.instantApp) { 12812 return null; 12813 } 12814 // throw out instant app filters if updates are available; will trigger 12815 // instant app resolution 12816 if (userState.instantApp && ps.isUpdateAvailable()) { 12817 return null; 12818 } 12819 final ResolveInfo res = new ResolveInfo(); 12820 res.serviceInfo = si; 12821 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12822 res.filter = filter; 12823 } 12824 res.priority = info.getPriority(); 12825 res.preferredOrder = service.owner.mPreferredOrder; 12826 res.match = match; 12827 res.isDefault = info.hasDefault; 12828 res.labelRes = info.labelRes; 12829 res.nonLocalizedLabel = info.nonLocalizedLabel; 12830 res.icon = info.icon; 12831 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12832 return res; 12833 } 12834 12835 @Override 12836 protected void sortResults(List<ResolveInfo> results) { 12837 Collections.sort(results, mResolvePrioritySorter); 12838 } 12839 12840 @Override 12841 protected void dumpFilter(PrintWriter out, String prefix, 12842 PackageParser.ServiceIntentInfo filter) { 12843 out.print(prefix); out.print( 12844 Integer.toHexString(System.identityHashCode(filter.service))); 12845 out.print(' '); 12846 filter.service.printComponentShortName(out); 12847 out.print(" filter "); 12848 out.println(Integer.toHexString(System.identityHashCode(filter))); 12849 } 12850 12851 @Override 12852 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12853 return filter.service; 12854 } 12855 12856 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12857 PackageParser.Service service = (PackageParser.Service)label; 12858 out.print(prefix); out.print( 12859 Integer.toHexString(System.identityHashCode(service))); 12860 out.print(' '); 12861 service.printComponentShortName(out); 12862 if (count > 1) { 12863 out.print(" ("); out.print(count); out.print(" filters)"); 12864 } 12865 out.println(); 12866 } 12867 12868// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12869// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12870// final List<ResolveInfo> retList = Lists.newArrayList(); 12871// while (i.hasNext()) { 12872// final ResolveInfo resolveInfo = (ResolveInfo) i; 12873// if (isEnabledLP(resolveInfo.serviceInfo)) { 12874// retList.add(resolveInfo); 12875// } 12876// } 12877// return retList; 12878// } 12879 12880 // Keys are String (activity class name), values are Activity. 12881 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12882 = new ArrayMap<ComponentName, PackageParser.Service>(); 12883 private int mFlags; 12884 } 12885 12886 private final class ProviderIntentResolver 12887 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12888 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12889 boolean defaultOnly, int userId) { 12890 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12891 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12892 } 12893 12894 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12895 int userId) { 12896 if (!sUserManager.exists(userId)) 12897 return null; 12898 mFlags = flags; 12899 return super.queryIntent(intent, resolvedType, 12900 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12901 userId); 12902 } 12903 12904 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12905 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12906 if (!sUserManager.exists(userId)) 12907 return null; 12908 if (packageProviders == null) { 12909 return null; 12910 } 12911 mFlags = flags; 12912 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12913 final int N = packageProviders.size(); 12914 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12915 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12916 12917 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12918 for (int i = 0; i < N; ++i) { 12919 intentFilters = packageProviders.get(i).intents; 12920 if (intentFilters != null && intentFilters.size() > 0) { 12921 PackageParser.ProviderIntentInfo[] array = 12922 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12923 intentFilters.toArray(array); 12924 listCut.add(array); 12925 } 12926 } 12927 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12928 } 12929 12930 public final void addProvider(PackageParser.Provider p) { 12931 if (mProviders.containsKey(p.getComponentName())) { 12932 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12933 return; 12934 } 12935 12936 mProviders.put(p.getComponentName(), p); 12937 if (DEBUG_SHOW_INFO) { 12938 Log.v(TAG, " " 12939 + (p.info.nonLocalizedLabel != null 12940 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12941 Log.v(TAG, " Class=" + p.info.name); 12942 } 12943 final int NI = p.intents.size(); 12944 int j; 12945 for (j = 0; j < NI; j++) { 12946 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12947 if (DEBUG_SHOW_INFO) { 12948 Log.v(TAG, " IntentFilter:"); 12949 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12950 } 12951 if (!intent.debugCheck()) { 12952 Log.w(TAG, "==> For Provider " + p.info.name); 12953 } 12954 addFilter(intent); 12955 } 12956 } 12957 12958 public final void removeProvider(PackageParser.Provider p) { 12959 mProviders.remove(p.getComponentName()); 12960 if (DEBUG_SHOW_INFO) { 12961 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12962 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12963 Log.v(TAG, " Class=" + p.info.name); 12964 } 12965 final int NI = p.intents.size(); 12966 int j; 12967 for (j = 0; j < NI; j++) { 12968 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12969 if (DEBUG_SHOW_INFO) { 12970 Log.v(TAG, " IntentFilter:"); 12971 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12972 } 12973 removeFilter(intent); 12974 } 12975 } 12976 12977 @Override 12978 protected boolean allowFilterResult( 12979 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12980 ProviderInfo filterPi = filter.provider.info; 12981 for (int i = dest.size() - 1; i >= 0; i--) { 12982 ProviderInfo destPi = dest.get(i).providerInfo; 12983 if (destPi.name == filterPi.name 12984 && destPi.packageName == filterPi.packageName) { 12985 return false; 12986 } 12987 } 12988 return true; 12989 } 12990 12991 @Override 12992 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12993 return new PackageParser.ProviderIntentInfo[size]; 12994 } 12995 12996 @Override 12997 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12998 if (!sUserManager.exists(userId)) 12999 return true; 13000 PackageParser.Package p = filter.provider.owner; 13001 if (p != null) { 13002 PackageSetting ps = (PackageSetting) p.mExtras; 13003 if (ps != null) { 13004 // System apps are never considered stopped for purposes of 13005 // filtering, because there may be no way for the user to 13006 // actually re-launch them. 13007 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13008 && ps.getStopped(userId); 13009 } 13010 } 13011 return false; 13012 } 13013 13014 @Override 13015 protected boolean isPackageForFilter(String packageName, 13016 PackageParser.ProviderIntentInfo info) { 13017 return packageName.equals(info.provider.owner.packageName); 13018 } 13019 13020 @Override 13021 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13022 int match, int userId) { 13023 if (!sUserManager.exists(userId)) 13024 return null; 13025 final PackageParser.ProviderIntentInfo info = filter; 13026 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13027 return null; 13028 } 13029 final PackageParser.Provider provider = info.provider; 13030 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13031 if (ps == null) { 13032 return null; 13033 } 13034 final PackageUserState userState = ps.readUserState(userId); 13035 final boolean matchVisibleToInstantApp = 13036 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13037 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13038 // throw out filters that aren't visible to instant applications 13039 if (matchVisibleToInstantApp 13040 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13041 return null; 13042 } 13043 // throw out instant application filters if we're not explicitly requesting them 13044 if (!isInstantApp && userState.instantApp) { 13045 return null; 13046 } 13047 // throw out instant application filters if updates are available; will trigger 13048 // instant application resolution 13049 if (userState.instantApp && ps.isUpdateAvailable()) { 13050 return null; 13051 } 13052 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13053 userState, userId); 13054 if (pi == null) { 13055 return null; 13056 } 13057 final ResolveInfo res = new ResolveInfo(); 13058 res.providerInfo = pi; 13059 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13060 res.filter = filter; 13061 } 13062 res.priority = info.getPriority(); 13063 res.preferredOrder = provider.owner.mPreferredOrder; 13064 res.match = match; 13065 res.isDefault = info.hasDefault; 13066 res.labelRes = info.labelRes; 13067 res.nonLocalizedLabel = info.nonLocalizedLabel; 13068 res.icon = info.icon; 13069 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13070 return res; 13071 } 13072 13073 @Override 13074 protected void sortResults(List<ResolveInfo> results) { 13075 Collections.sort(results, mResolvePrioritySorter); 13076 } 13077 13078 @Override 13079 protected void dumpFilter(PrintWriter out, String prefix, 13080 PackageParser.ProviderIntentInfo filter) { 13081 out.print(prefix); 13082 out.print( 13083 Integer.toHexString(System.identityHashCode(filter.provider))); 13084 out.print(' '); 13085 filter.provider.printComponentShortName(out); 13086 out.print(" filter "); 13087 out.println(Integer.toHexString(System.identityHashCode(filter))); 13088 } 13089 13090 @Override 13091 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13092 return filter.provider; 13093 } 13094 13095 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13096 PackageParser.Provider provider = (PackageParser.Provider)label; 13097 out.print(prefix); out.print( 13098 Integer.toHexString(System.identityHashCode(provider))); 13099 out.print(' '); 13100 provider.printComponentShortName(out); 13101 if (count > 1) { 13102 out.print(" ("); out.print(count); out.print(" filters)"); 13103 } 13104 out.println(); 13105 } 13106 13107 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13108 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13109 private int mFlags; 13110 } 13111 13112 static final class EphemeralIntentResolver 13113 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13114 /** 13115 * The result that has the highest defined order. Ordering applies on a 13116 * per-package basis. Mapping is from package name to Pair of order and 13117 * EphemeralResolveInfo. 13118 * <p> 13119 * NOTE: This is implemented as a field variable for convenience and efficiency. 13120 * By having a field variable, we're able to track filter ordering as soon as 13121 * a non-zero order is defined. Otherwise, multiple loops across the result set 13122 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13123 * this needs to be contained entirely within {@link #filterResults}. 13124 */ 13125 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13126 13127 @Override 13128 protected AuxiliaryResolveInfo[] newArray(int size) { 13129 return new AuxiliaryResolveInfo[size]; 13130 } 13131 13132 @Override 13133 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13134 return true; 13135 } 13136 13137 @Override 13138 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13139 int userId) { 13140 if (!sUserManager.exists(userId)) { 13141 return null; 13142 } 13143 final String packageName = responseObj.resolveInfo.getPackageName(); 13144 final Integer order = responseObj.getOrder(); 13145 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13146 mOrderResult.get(packageName); 13147 // ordering is enabled and this item's order isn't high enough 13148 if (lastOrderResult != null && lastOrderResult.first >= order) { 13149 return null; 13150 } 13151 final InstantAppResolveInfo res = responseObj.resolveInfo; 13152 if (order > 0) { 13153 // non-zero order, enable ordering 13154 mOrderResult.put(packageName, new Pair<>(order, res)); 13155 } 13156 return responseObj; 13157 } 13158 13159 @Override 13160 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13161 // only do work if ordering is enabled [most of the time it won't be] 13162 if (mOrderResult.size() == 0) { 13163 return; 13164 } 13165 int resultSize = results.size(); 13166 for (int i = 0; i < resultSize; i++) { 13167 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13168 final String packageName = info.getPackageName(); 13169 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13170 if (savedInfo == null) { 13171 // package doesn't having ordering 13172 continue; 13173 } 13174 if (savedInfo.second == info) { 13175 // circled back to the highest ordered item; remove from order list 13176 mOrderResult.remove(savedInfo); 13177 if (mOrderResult.size() == 0) { 13178 // no more ordered items 13179 break; 13180 } 13181 continue; 13182 } 13183 // item has a worse order, remove it from the result list 13184 results.remove(i); 13185 resultSize--; 13186 i--; 13187 } 13188 } 13189 } 13190 13191 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13192 new Comparator<ResolveInfo>() { 13193 public int compare(ResolveInfo r1, ResolveInfo r2) { 13194 int v1 = r1.priority; 13195 int v2 = r2.priority; 13196 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13197 if (v1 != v2) { 13198 return (v1 > v2) ? -1 : 1; 13199 } 13200 v1 = r1.preferredOrder; 13201 v2 = r2.preferredOrder; 13202 if (v1 != v2) { 13203 return (v1 > v2) ? -1 : 1; 13204 } 13205 if (r1.isDefault != r2.isDefault) { 13206 return r1.isDefault ? -1 : 1; 13207 } 13208 v1 = r1.match; 13209 v2 = r2.match; 13210 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13211 if (v1 != v2) { 13212 return (v1 > v2) ? -1 : 1; 13213 } 13214 if (r1.system != r2.system) { 13215 return r1.system ? -1 : 1; 13216 } 13217 if (r1.activityInfo != null) { 13218 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13219 } 13220 if (r1.serviceInfo != null) { 13221 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13222 } 13223 if (r1.providerInfo != null) { 13224 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13225 } 13226 return 0; 13227 } 13228 }; 13229 13230 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13231 new Comparator<ProviderInfo>() { 13232 public int compare(ProviderInfo p1, ProviderInfo p2) { 13233 final int v1 = p1.initOrder; 13234 final int v2 = p2.initOrder; 13235 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13236 } 13237 }; 13238 13239 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13240 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13241 final int[] userIds) { 13242 mHandler.post(new Runnable() { 13243 @Override 13244 public void run() { 13245 try { 13246 final IActivityManager am = ActivityManager.getService(); 13247 if (am == null) return; 13248 final int[] resolvedUserIds; 13249 if (userIds == null) { 13250 resolvedUserIds = am.getRunningUserIds(); 13251 } else { 13252 resolvedUserIds = userIds; 13253 } 13254 for (int id : resolvedUserIds) { 13255 final Intent intent = new Intent(action, 13256 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13257 if (extras != null) { 13258 intent.putExtras(extras); 13259 } 13260 if (targetPkg != null) { 13261 intent.setPackage(targetPkg); 13262 } 13263 // Modify the UID when posting to other users 13264 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13265 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13266 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13267 intent.putExtra(Intent.EXTRA_UID, uid); 13268 } 13269 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13270 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13271 if (DEBUG_BROADCASTS) { 13272 RuntimeException here = new RuntimeException("here"); 13273 here.fillInStackTrace(); 13274 Slog.d(TAG, "Sending to user " + id + ": " 13275 + intent.toShortString(false, true, false, false) 13276 + " " + intent.getExtras(), here); 13277 } 13278 am.broadcastIntent(null, intent, null, finishedReceiver, 13279 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13280 null, finishedReceiver != null, false, id); 13281 } 13282 } catch (RemoteException ex) { 13283 } 13284 } 13285 }); 13286 } 13287 13288 /** 13289 * Check if the external storage media is available. This is true if there 13290 * is a mounted external storage medium or if the external storage is 13291 * emulated. 13292 */ 13293 private boolean isExternalMediaAvailable() { 13294 return mMediaMounted || Environment.isExternalStorageEmulated(); 13295 } 13296 13297 @Override 13298 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13299 // writer 13300 synchronized (mPackages) { 13301 if (!isExternalMediaAvailable()) { 13302 // If the external storage is no longer mounted at this point, 13303 // the caller may not have been able to delete all of this 13304 // packages files and can not delete any more. Bail. 13305 return null; 13306 } 13307 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13308 if (lastPackage != null) { 13309 pkgs.remove(lastPackage); 13310 } 13311 if (pkgs.size() > 0) { 13312 return pkgs.get(0); 13313 } 13314 } 13315 return null; 13316 } 13317 13318 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13319 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13320 userId, andCode ? 1 : 0, packageName); 13321 if (mSystemReady) { 13322 msg.sendToTarget(); 13323 } else { 13324 if (mPostSystemReadyMessages == null) { 13325 mPostSystemReadyMessages = new ArrayList<>(); 13326 } 13327 mPostSystemReadyMessages.add(msg); 13328 } 13329 } 13330 13331 void startCleaningPackages() { 13332 // reader 13333 if (!isExternalMediaAvailable()) { 13334 return; 13335 } 13336 synchronized (mPackages) { 13337 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13338 return; 13339 } 13340 } 13341 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13342 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13343 IActivityManager am = ActivityManager.getService(); 13344 if (am != null) { 13345 int dcsUid = -1; 13346 synchronized (mPackages) { 13347 if (!mDefaultContainerWhitelisted) { 13348 mDefaultContainerWhitelisted = true; 13349 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13350 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13351 } 13352 } 13353 try { 13354 if (dcsUid > 0) { 13355 am.backgroundWhitelistUid(dcsUid); 13356 } 13357 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13358 UserHandle.USER_SYSTEM); 13359 } catch (RemoteException e) { 13360 } 13361 } 13362 } 13363 13364 @Override 13365 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13366 int installFlags, String installerPackageName, int userId) { 13367 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13368 13369 final int callingUid = Binder.getCallingUid(); 13370 enforceCrossUserPermission(callingUid, userId, 13371 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13372 13373 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13374 try { 13375 if (observer != null) { 13376 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13377 } 13378 } catch (RemoteException re) { 13379 } 13380 return; 13381 } 13382 13383 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13384 installFlags |= PackageManager.INSTALL_FROM_ADB; 13385 13386 } else { 13387 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13388 // about installerPackageName. 13389 13390 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13391 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13392 } 13393 13394 UserHandle user; 13395 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13396 user = UserHandle.ALL; 13397 } else { 13398 user = new UserHandle(userId); 13399 } 13400 13401 // Only system components can circumvent runtime permissions when installing. 13402 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13403 && mContext.checkCallingOrSelfPermission(Manifest.permission 13404 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13405 throw new SecurityException("You need the " 13406 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13407 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13408 } 13409 13410 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13411 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13412 throw new IllegalArgumentException( 13413 "New installs into ASEC containers no longer supported"); 13414 } 13415 13416 final File originFile = new File(originPath); 13417 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13418 13419 final Message msg = mHandler.obtainMessage(INIT_COPY); 13420 final VerificationInfo verificationInfo = new VerificationInfo( 13421 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13422 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13423 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13424 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13425 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13426 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13427 msg.obj = params; 13428 13429 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13430 System.identityHashCode(msg.obj)); 13431 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13432 System.identityHashCode(msg.obj)); 13433 13434 mHandler.sendMessage(msg); 13435 } 13436 13437 13438 /** 13439 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13440 * it is acting on behalf on an enterprise or the user). 13441 * 13442 * Note that the ordering of the conditionals in this method is important. The checks we perform 13443 * are as follows, in this order: 13444 * 13445 * 1) If the install is being performed by a system app, we can trust the app to have set the 13446 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13447 * what it is. 13448 * 2) If the install is being performed by a device or profile owner app, the install reason 13449 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13450 * set the install reason correctly. If the app targets an older SDK version where install 13451 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13452 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13453 * 3) In all other cases, the install is being performed by a regular app that is neither part 13454 * of the system nor a device or profile owner. We have no reason to believe that this app is 13455 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13456 * set to enterprise policy and if so, change it to unknown instead. 13457 */ 13458 private int fixUpInstallReason(String installerPackageName, int installerUid, 13459 int installReason) { 13460 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13461 == PERMISSION_GRANTED) { 13462 // If the install is being performed by a system app, we trust that app to have set the 13463 // install reason correctly. 13464 return installReason; 13465 } 13466 13467 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13468 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13469 if (dpm != null) { 13470 ComponentName owner = null; 13471 try { 13472 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13473 if (owner == null) { 13474 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13475 } 13476 } catch (RemoteException e) { 13477 } 13478 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13479 // If the install is being performed by a device or profile owner, the install 13480 // reason should be enterprise policy. 13481 return PackageManager.INSTALL_REASON_POLICY; 13482 } 13483 } 13484 13485 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13486 // If the install is being performed by a regular app (i.e. neither system app nor 13487 // device or profile owner), we have no reason to believe that the app is acting on 13488 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13489 // change it to unknown instead. 13490 return PackageManager.INSTALL_REASON_UNKNOWN; 13491 } 13492 13493 // If the install is being performed by a regular app and the install reason was set to any 13494 // value but enterprise policy, leave the install reason unchanged. 13495 return installReason; 13496 } 13497 13498 void installStage(String packageName, File stagedDir, String stagedCid, 13499 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13500 String installerPackageName, int installerUid, UserHandle user, 13501 Certificate[][] certificates) { 13502 if (DEBUG_EPHEMERAL) { 13503 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13504 Slog.d(TAG, "Ephemeral install of " + packageName); 13505 } 13506 } 13507 final VerificationInfo verificationInfo = new VerificationInfo( 13508 sessionParams.originatingUri, sessionParams.referrerUri, 13509 sessionParams.originatingUid, installerUid); 13510 13511 final OriginInfo origin; 13512 if (stagedDir != null) { 13513 origin = OriginInfo.fromStagedFile(stagedDir); 13514 } else { 13515 origin = OriginInfo.fromStagedContainer(stagedCid); 13516 } 13517 13518 final Message msg = mHandler.obtainMessage(INIT_COPY); 13519 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13520 sessionParams.installReason); 13521 final InstallParams params = new InstallParams(origin, null, observer, 13522 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13523 verificationInfo, user, sessionParams.abiOverride, 13524 sessionParams.grantedRuntimePermissions, certificates, installReason); 13525 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13526 msg.obj = params; 13527 13528 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13529 System.identityHashCode(msg.obj)); 13530 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13531 System.identityHashCode(msg.obj)); 13532 13533 mHandler.sendMessage(msg); 13534 } 13535 13536 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13537 int userId) { 13538 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13539 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13540 } 13541 13542 public void sendPackageAddedForNewUsers(String packageName, boolean isSystem, int appId, int... userIds) { 13543 if (ArrayUtils.isEmpty(userIds)) { 13544 return; 13545 } 13546 Bundle extras = new Bundle(1); 13547 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13548 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13549 13550 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13551 packageName, extras, 0, null, null, userIds); 13552 if (isSystem) { 13553 mHandler.post(() -> { 13554 for (int userId : userIds) { 13555 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13556 } 13557 } 13558 ); 13559 } 13560 } 13561 13562 /** 13563 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13564 * automatically without needing an explicit launch. 13565 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13566 */ 13567 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13568 // If user is not running, the app didn't miss any broadcast 13569 if (!mUserManagerInternal.isUserRunning(userId)) { 13570 return; 13571 } 13572 final IActivityManager am = ActivityManager.getService(); 13573 try { 13574 // Deliver LOCKED_BOOT_COMPLETED first 13575 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13576 .setPackage(packageName); 13577 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13578 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13579 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13580 13581 // Deliver BOOT_COMPLETED only if user is unlocked 13582 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13583 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13584 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13585 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13586 } 13587 } catch (RemoteException e) { 13588 throw e.rethrowFromSystemServer(); 13589 } 13590 } 13591 13592 @Override 13593 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13594 int userId) { 13595 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13596 PackageSetting pkgSetting; 13597 final int uid = Binder.getCallingUid(); 13598 enforceCrossUserPermission(uid, userId, 13599 true /* requireFullPermission */, true /* checkShell */, 13600 "setApplicationHiddenSetting for user " + userId); 13601 13602 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13603 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13604 return false; 13605 } 13606 13607 long callingId = Binder.clearCallingIdentity(); 13608 try { 13609 boolean sendAdded = false; 13610 boolean sendRemoved = false; 13611 // writer 13612 synchronized (mPackages) { 13613 pkgSetting = mSettings.mPackages.get(packageName); 13614 if (pkgSetting == null) { 13615 return false; 13616 } 13617 // Do not allow "android" is being disabled 13618 if ("android".equals(packageName)) { 13619 Slog.w(TAG, "Cannot hide package: android"); 13620 return false; 13621 } 13622 // Cannot hide static shared libs as they are considered 13623 // a part of the using app (emulating static linking). Also 13624 // static libs are installed always on internal storage. 13625 PackageParser.Package pkg = mPackages.get(packageName); 13626 if (pkg != null && pkg.staticSharedLibName != null) { 13627 Slog.w(TAG, "Cannot hide package: " + packageName 13628 + " providing static shared library: " 13629 + pkg.staticSharedLibName); 13630 return false; 13631 } 13632 // Only allow protected packages to hide themselves. 13633 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13634 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13635 Slog.w(TAG, "Not hiding protected package: " + packageName); 13636 return false; 13637 } 13638 13639 if (pkgSetting.getHidden(userId) != hidden) { 13640 pkgSetting.setHidden(hidden, userId); 13641 mSettings.writePackageRestrictionsLPr(userId); 13642 if (hidden) { 13643 sendRemoved = true; 13644 } else { 13645 sendAdded = true; 13646 } 13647 } 13648 } 13649 if (sendAdded) { 13650 sendPackageAddedForUser(packageName, pkgSetting, userId); 13651 return true; 13652 } 13653 if (sendRemoved) { 13654 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13655 "hiding pkg"); 13656 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13657 return true; 13658 } 13659 } finally { 13660 Binder.restoreCallingIdentity(callingId); 13661 } 13662 return false; 13663 } 13664 13665 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13666 int userId) { 13667 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13668 info.removedPackage = packageName; 13669 info.installerPackageName = pkgSetting.installerPackageName; 13670 info.removedUsers = new int[] {userId}; 13671 info.broadcastUsers = new int[] {userId}; 13672 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13673 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13674 } 13675 13676 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13677 if (pkgList.length > 0) { 13678 Bundle extras = new Bundle(1); 13679 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13680 13681 sendPackageBroadcast( 13682 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13683 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13684 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13685 new int[] {userId}); 13686 } 13687 } 13688 13689 /** 13690 * Returns true if application is not found or there was an error. Otherwise it returns 13691 * the hidden state of the package for the given user. 13692 */ 13693 @Override 13694 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13695 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13696 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13697 true /* requireFullPermission */, false /* checkShell */, 13698 "getApplicationHidden for user " + userId); 13699 PackageSetting pkgSetting; 13700 long callingId = Binder.clearCallingIdentity(); 13701 try { 13702 // writer 13703 synchronized (mPackages) { 13704 pkgSetting = mSettings.mPackages.get(packageName); 13705 if (pkgSetting == null) { 13706 return true; 13707 } 13708 return pkgSetting.getHidden(userId); 13709 } 13710 } finally { 13711 Binder.restoreCallingIdentity(callingId); 13712 } 13713 } 13714 13715 /** 13716 * @hide 13717 */ 13718 @Override 13719 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13720 int installReason) { 13721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13722 null); 13723 PackageSetting pkgSetting; 13724 final int uid = Binder.getCallingUid(); 13725 enforceCrossUserPermission(uid, userId, 13726 true /* requireFullPermission */, true /* checkShell */, 13727 "installExistingPackage for user " + userId); 13728 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13729 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13730 } 13731 13732 long callingId = Binder.clearCallingIdentity(); 13733 try { 13734 boolean installed = false; 13735 final boolean instantApp = 13736 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13737 final boolean fullApp = 13738 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13739 13740 // writer 13741 synchronized (mPackages) { 13742 pkgSetting = mSettings.mPackages.get(packageName); 13743 if (pkgSetting == null) { 13744 return PackageManager.INSTALL_FAILED_INVALID_URI; 13745 } 13746 if (!pkgSetting.getInstalled(userId)) { 13747 pkgSetting.setInstalled(true, userId); 13748 pkgSetting.setHidden(false, userId); 13749 pkgSetting.setInstallReason(installReason, userId); 13750 mSettings.writePackageRestrictionsLPr(userId); 13751 mSettings.writeKernelMappingLPr(pkgSetting); 13752 installed = true; 13753 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13754 // upgrade app from instant to full; we don't allow app downgrade 13755 installed = true; 13756 } 13757 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13758 } 13759 13760 if (installed) { 13761 if (pkgSetting.pkg != null) { 13762 synchronized (mInstallLock) { 13763 // We don't need to freeze for a brand new install 13764 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13765 } 13766 } 13767 sendPackageAddedForUser(packageName, pkgSetting, userId); 13768 synchronized (mPackages) { 13769 updateSequenceNumberLP(packageName, new int[]{ userId }); 13770 } 13771 } 13772 } finally { 13773 Binder.restoreCallingIdentity(callingId); 13774 } 13775 13776 return PackageManager.INSTALL_SUCCEEDED; 13777 } 13778 13779 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13780 boolean instantApp, boolean fullApp) { 13781 // no state specified; do nothing 13782 if (!instantApp && !fullApp) { 13783 return; 13784 } 13785 if (userId != UserHandle.USER_ALL) { 13786 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13787 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13788 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13789 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13790 } 13791 } else { 13792 for (int currentUserId : sUserManager.getUserIds()) { 13793 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13794 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13795 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13796 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13797 } 13798 } 13799 } 13800 } 13801 13802 boolean isUserRestricted(int userId, String restrictionKey) { 13803 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13804 if (restrictions.getBoolean(restrictionKey, false)) { 13805 Log.w(TAG, "User is restricted: " + restrictionKey); 13806 return true; 13807 } 13808 return false; 13809 } 13810 13811 @Override 13812 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13813 int userId) { 13814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13815 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13816 true /* requireFullPermission */, true /* checkShell */, 13817 "setPackagesSuspended for user " + userId); 13818 13819 if (ArrayUtils.isEmpty(packageNames)) { 13820 return packageNames; 13821 } 13822 13823 // List of package names for whom the suspended state has changed. 13824 List<String> changedPackages = new ArrayList<>(packageNames.length); 13825 // List of package names for whom the suspended state is not set as requested in this 13826 // method. 13827 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13828 long callingId = Binder.clearCallingIdentity(); 13829 try { 13830 for (int i = 0; i < packageNames.length; i++) { 13831 String packageName = packageNames[i]; 13832 boolean changed = false; 13833 final int appId; 13834 synchronized (mPackages) { 13835 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13836 if (pkgSetting == null) { 13837 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13838 + "\". Skipping suspending/un-suspending."); 13839 unactionedPackages.add(packageName); 13840 continue; 13841 } 13842 appId = pkgSetting.appId; 13843 if (pkgSetting.getSuspended(userId) != suspended) { 13844 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13845 unactionedPackages.add(packageName); 13846 continue; 13847 } 13848 pkgSetting.setSuspended(suspended, userId); 13849 mSettings.writePackageRestrictionsLPr(userId); 13850 changed = true; 13851 changedPackages.add(packageName); 13852 } 13853 } 13854 13855 if (changed && suspended) { 13856 killApplication(packageName, UserHandle.getUid(userId, appId), 13857 "suspending package"); 13858 } 13859 } 13860 } finally { 13861 Binder.restoreCallingIdentity(callingId); 13862 } 13863 13864 if (!changedPackages.isEmpty()) { 13865 sendPackagesSuspendedForUser(changedPackages.toArray( 13866 new String[changedPackages.size()]), userId, suspended); 13867 } 13868 13869 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13870 } 13871 13872 @Override 13873 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13874 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13875 true /* requireFullPermission */, false /* checkShell */, 13876 "isPackageSuspendedForUser for user " + userId); 13877 synchronized (mPackages) { 13878 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13879 if (pkgSetting == null) { 13880 throw new IllegalArgumentException("Unknown target package: " + packageName); 13881 } 13882 return pkgSetting.getSuspended(userId); 13883 } 13884 } 13885 13886 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13887 if (isPackageDeviceAdmin(packageName, userId)) { 13888 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13889 + "\": has an active device admin"); 13890 return false; 13891 } 13892 13893 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13894 if (packageName.equals(activeLauncherPackageName)) { 13895 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13896 + "\": contains the active launcher"); 13897 return false; 13898 } 13899 13900 if (packageName.equals(mRequiredInstallerPackage)) { 13901 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13902 + "\": required for package installation"); 13903 return false; 13904 } 13905 13906 if (packageName.equals(mRequiredUninstallerPackage)) { 13907 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13908 + "\": required for package uninstallation"); 13909 return false; 13910 } 13911 13912 if (packageName.equals(mRequiredVerifierPackage)) { 13913 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13914 + "\": required for package verification"); 13915 return false; 13916 } 13917 13918 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13919 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13920 + "\": is the default dialer"); 13921 return false; 13922 } 13923 13924 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13925 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13926 + "\": protected package"); 13927 return false; 13928 } 13929 13930 // Cannot suspend static shared libs as they are considered 13931 // a part of the using app (emulating static linking). Also 13932 // static libs are installed always on internal storage. 13933 PackageParser.Package pkg = mPackages.get(packageName); 13934 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13935 Slog.w(TAG, "Cannot suspend package: " + packageName 13936 + " providing static shared library: " 13937 + pkg.staticSharedLibName); 13938 return false; 13939 } 13940 13941 return true; 13942 } 13943 13944 private String getActiveLauncherPackageName(int userId) { 13945 Intent intent = new Intent(Intent.ACTION_MAIN); 13946 intent.addCategory(Intent.CATEGORY_HOME); 13947 ResolveInfo resolveInfo = resolveIntent( 13948 intent, 13949 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13950 PackageManager.MATCH_DEFAULT_ONLY, 13951 userId); 13952 13953 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13954 } 13955 13956 private String getDefaultDialerPackageName(int userId) { 13957 synchronized (mPackages) { 13958 return mSettings.getDefaultDialerPackageNameLPw(userId); 13959 } 13960 } 13961 13962 @Override 13963 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13964 mContext.enforceCallingOrSelfPermission( 13965 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13966 "Only package verification agents can verify applications"); 13967 13968 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13969 final PackageVerificationResponse response = new PackageVerificationResponse( 13970 verificationCode, Binder.getCallingUid()); 13971 msg.arg1 = id; 13972 msg.obj = response; 13973 mHandler.sendMessage(msg); 13974 } 13975 13976 @Override 13977 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13978 long millisecondsToDelay) { 13979 mContext.enforceCallingOrSelfPermission( 13980 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13981 "Only package verification agents can extend verification timeouts"); 13982 13983 final PackageVerificationState state = mPendingVerification.get(id); 13984 final PackageVerificationResponse response = new PackageVerificationResponse( 13985 verificationCodeAtTimeout, Binder.getCallingUid()); 13986 13987 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13988 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13989 } 13990 if (millisecondsToDelay < 0) { 13991 millisecondsToDelay = 0; 13992 } 13993 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13994 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13995 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13996 } 13997 13998 if ((state != null) && !state.timeoutExtended()) { 13999 state.extendTimeout(); 14000 14001 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14002 msg.arg1 = id; 14003 msg.obj = response; 14004 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14005 } 14006 } 14007 14008 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14009 int verificationCode, UserHandle user) { 14010 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14011 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14012 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14013 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14014 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14015 14016 mContext.sendBroadcastAsUser(intent, user, 14017 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14018 } 14019 14020 private ComponentName matchComponentForVerifier(String packageName, 14021 List<ResolveInfo> receivers) { 14022 ActivityInfo targetReceiver = null; 14023 14024 final int NR = receivers.size(); 14025 for (int i = 0; i < NR; i++) { 14026 final ResolveInfo info = receivers.get(i); 14027 if (info.activityInfo == null) { 14028 continue; 14029 } 14030 14031 if (packageName.equals(info.activityInfo.packageName)) { 14032 targetReceiver = info.activityInfo; 14033 break; 14034 } 14035 } 14036 14037 if (targetReceiver == null) { 14038 return null; 14039 } 14040 14041 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14042 } 14043 14044 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14045 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14046 if (pkgInfo.verifiers.length == 0) { 14047 return null; 14048 } 14049 14050 final int N = pkgInfo.verifiers.length; 14051 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14052 for (int i = 0; i < N; i++) { 14053 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14054 14055 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14056 receivers); 14057 if (comp == null) { 14058 continue; 14059 } 14060 14061 final int verifierUid = getUidForVerifier(verifierInfo); 14062 if (verifierUid == -1) { 14063 continue; 14064 } 14065 14066 if (DEBUG_VERIFY) { 14067 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14068 + " with the correct signature"); 14069 } 14070 sufficientVerifiers.add(comp); 14071 verificationState.addSufficientVerifier(verifierUid); 14072 } 14073 14074 return sufficientVerifiers; 14075 } 14076 14077 private int getUidForVerifier(VerifierInfo verifierInfo) { 14078 synchronized (mPackages) { 14079 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14080 if (pkg == null) { 14081 return -1; 14082 } else if (pkg.mSignatures.length != 1) { 14083 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14084 + " has more than one signature; ignoring"); 14085 return -1; 14086 } 14087 14088 /* 14089 * If the public key of the package's signature does not match 14090 * our expected public key, then this is a different package and 14091 * we should skip. 14092 */ 14093 14094 final byte[] expectedPublicKey; 14095 try { 14096 final Signature verifierSig = pkg.mSignatures[0]; 14097 final PublicKey publicKey = verifierSig.getPublicKey(); 14098 expectedPublicKey = publicKey.getEncoded(); 14099 } catch (CertificateException e) { 14100 return -1; 14101 } 14102 14103 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14104 14105 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14106 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14107 + " does not have the expected public key; ignoring"); 14108 return -1; 14109 } 14110 14111 return pkg.applicationInfo.uid; 14112 } 14113 } 14114 14115 @Override 14116 public void finishPackageInstall(int token, boolean didLaunch) { 14117 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14118 14119 if (DEBUG_INSTALL) { 14120 Slog.v(TAG, "BM finishing package install for " + token); 14121 } 14122 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14123 14124 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14125 mHandler.sendMessage(msg); 14126 } 14127 14128 /** 14129 * Get the verification agent timeout. Used for both the APK verifier and the 14130 * intent filter verifier. 14131 * 14132 * @return verification timeout in milliseconds 14133 */ 14134 private long getVerificationTimeout() { 14135 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14136 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14137 DEFAULT_VERIFICATION_TIMEOUT); 14138 } 14139 14140 /** 14141 * Get the default verification agent response code. 14142 * 14143 * @return default verification response code 14144 */ 14145 private int getDefaultVerificationResponse() { 14146 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14147 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14148 DEFAULT_VERIFICATION_RESPONSE); 14149 } 14150 14151 /** 14152 * Check whether or not package verification has been enabled. 14153 * 14154 * @return true if verification should be performed 14155 */ 14156 private boolean isVerificationEnabled(int userId, int installFlags) { 14157 if (!DEFAULT_VERIFY_ENABLE) { 14158 return false; 14159 } 14160 14161 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14162 14163 // Check if installing from ADB 14164 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14165 // Do not run verification in a test harness environment 14166 if (ActivityManager.isRunningInTestHarness()) { 14167 return false; 14168 } 14169 if (ensureVerifyAppsEnabled) { 14170 return true; 14171 } 14172 // Check if the developer does not want package verification for ADB installs 14173 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14174 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14175 return false; 14176 } 14177 } 14178 14179 if (ensureVerifyAppsEnabled) { 14180 return true; 14181 } 14182 14183 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14184 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14185 } 14186 14187 @Override 14188 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14189 throws RemoteException { 14190 mContext.enforceCallingOrSelfPermission( 14191 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14192 "Only intentfilter verification agents can verify applications"); 14193 14194 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14195 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14196 Binder.getCallingUid(), verificationCode, failedDomains); 14197 msg.arg1 = id; 14198 msg.obj = response; 14199 mHandler.sendMessage(msg); 14200 } 14201 14202 @Override 14203 public int getIntentVerificationStatus(String packageName, int userId) { 14204 synchronized (mPackages) { 14205 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14206 } 14207 } 14208 14209 @Override 14210 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14211 mContext.enforceCallingOrSelfPermission( 14212 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14213 14214 boolean result = false; 14215 synchronized (mPackages) { 14216 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14217 } 14218 if (result) { 14219 scheduleWritePackageRestrictionsLocked(userId); 14220 } 14221 return result; 14222 } 14223 14224 @Override 14225 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14226 String packageName) { 14227 synchronized (mPackages) { 14228 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14229 } 14230 } 14231 14232 @Override 14233 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14234 if (TextUtils.isEmpty(packageName)) { 14235 return ParceledListSlice.emptyList(); 14236 } 14237 synchronized (mPackages) { 14238 PackageParser.Package pkg = mPackages.get(packageName); 14239 if (pkg == null || pkg.activities == null) { 14240 return ParceledListSlice.emptyList(); 14241 } 14242 final int count = pkg.activities.size(); 14243 ArrayList<IntentFilter> result = new ArrayList<>(); 14244 for (int n=0; n<count; n++) { 14245 PackageParser.Activity activity = pkg.activities.get(n); 14246 if (activity.intents != null && activity.intents.size() > 0) { 14247 result.addAll(activity.intents); 14248 } 14249 } 14250 return new ParceledListSlice<>(result); 14251 } 14252 } 14253 14254 @Override 14255 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14256 mContext.enforceCallingOrSelfPermission( 14257 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14258 14259 synchronized (mPackages) { 14260 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14261 if (packageName != null) { 14262 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 14263 packageName, userId); 14264 } 14265 return result; 14266 } 14267 } 14268 14269 @Override 14270 public String getDefaultBrowserPackageName(int userId) { 14271 synchronized (mPackages) { 14272 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14273 } 14274 } 14275 14276 /** 14277 * Get the "allow unknown sources" setting. 14278 * 14279 * @return the current "allow unknown sources" setting 14280 */ 14281 private int getUnknownSourcesSettings() { 14282 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14283 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14284 -1); 14285 } 14286 14287 @Override 14288 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14289 final int uid = Binder.getCallingUid(); 14290 // writer 14291 synchronized (mPackages) { 14292 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14293 if (targetPackageSetting == null) { 14294 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14295 } 14296 14297 PackageSetting installerPackageSetting; 14298 if (installerPackageName != null) { 14299 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14300 if (installerPackageSetting == null) { 14301 throw new IllegalArgumentException("Unknown installer package: " 14302 + installerPackageName); 14303 } 14304 } else { 14305 installerPackageSetting = null; 14306 } 14307 14308 Signature[] callerSignature; 14309 Object obj = mSettings.getUserIdLPr(uid); 14310 if (obj != null) { 14311 if (obj instanceof SharedUserSetting) { 14312 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14313 } else if (obj instanceof PackageSetting) { 14314 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14315 } else { 14316 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14317 } 14318 } else { 14319 throw new SecurityException("Unknown calling UID: " + uid); 14320 } 14321 14322 // Verify: can't set installerPackageName to a package that is 14323 // not signed with the same cert as the caller. 14324 if (installerPackageSetting != null) { 14325 if (compareSignatures(callerSignature, 14326 installerPackageSetting.signatures.mSignatures) 14327 != PackageManager.SIGNATURE_MATCH) { 14328 throw new SecurityException( 14329 "Caller does not have same cert as new installer package " 14330 + installerPackageName); 14331 } 14332 } 14333 14334 // Verify: if target already has an installer package, it must 14335 // be signed with the same cert as the caller. 14336 if (targetPackageSetting.installerPackageName != null) { 14337 PackageSetting setting = mSettings.mPackages.get( 14338 targetPackageSetting.installerPackageName); 14339 // If the currently set package isn't valid, then it's always 14340 // okay to change it. 14341 if (setting != null) { 14342 if (compareSignatures(callerSignature, 14343 setting.signatures.mSignatures) 14344 != PackageManager.SIGNATURE_MATCH) { 14345 throw new SecurityException( 14346 "Caller does not have same cert as old installer package " 14347 + targetPackageSetting.installerPackageName); 14348 } 14349 } 14350 } 14351 14352 // Okay! 14353 targetPackageSetting.installerPackageName = installerPackageName; 14354 if (installerPackageName != null) { 14355 mSettings.mInstallerPackages.add(installerPackageName); 14356 } 14357 scheduleWriteSettingsLocked(); 14358 } 14359 } 14360 14361 @Override 14362 public void setApplicationCategoryHint(String packageName, int categoryHint, 14363 String callerPackageName) { 14364 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14365 callerPackageName); 14366 synchronized (mPackages) { 14367 PackageSetting ps = mSettings.mPackages.get(packageName); 14368 if (ps == null) { 14369 throw new IllegalArgumentException("Unknown target package " + packageName); 14370 } 14371 14372 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14373 throw new IllegalArgumentException("Calling package " + callerPackageName 14374 + " is not installer for " + packageName); 14375 } 14376 14377 if (ps.categoryHint != categoryHint) { 14378 ps.categoryHint = categoryHint; 14379 scheduleWriteSettingsLocked(); 14380 } 14381 } 14382 } 14383 14384 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14385 // Queue up an async operation since the package installation may take a little while. 14386 mHandler.post(new Runnable() { 14387 public void run() { 14388 mHandler.removeCallbacks(this); 14389 // Result object to be returned 14390 PackageInstalledInfo res = new PackageInstalledInfo(); 14391 res.setReturnCode(currentStatus); 14392 res.uid = -1; 14393 res.pkg = null; 14394 res.removedInfo = null; 14395 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14396 args.doPreInstall(res.returnCode); 14397 synchronized (mInstallLock) { 14398 installPackageTracedLI(args, res); 14399 } 14400 args.doPostInstall(res.returnCode, res.uid); 14401 } 14402 14403 // A restore should be performed at this point if (a) the install 14404 // succeeded, (b) the operation is not an update, and (c) the new 14405 // package has not opted out of backup participation. 14406 final boolean update = res.removedInfo != null 14407 && res.removedInfo.removedPackage != null; 14408 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14409 boolean doRestore = !update 14410 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14411 14412 // Set up the post-install work request bookkeeping. This will be used 14413 // and cleaned up by the post-install event handling regardless of whether 14414 // there's a restore pass performed. Token values are >= 1. 14415 int token; 14416 if (mNextInstallToken < 0) mNextInstallToken = 1; 14417 token = mNextInstallToken++; 14418 14419 PostInstallData data = new PostInstallData(args, res); 14420 mRunningInstalls.put(token, data); 14421 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14422 14423 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14424 // Pass responsibility to the Backup Manager. It will perform a 14425 // restore if appropriate, then pass responsibility back to the 14426 // Package Manager to run the post-install observer callbacks 14427 // and broadcasts. 14428 IBackupManager bm = IBackupManager.Stub.asInterface( 14429 ServiceManager.getService(Context.BACKUP_SERVICE)); 14430 if (bm != null) { 14431 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14432 + " to BM for possible restore"); 14433 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14434 try { 14435 // TODO: http://b/22388012 14436 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14437 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14438 } else { 14439 doRestore = false; 14440 } 14441 } catch (RemoteException e) { 14442 // can't happen; the backup manager is local 14443 } catch (Exception e) { 14444 Slog.e(TAG, "Exception trying to enqueue restore", e); 14445 doRestore = false; 14446 } 14447 } else { 14448 Slog.e(TAG, "Backup Manager not found!"); 14449 doRestore = false; 14450 } 14451 } 14452 14453 if (!doRestore) { 14454 // No restore possible, or the Backup Manager was mysteriously not 14455 // available -- just fire the post-install work request directly. 14456 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14457 14458 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14459 14460 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14461 mHandler.sendMessage(msg); 14462 } 14463 } 14464 }); 14465 } 14466 14467 /** 14468 * Callback from PackageSettings whenever an app is first transitioned out of the 14469 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14470 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14471 * here whether the app is the target of an ongoing install, and only send the 14472 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14473 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14474 * handling. 14475 */ 14476 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14477 // Serialize this with the rest of the install-process message chain. In the 14478 // restore-at-install case, this Runnable will necessarily run before the 14479 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14480 // are coherent. In the non-restore case, the app has already completed install 14481 // and been launched through some other means, so it is not in a problematic 14482 // state for observers to see the FIRST_LAUNCH signal. 14483 mHandler.post(new Runnable() { 14484 @Override 14485 public void run() { 14486 for (int i = 0; i < mRunningInstalls.size(); i++) { 14487 final PostInstallData data = mRunningInstalls.valueAt(i); 14488 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14489 continue; 14490 } 14491 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14492 // right package; but is it for the right user? 14493 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14494 if (userId == data.res.newUsers[uIndex]) { 14495 if (DEBUG_BACKUP) { 14496 Slog.i(TAG, "Package " + pkgName 14497 + " being restored so deferring FIRST_LAUNCH"); 14498 } 14499 return; 14500 } 14501 } 14502 } 14503 } 14504 // didn't find it, so not being restored 14505 if (DEBUG_BACKUP) { 14506 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14507 } 14508 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14509 } 14510 }); 14511 } 14512 14513 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14514 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14515 installerPkg, null, userIds); 14516 } 14517 14518 private abstract class HandlerParams { 14519 private static final int MAX_RETRIES = 4; 14520 14521 /** 14522 * Number of times startCopy() has been attempted and had a non-fatal 14523 * error. 14524 */ 14525 private int mRetries = 0; 14526 14527 /** User handle for the user requesting the information or installation. */ 14528 private final UserHandle mUser; 14529 String traceMethod; 14530 int traceCookie; 14531 14532 HandlerParams(UserHandle user) { 14533 mUser = user; 14534 } 14535 14536 UserHandle getUser() { 14537 return mUser; 14538 } 14539 14540 HandlerParams setTraceMethod(String traceMethod) { 14541 this.traceMethod = traceMethod; 14542 return this; 14543 } 14544 14545 HandlerParams setTraceCookie(int traceCookie) { 14546 this.traceCookie = traceCookie; 14547 return this; 14548 } 14549 14550 final boolean startCopy() { 14551 boolean res; 14552 try { 14553 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14554 14555 if (++mRetries > MAX_RETRIES) { 14556 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14557 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14558 handleServiceError(); 14559 return false; 14560 } else { 14561 handleStartCopy(); 14562 res = true; 14563 } 14564 } catch (RemoteException e) { 14565 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14566 mHandler.sendEmptyMessage(MCS_RECONNECT); 14567 res = false; 14568 } 14569 handleReturnCode(); 14570 return res; 14571 } 14572 14573 final void serviceError() { 14574 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14575 handleServiceError(); 14576 handleReturnCode(); 14577 } 14578 14579 abstract void handleStartCopy() throws RemoteException; 14580 abstract void handleServiceError(); 14581 abstract void handleReturnCode(); 14582 } 14583 14584 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14585 for (File path : paths) { 14586 try { 14587 mcs.clearDirectory(path.getAbsolutePath()); 14588 } catch (RemoteException e) { 14589 } 14590 } 14591 } 14592 14593 static class OriginInfo { 14594 /** 14595 * Location where install is coming from, before it has been 14596 * copied/renamed into place. This could be a single monolithic APK 14597 * file, or a cluster directory. This location may be untrusted. 14598 */ 14599 final File file; 14600 final String cid; 14601 14602 /** 14603 * Flag indicating that {@link #file} or {@link #cid} has already been 14604 * staged, meaning downstream users don't need to defensively copy the 14605 * contents. 14606 */ 14607 final boolean staged; 14608 14609 /** 14610 * Flag indicating that {@link #file} or {@link #cid} is an already 14611 * installed app that is being moved. 14612 */ 14613 final boolean existing; 14614 14615 final String resolvedPath; 14616 final File resolvedFile; 14617 14618 static OriginInfo fromNothing() { 14619 return new OriginInfo(null, null, false, false); 14620 } 14621 14622 static OriginInfo fromUntrustedFile(File file) { 14623 return new OriginInfo(file, null, false, false); 14624 } 14625 14626 static OriginInfo fromExistingFile(File file) { 14627 return new OriginInfo(file, null, false, true); 14628 } 14629 14630 static OriginInfo fromStagedFile(File file) { 14631 return new OriginInfo(file, null, true, false); 14632 } 14633 14634 static OriginInfo fromStagedContainer(String cid) { 14635 return new OriginInfo(null, cid, true, false); 14636 } 14637 14638 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14639 this.file = file; 14640 this.cid = cid; 14641 this.staged = staged; 14642 this.existing = existing; 14643 14644 if (cid != null) { 14645 resolvedPath = PackageHelper.getSdDir(cid); 14646 resolvedFile = new File(resolvedPath); 14647 } else if (file != null) { 14648 resolvedPath = file.getAbsolutePath(); 14649 resolvedFile = file; 14650 } else { 14651 resolvedPath = null; 14652 resolvedFile = null; 14653 } 14654 } 14655 } 14656 14657 static class MoveInfo { 14658 final int moveId; 14659 final String fromUuid; 14660 final String toUuid; 14661 final String packageName; 14662 final String dataAppName; 14663 final int appId; 14664 final String seinfo; 14665 final int targetSdkVersion; 14666 14667 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14668 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14669 this.moveId = moveId; 14670 this.fromUuid = fromUuid; 14671 this.toUuid = toUuid; 14672 this.packageName = packageName; 14673 this.dataAppName = dataAppName; 14674 this.appId = appId; 14675 this.seinfo = seinfo; 14676 this.targetSdkVersion = targetSdkVersion; 14677 } 14678 } 14679 14680 static class VerificationInfo { 14681 /** A constant used to indicate that a uid value is not present. */ 14682 public static final int NO_UID = -1; 14683 14684 /** URI referencing where the package was downloaded from. */ 14685 final Uri originatingUri; 14686 14687 /** HTTP referrer URI associated with the originatingURI. */ 14688 final Uri referrer; 14689 14690 /** UID of the application that the install request originated from. */ 14691 final int originatingUid; 14692 14693 /** UID of application requesting the install */ 14694 final int installerUid; 14695 14696 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14697 this.originatingUri = originatingUri; 14698 this.referrer = referrer; 14699 this.originatingUid = originatingUid; 14700 this.installerUid = installerUid; 14701 } 14702 } 14703 14704 class InstallParams extends HandlerParams { 14705 final OriginInfo origin; 14706 final MoveInfo move; 14707 final IPackageInstallObserver2 observer; 14708 int installFlags; 14709 final String installerPackageName; 14710 final String volumeUuid; 14711 private InstallArgs mArgs; 14712 private int mRet; 14713 final String packageAbiOverride; 14714 final String[] grantedRuntimePermissions; 14715 final VerificationInfo verificationInfo; 14716 final Certificate[][] certificates; 14717 final int installReason; 14718 14719 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14720 int installFlags, String installerPackageName, String volumeUuid, 14721 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14722 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14723 super(user); 14724 this.origin = origin; 14725 this.move = move; 14726 this.observer = observer; 14727 this.installFlags = installFlags; 14728 this.installerPackageName = installerPackageName; 14729 this.volumeUuid = volumeUuid; 14730 this.verificationInfo = verificationInfo; 14731 this.packageAbiOverride = packageAbiOverride; 14732 this.grantedRuntimePermissions = grantedPermissions; 14733 this.certificates = certificates; 14734 this.installReason = installReason; 14735 } 14736 14737 @Override 14738 public String toString() { 14739 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14740 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14741 } 14742 14743 private int installLocationPolicy(PackageInfoLite pkgLite) { 14744 String packageName = pkgLite.packageName; 14745 int installLocation = pkgLite.installLocation; 14746 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14747 // reader 14748 synchronized (mPackages) { 14749 // Currently installed package which the new package is attempting to replace or 14750 // null if no such package is installed. 14751 PackageParser.Package installedPkg = mPackages.get(packageName); 14752 // Package which currently owns the data which the new package will own if installed. 14753 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14754 // will be null whereas dataOwnerPkg will contain information about the package 14755 // which was uninstalled while keeping its data. 14756 PackageParser.Package dataOwnerPkg = installedPkg; 14757 if (dataOwnerPkg == null) { 14758 PackageSetting ps = mSettings.mPackages.get(packageName); 14759 if (ps != null) { 14760 dataOwnerPkg = ps.pkg; 14761 } 14762 } 14763 14764 if (dataOwnerPkg != null) { 14765 // If installed, the package will get access to data left on the device by its 14766 // predecessor. As a security measure, this is permited only if this is not a 14767 // version downgrade or if the predecessor package is marked as debuggable and 14768 // a downgrade is explicitly requested. 14769 // 14770 // On debuggable platform builds, downgrades are permitted even for 14771 // non-debuggable packages to make testing easier. Debuggable platform builds do 14772 // not offer security guarantees and thus it's OK to disable some security 14773 // mechanisms to make debugging/testing easier on those builds. However, even on 14774 // debuggable builds downgrades of packages are permitted only if requested via 14775 // installFlags. This is because we aim to keep the behavior of debuggable 14776 // platform builds as close as possible to the behavior of non-debuggable 14777 // platform builds. 14778 final boolean downgradeRequested = 14779 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14780 final boolean packageDebuggable = 14781 (dataOwnerPkg.applicationInfo.flags 14782 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14783 final boolean downgradePermitted = 14784 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14785 if (!downgradePermitted) { 14786 try { 14787 checkDowngrade(dataOwnerPkg, pkgLite); 14788 } catch (PackageManagerException e) { 14789 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14790 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14791 } 14792 } 14793 } 14794 14795 if (installedPkg != null) { 14796 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14797 // Check for updated system application. 14798 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14799 if (onSd) { 14800 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14801 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14802 } 14803 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14804 } else { 14805 if (onSd) { 14806 // Install flag overrides everything. 14807 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14808 } 14809 // If current upgrade specifies particular preference 14810 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14811 // Application explicitly specified internal. 14812 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14813 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14814 // App explictly prefers external. Let policy decide 14815 } else { 14816 // Prefer previous location 14817 if (isExternal(installedPkg)) { 14818 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14819 } 14820 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14821 } 14822 } 14823 } else { 14824 // Invalid install. Return error code 14825 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14826 } 14827 } 14828 } 14829 // All the special cases have been taken care of. 14830 // Return result based on recommended install location. 14831 if (onSd) { 14832 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14833 } 14834 return pkgLite.recommendedInstallLocation; 14835 } 14836 14837 /* 14838 * Invoke remote method to get package information and install 14839 * location values. Override install location based on default 14840 * policy if needed and then create install arguments based 14841 * on the install location. 14842 */ 14843 public void handleStartCopy() throws RemoteException { 14844 int ret = PackageManager.INSTALL_SUCCEEDED; 14845 14846 // If we're already staged, we've firmly committed to an install location 14847 if (origin.staged) { 14848 if (origin.file != null) { 14849 installFlags |= PackageManager.INSTALL_INTERNAL; 14850 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14851 } else if (origin.cid != null) { 14852 installFlags |= PackageManager.INSTALL_EXTERNAL; 14853 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14854 } else { 14855 throw new IllegalStateException("Invalid stage location"); 14856 } 14857 } 14858 14859 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14860 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14861 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14862 PackageInfoLite pkgLite = null; 14863 14864 if (onInt && onSd) { 14865 // Check if both bits are set. 14866 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14867 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14868 } else if (onSd && ephemeral) { 14869 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14870 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14871 } else { 14872 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14873 packageAbiOverride); 14874 14875 if (DEBUG_EPHEMERAL && ephemeral) { 14876 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14877 } 14878 14879 /* 14880 * If we have too little free space, try to free cache 14881 * before giving up. 14882 */ 14883 if (!origin.staged && pkgLite.recommendedInstallLocation 14884 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14885 // TODO: focus freeing disk space on the target device 14886 final StorageManager storage = StorageManager.from(mContext); 14887 final long lowThreshold = storage.getStorageLowBytes( 14888 Environment.getDataDirectory()); 14889 14890 final long sizeBytes = mContainerService.calculateInstalledSize( 14891 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14892 14893 try { 14894 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14895 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14896 installFlags, packageAbiOverride); 14897 } catch (InstallerException e) { 14898 Slog.w(TAG, "Failed to free cache", e); 14899 } 14900 14901 /* 14902 * The cache free must have deleted the file we 14903 * downloaded to install. 14904 * 14905 * TODO: fix the "freeCache" call to not delete 14906 * the file we care about. 14907 */ 14908 if (pkgLite.recommendedInstallLocation 14909 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14910 pkgLite.recommendedInstallLocation 14911 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14912 } 14913 } 14914 } 14915 14916 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14917 int loc = pkgLite.recommendedInstallLocation; 14918 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14919 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14920 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14921 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14922 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14923 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14924 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14925 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14926 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14927 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14928 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14929 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14930 } else { 14931 // Override with defaults if needed. 14932 loc = installLocationPolicy(pkgLite); 14933 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14934 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14935 } else if (!onSd && !onInt) { 14936 // Override install location with flags 14937 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14938 // Set the flag to install on external media. 14939 installFlags |= PackageManager.INSTALL_EXTERNAL; 14940 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14941 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14942 if (DEBUG_EPHEMERAL) { 14943 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14944 } 14945 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14946 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14947 |PackageManager.INSTALL_INTERNAL); 14948 } else { 14949 // Make sure the flag for installing on external 14950 // media is unset 14951 installFlags |= PackageManager.INSTALL_INTERNAL; 14952 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14953 } 14954 } 14955 } 14956 } 14957 14958 final InstallArgs args = createInstallArgs(this); 14959 mArgs = args; 14960 14961 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14962 // TODO: http://b/22976637 14963 // Apps installed for "all" users use the device owner to verify the app 14964 UserHandle verifierUser = getUser(); 14965 if (verifierUser == UserHandle.ALL) { 14966 verifierUser = UserHandle.SYSTEM; 14967 } 14968 14969 /* 14970 * Determine if we have any installed package verifiers. If we 14971 * do, then we'll defer to them to verify the packages. 14972 */ 14973 final int requiredUid = mRequiredVerifierPackage == null ? -1 14974 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14975 verifierUser.getIdentifier()); 14976 if (!origin.existing && requiredUid != -1 14977 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14978 final Intent verification = new Intent( 14979 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14980 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14981 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14982 PACKAGE_MIME_TYPE); 14983 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14984 14985 // Query all live verifiers based on current user state 14986 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14987 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14988 14989 if (DEBUG_VERIFY) { 14990 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14991 + verification.toString() + " with " + pkgLite.verifiers.length 14992 + " optional verifiers"); 14993 } 14994 14995 final int verificationId = mPendingVerificationToken++; 14996 14997 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14998 14999 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15000 installerPackageName); 15001 15002 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15003 installFlags); 15004 15005 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15006 pkgLite.packageName); 15007 15008 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15009 pkgLite.versionCode); 15010 15011 if (verificationInfo != null) { 15012 if (verificationInfo.originatingUri != null) { 15013 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15014 verificationInfo.originatingUri); 15015 } 15016 if (verificationInfo.referrer != null) { 15017 verification.putExtra(Intent.EXTRA_REFERRER, 15018 verificationInfo.referrer); 15019 } 15020 if (verificationInfo.originatingUid >= 0) { 15021 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15022 verificationInfo.originatingUid); 15023 } 15024 if (verificationInfo.installerUid >= 0) { 15025 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15026 verificationInfo.installerUid); 15027 } 15028 } 15029 15030 final PackageVerificationState verificationState = new PackageVerificationState( 15031 requiredUid, args); 15032 15033 mPendingVerification.append(verificationId, verificationState); 15034 15035 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15036 receivers, verificationState); 15037 15038 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15039 final long idleDuration = getVerificationTimeout(); 15040 15041 /* 15042 * If any sufficient verifiers were listed in the package 15043 * manifest, attempt to ask them. 15044 */ 15045 if (sufficientVerifiers != null) { 15046 final int N = sufficientVerifiers.size(); 15047 if (N == 0) { 15048 Slog.i(TAG, "Additional verifiers required, but none installed."); 15049 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15050 } else { 15051 for (int i = 0; i < N; i++) { 15052 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15053 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15054 verifierComponent.getPackageName(), idleDuration, 15055 verifierUser.getIdentifier(), false, "package verifier"); 15056 15057 final Intent sufficientIntent = new Intent(verification); 15058 sufficientIntent.setComponent(verifierComponent); 15059 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15060 } 15061 } 15062 } 15063 15064 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15065 mRequiredVerifierPackage, receivers); 15066 if (ret == PackageManager.INSTALL_SUCCEEDED 15067 && mRequiredVerifierPackage != null) { 15068 Trace.asyncTraceBegin( 15069 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15070 /* 15071 * Send the intent to the required verification agent, 15072 * but only start the verification timeout after the 15073 * target BroadcastReceivers have run. 15074 */ 15075 verification.setComponent(requiredVerifierComponent); 15076 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15077 mRequiredVerifierPackage, idleDuration, 15078 verifierUser.getIdentifier(), false, "package verifier"); 15079 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15080 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15081 new BroadcastReceiver() { 15082 @Override 15083 public void onReceive(Context context, Intent intent) { 15084 final Message msg = mHandler 15085 .obtainMessage(CHECK_PENDING_VERIFICATION); 15086 msg.arg1 = verificationId; 15087 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15088 } 15089 }, null, 0, null, null); 15090 15091 /* 15092 * We don't want the copy to proceed until verification 15093 * succeeds, so null out this field. 15094 */ 15095 mArgs = null; 15096 } 15097 } else { 15098 /* 15099 * No package verification is enabled, so immediately start 15100 * the remote call to initiate copy using temporary file. 15101 */ 15102 ret = args.copyApk(mContainerService, true); 15103 } 15104 } 15105 15106 mRet = ret; 15107 } 15108 15109 @Override 15110 void handleReturnCode() { 15111 // If mArgs is null, then MCS couldn't be reached. When it 15112 // reconnects, it will try again to install. At that point, this 15113 // will succeed. 15114 if (mArgs != null) { 15115 processPendingInstall(mArgs, mRet); 15116 } 15117 } 15118 15119 @Override 15120 void handleServiceError() { 15121 mArgs = createInstallArgs(this); 15122 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15123 } 15124 15125 public boolean isForwardLocked() { 15126 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15127 } 15128 } 15129 15130 /** 15131 * Used during creation of InstallArgs 15132 * 15133 * @param installFlags package installation flags 15134 * @return true if should be installed on external storage 15135 */ 15136 private static boolean installOnExternalAsec(int installFlags) { 15137 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 15138 return false; 15139 } 15140 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 15141 return true; 15142 } 15143 return false; 15144 } 15145 15146 /** 15147 * Used during creation of InstallArgs 15148 * 15149 * @param installFlags package installation flags 15150 * @return true if should be installed as forward locked 15151 */ 15152 private static boolean installForwardLocked(int installFlags) { 15153 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15154 } 15155 15156 private InstallArgs createInstallArgs(InstallParams params) { 15157 if (params.move != null) { 15158 return new MoveInstallArgs(params); 15159 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 15160 return new AsecInstallArgs(params); 15161 } else { 15162 return new FileInstallArgs(params); 15163 } 15164 } 15165 15166 /** 15167 * Create args that describe an existing installed package. Typically used 15168 * when cleaning up old installs, or used as a move source. 15169 */ 15170 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15171 String resourcePath, String[] instructionSets) { 15172 final boolean isInAsec; 15173 if (installOnExternalAsec(installFlags)) { 15174 /* Apps on SD card are always in ASEC containers. */ 15175 isInAsec = true; 15176 } else if (installForwardLocked(installFlags) 15177 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 15178 /* 15179 * Forward-locked apps are only in ASEC containers if they're the 15180 * new style 15181 */ 15182 isInAsec = true; 15183 } else { 15184 isInAsec = false; 15185 } 15186 15187 if (isInAsec) { 15188 return new AsecInstallArgs(codePath, instructionSets, 15189 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 15190 } else { 15191 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15192 } 15193 } 15194 15195 static abstract class InstallArgs { 15196 /** @see InstallParams#origin */ 15197 final OriginInfo origin; 15198 /** @see InstallParams#move */ 15199 final MoveInfo move; 15200 15201 final IPackageInstallObserver2 observer; 15202 // Always refers to PackageManager flags only 15203 final int installFlags; 15204 final String installerPackageName; 15205 final String volumeUuid; 15206 final UserHandle user; 15207 final String abiOverride; 15208 final String[] installGrantPermissions; 15209 /** If non-null, drop an async trace when the install completes */ 15210 final String traceMethod; 15211 final int traceCookie; 15212 final Certificate[][] certificates; 15213 final int installReason; 15214 15215 // The list of instruction sets supported by this app. This is currently 15216 // only used during the rmdex() phase to clean up resources. We can get rid of this 15217 // if we move dex files under the common app path. 15218 /* nullable */ String[] instructionSets; 15219 15220 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15221 int installFlags, String installerPackageName, String volumeUuid, 15222 UserHandle user, String[] instructionSets, 15223 String abiOverride, String[] installGrantPermissions, 15224 String traceMethod, int traceCookie, Certificate[][] certificates, 15225 int installReason) { 15226 this.origin = origin; 15227 this.move = move; 15228 this.installFlags = installFlags; 15229 this.observer = observer; 15230 this.installerPackageName = installerPackageName; 15231 this.volumeUuid = volumeUuid; 15232 this.user = user; 15233 this.instructionSets = instructionSets; 15234 this.abiOverride = abiOverride; 15235 this.installGrantPermissions = installGrantPermissions; 15236 this.traceMethod = traceMethod; 15237 this.traceCookie = traceCookie; 15238 this.certificates = certificates; 15239 this.installReason = installReason; 15240 } 15241 15242 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15243 abstract int doPreInstall(int status); 15244 15245 /** 15246 * Rename package into final resting place. All paths on the given 15247 * scanned package should be updated to reflect the rename. 15248 */ 15249 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15250 abstract int doPostInstall(int status, int uid); 15251 15252 /** @see PackageSettingBase#codePathString */ 15253 abstract String getCodePath(); 15254 /** @see PackageSettingBase#resourcePathString */ 15255 abstract String getResourcePath(); 15256 15257 // Need installer lock especially for dex file removal. 15258 abstract void cleanUpResourcesLI(); 15259 abstract boolean doPostDeleteLI(boolean delete); 15260 15261 /** 15262 * Called before the source arguments are copied. This is used mostly 15263 * for MoveParams when it needs to read the source file to put it in the 15264 * destination. 15265 */ 15266 int doPreCopy() { 15267 return PackageManager.INSTALL_SUCCEEDED; 15268 } 15269 15270 /** 15271 * Called after the source arguments are copied. This is used mostly for 15272 * MoveParams when it needs to read the source file to put it in the 15273 * destination. 15274 */ 15275 int doPostCopy(int uid) { 15276 return PackageManager.INSTALL_SUCCEEDED; 15277 } 15278 15279 protected boolean isFwdLocked() { 15280 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15281 } 15282 15283 protected boolean isExternalAsec() { 15284 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15285 } 15286 15287 protected boolean isEphemeral() { 15288 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15289 } 15290 15291 UserHandle getUser() { 15292 return user; 15293 } 15294 } 15295 15296 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15297 if (!allCodePaths.isEmpty()) { 15298 if (instructionSets == null) { 15299 throw new IllegalStateException("instructionSet == null"); 15300 } 15301 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15302 for (String codePath : allCodePaths) { 15303 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15304 try { 15305 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15306 } catch (InstallerException ignored) { 15307 } 15308 } 15309 } 15310 } 15311 } 15312 15313 /** 15314 * Logic to handle installation of non-ASEC applications, including copying 15315 * and renaming logic. 15316 */ 15317 class FileInstallArgs extends InstallArgs { 15318 private File codeFile; 15319 private File resourceFile; 15320 15321 // Example topology: 15322 // /data/app/com.example/base.apk 15323 // /data/app/com.example/split_foo.apk 15324 // /data/app/com.example/lib/arm/libfoo.so 15325 // /data/app/com.example/lib/arm64/libfoo.so 15326 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15327 15328 /** New install */ 15329 FileInstallArgs(InstallParams params) { 15330 super(params.origin, params.move, params.observer, params.installFlags, 15331 params.installerPackageName, params.volumeUuid, 15332 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15333 params.grantedRuntimePermissions, 15334 params.traceMethod, params.traceCookie, params.certificates, 15335 params.installReason); 15336 if (isFwdLocked()) { 15337 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15338 } 15339 } 15340 15341 /** Existing install */ 15342 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15343 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15344 null, null, null, 0, null /*certificates*/, 15345 PackageManager.INSTALL_REASON_UNKNOWN); 15346 this.codeFile = (codePath != null) ? new File(codePath) : null; 15347 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15348 } 15349 15350 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15351 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15352 try { 15353 return doCopyApk(imcs, temp); 15354 } finally { 15355 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15356 } 15357 } 15358 15359 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15360 if (origin.staged) { 15361 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15362 codeFile = origin.file; 15363 resourceFile = origin.file; 15364 return PackageManager.INSTALL_SUCCEEDED; 15365 } 15366 15367 try { 15368 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15369 final File tempDir = 15370 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15371 codeFile = tempDir; 15372 resourceFile = tempDir; 15373 } catch (IOException e) { 15374 Slog.w(TAG, "Failed to create copy file: " + e); 15375 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15376 } 15377 15378 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15379 @Override 15380 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15381 if (!FileUtils.isValidExtFilename(name)) { 15382 throw new IllegalArgumentException("Invalid filename: " + name); 15383 } 15384 try { 15385 final File file = new File(codeFile, name); 15386 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15387 O_RDWR | O_CREAT, 0644); 15388 Os.chmod(file.getAbsolutePath(), 0644); 15389 return new ParcelFileDescriptor(fd); 15390 } catch (ErrnoException e) { 15391 throw new RemoteException("Failed to open: " + e.getMessage()); 15392 } 15393 } 15394 }; 15395 15396 int ret = PackageManager.INSTALL_SUCCEEDED; 15397 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15398 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15399 Slog.e(TAG, "Failed to copy package"); 15400 return ret; 15401 } 15402 15403 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15404 NativeLibraryHelper.Handle handle = null; 15405 try { 15406 handle = NativeLibraryHelper.Handle.create(codeFile); 15407 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15408 abiOverride); 15409 } catch (IOException e) { 15410 Slog.e(TAG, "Copying native libraries failed", e); 15411 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15412 } finally { 15413 IoUtils.closeQuietly(handle); 15414 } 15415 15416 return ret; 15417 } 15418 15419 int doPreInstall(int status) { 15420 if (status != PackageManager.INSTALL_SUCCEEDED) { 15421 cleanUp(); 15422 } 15423 return status; 15424 } 15425 15426 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15427 if (status != PackageManager.INSTALL_SUCCEEDED) { 15428 cleanUp(); 15429 return false; 15430 } 15431 15432 final File targetDir = codeFile.getParentFile(); 15433 final File beforeCodeFile = codeFile; 15434 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15435 15436 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15437 try { 15438 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15439 } catch (ErrnoException e) { 15440 Slog.w(TAG, "Failed to rename", e); 15441 return false; 15442 } 15443 15444 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15445 Slog.w(TAG, "Failed to restorecon"); 15446 return false; 15447 } 15448 15449 // Reflect the rename internally 15450 codeFile = afterCodeFile; 15451 resourceFile = afterCodeFile; 15452 15453 // Reflect the rename in scanned details 15454 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15455 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15456 afterCodeFile, pkg.baseCodePath)); 15457 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15458 afterCodeFile, pkg.splitCodePaths)); 15459 15460 // Reflect the rename in app info 15461 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15462 pkg.setApplicationInfoCodePath(pkg.codePath); 15463 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15464 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15465 pkg.setApplicationInfoResourcePath(pkg.codePath); 15466 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15467 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15468 15469 return true; 15470 } 15471 15472 int doPostInstall(int status, int uid) { 15473 if (status != PackageManager.INSTALL_SUCCEEDED) { 15474 cleanUp(); 15475 } 15476 return status; 15477 } 15478 15479 @Override 15480 String getCodePath() { 15481 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15482 } 15483 15484 @Override 15485 String getResourcePath() { 15486 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15487 } 15488 15489 private boolean cleanUp() { 15490 if (codeFile == null || !codeFile.exists()) { 15491 return false; 15492 } 15493 15494 removeCodePathLI(codeFile); 15495 15496 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15497 resourceFile.delete(); 15498 } 15499 15500 return true; 15501 } 15502 15503 void cleanUpResourcesLI() { 15504 // Try enumerating all code paths before deleting 15505 List<String> allCodePaths = Collections.EMPTY_LIST; 15506 if (codeFile != null && codeFile.exists()) { 15507 try { 15508 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15509 allCodePaths = pkg.getAllCodePaths(); 15510 } catch (PackageParserException e) { 15511 // Ignored; we tried our best 15512 } 15513 } 15514 15515 cleanUp(); 15516 removeDexFiles(allCodePaths, instructionSets); 15517 } 15518 15519 boolean doPostDeleteLI(boolean delete) { 15520 // XXX err, shouldn't we respect the delete flag? 15521 cleanUpResourcesLI(); 15522 return true; 15523 } 15524 } 15525 15526 private boolean isAsecExternal(String cid) { 15527 final String asecPath = PackageHelper.getSdFilesystem(cid); 15528 return !asecPath.startsWith(mAsecInternalPath); 15529 } 15530 15531 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15532 PackageManagerException { 15533 if (copyRet < 0) { 15534 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15535 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15536 throw new PackageManagerException(copyRet, message); 15537 } 15538 } 15539 } 15540 15541 /** 15542 * Extract the StorageManagerService "container ID" from the full code path of an 15543 * .apk. 15544 */ 15545 static String cidFromCodePath(String fullCodePath) { 15546 int eidx = fullCodePath.lastIndexOf("/"); 15547 String subStr1 = fullCodePath.substring(0, eidx); 15548 int sidx = subStr1.lastIndexOf("/"); 15549 return subStr1.substring(sidx+1, eidx); 15550 } 15551 15552 /** 15553 * Logic to handle installation of ASEC applications, including copying and 15554 * renaming logic. 15555 */ 15556 class AsecInstallArgs extends InstallArgs { 15557 static final String RES_FILE_NAME = "pkg.apk"; 15558 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15559 15560 String cid; 15561 String packagePath; 15562 String resourcePath; 15563 15564 /** New install */ 15565 AsecInstallArgs(InstallParams params) { 15566 super(params.origin, params.move, params.observer, params.installFlags, 15567 params.installerPackageName, params.volumeUuid, 15568 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15569 params.grantedRuntimePermissions, 15570 params.traceMethod, params.traceCookie, params.certificates, 15571 params.installReason); 15572 } 15573 15574 /** Existing install */ 15575 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15576 boolean isExternal, boolean isForwardLocked) { 15577 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15578 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15579 instructionSets, null, null, null, 0, null /*certificates*/, 15580 PackageManager.INSTALL_REASON_UNKNOWN); 15581 // Hackily pretend we're still looking at a full code path 15582 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15583 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15584 } 15585 15586 // Extract cid from fullCodePath 15587 int eidx = fullCodePath.lastIndexOf("/"); 15588 String subStr1 = fullCodePath.substring(0, eidx); 15589 int sidx = subStr1.lastIndexOf("/"); 15590 cid = subStr1.substring(sidx+1, eidx); 15591 setMountPath(subStr1); 15592 } 15593 15594 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15595 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15596 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15597 instructionSets, null, null, null, 0, null /*certificates*/, 15598 PackageManager.INSTALL_REASON_UNKNOWN); 15599 this.cid = cid; 15600 setMountPath(PackageHelper.getSdDir(cid)); 15601 } 15602 15603 void createCopyFile() { 15604 cid = mInstallerService.allocateExternalStageCidLegacy(); 15605 } 15606 15607 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15608 if (origin.staged && origin.cid != null) { 15609 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15610 cid = origin.cid; 15611 setMountPath(PackageHelper.getSdDir(cid)); 15612 return PackageManager.INSTALL_SUCCEEDED; 15613 } 15614 15615 if (temp) { 15616 createCopyFile(); 15617 } else { 15618 /* 15619 * Pre-emptively destroy the container since it's destroyed if 15620 * copying fails due to it existing anyway. 15621 */ 15622 PackageHelper.destroySdDir(cid); 15623 } 15624 15625 final String newMountPath = imcs.copyPackageToContainer( 15626 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15627 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15628 15629 if (newMountPath != null) { 15630 setMountPath(newMountPath); 15631 return PackageManager.INSTALL_SUCCEEDED; 15632 } else { 15633 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15634 } 15635 } 15636 15637 @Override 15638 String getCodePath() { 15639 return packagePath; 15640 } 15641 15642 @Override 15643 String getResourcePath() { 15644 return resourcePath; 15645 } 15646 15647 int doPreInstall(int status) { 15648 if (status != PackageManager.INSTALL_SUCCEEDED) { 15649 // Destroy container 15650 PackageHelper.destroySdDir(cid); 15651 } else { 15652 boolean mounted = PackageHelper.isContainerMounted(cid); 15653 if (!mounted) { 15654 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15655 Process.SYSTEM_UID); 15656 if (newMountPath != null) { 15657 setMountPath(newMountPath); 15658 } else { 15659 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15660 } 15661 } 15662 } 15663 return status; 15664 } 15665 15666 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15667 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15668 String newMountPath = null; 15669 if (PackageHelper.isContainerMounted(cid)) { 15670 // Unmount the container 15671 if (!PackageHelper.unMountSdDir(cid)) { 15672 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15673 return false; 15674 } 15675 } 15676 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15677 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15678 " which might be stale. Will try to clean up."); 15679 // Clean up the stale container and proceed to recreate. 15680 if (!PackageHelper.destroySdDir(newCacheId)) { 15681 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15682 return false; 15683 } 15684 // Successfully cleaned up stale container. Try to rename again. 15685 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15686 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15687 + " inspite of cleaning it up."); 15688 return false; 15689 } 15690 } 15691 if (!PackageHelper.isContainerMounted(newCacheId)) { 15692 Slog.w(TAG, "Mounting container " + newCacheId); 15693 newMountPath = PackageHelper.mountSdDir(newCacheId, 15694 getEncryptKey(), Process.SYSTEM_UID); 15695 } else { 15696 newMountPath = PackageHelper.getSdDir(newCacheId); 15697 } 15698 if (newMountPath == null) { 15699 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15700 return false; 15701 } 15702 Log.i(TAG, "Succesfully renamed " + cid + 15703 " to " + newCacheId + 15704 " at new path: " + newMountPath); 15705 cid = newCacheId; 15706 15707 final File beforeCodeFile = new File(packagePath); 15708 setMountPath(newMountPath); 15709 final File afterCodeFile = new File(packagePath); 15710 15711 // Reflect the rename in scanned details 15712 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15713 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15714 afterCodeFile, pkg.baseCodePath)); 15715 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15716 afterCodeFile, pkg.splitCodePaths)); 15717 15718 // Reflect the rename in app info 15719 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15720 pkg.setApplicationInfoCodePath(pkg.codePath); 15721 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15722 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15723 pkg.setApplicationInfoResourcePath(pkg.codePath); 15724 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15725 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15726 15727 return true; 15728 } 15729 15730 private void setMountPath(String mountPath) { 15731 final File mountFile = new File(mountPath); 15732 15733 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15734 if (monolithicFile.exists()) { 15735 packagePath = monolithicFile.getAbsolutePath(); 15736 if (isFwdLocked()) { 15737 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15738 } else { 15739 resourcePath = packagePath; 15740 } 15741 } else { 15742 packagePath = mountFile.getAbsolutePath(); 15743 resourcePath = packagePath; 15744 } 15745 } 15746 15747 int doPostInstall(int status, int uid) { 15748 if (status != PackageManager.INSTALL_SUCCEEDED) { 15749 cleanUp(); 15750 } else { 15751 final int groupOwner; 15752 final String protectedFile; 15753 if (isFwdLocked()) { 15754 groupOwner = UserHandle.getSharedAppGid(uid); 15755 protectedFile = RES_FILE_NAME; 15756 } else { 15757 groupOwner = -1; 15758 protectedFile = null; 15759 } 15760 15761 if (uid < Process.FIRST_APPLICATION_UID 15762 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15763 Slog.e(TAG, "Failed to finalize " + cid); 15764 PackageHelper.destroySdDir(cid); 15765 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15766 } 15767 15768 boolean mounted = PackageHelper.isContainerMounted(cid); 15769 if (!mounted) { 15770 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15771 } 15772 } 15773 return status; 15774 } 15775 15776 private void cleanUp() { 15777 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15778 15779 // Destroy secure container 15780 PackageHelper.destroySdDir(cid); 15781 } 15782 15783 private List<String> getAllCodePaths() { 15784 final File codeFile = new File(getCodePath()); 15785 if (codeFile != null && codeFile.exists()) { 15786 try { 15787 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15788 return pkg.getAllCodePaths(); 15789 } catch (PackageParserException e) { 15790 // Ignored; we tried our best 15791 } 15792 } 15793 return Collections.EMPTY_LIST; 15794 } 15795 15796 void cleanUpResourcesLI() { 15797 // Enumerate all code paths before deleting 15798 cleanUpResourcesLI(getAllCodePaths()); 15799 } 15800 15801 private void cleanUpResourcesLI(List<String> allCodePaths) { 15802 cleanUp(); 15803 removeDexFiles(allCodePaths, instructionSets); 15804 } 15805 15806 String getPackageName() { 15807 return getAsecPackageName(cid); 15808 } 15809 15810 boolean doPostDeleteLI(boolean delete) { 15811 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15812 final List<String> allCodePaths = getAllCodePaths(); 15813 boolean mounted = PackageHelper.isContainerMounted(cid); 15814 if (mounted) { 15815 // Unmount first 15816 if (PackageHelper.unMountSdDir(cid)) { 15817 mounted = false; 15818 } 15819 } 15820 if (!mounted && delete) { 15821 cleanUpResourcesLI(allCodePaths); 15822 } 15823 return !mounted; 15824 } 15825 15826 @Override 15827 int doPreCopy() { 15828 if (isFwdLocked()) { 15829 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15830 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15831 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15832 } 15833 } 15834 15835 return PackageManager.INSTALL_SUCCEEDED; 15836 } 15837 15838 @Override 15839 int doPostCopy(int uid) { 15840 if (isFwdLocked()) { 15841 if (uid < Process.FIRST_APPLICATION_UID 15842 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15843 RES_FILE_NAME)) { 15844 Slog.e(TAG, "Failed to finalize " + cid); 15845 PackageHelper.destroySdDir(cid); 15846 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15847 } 15848 } 15849 15850 return PackageManager.INSTALL_SUCCEEDED; 15851 } 15852 } 15853 15854 /** 15855 * Logic to handle movement of existing installed applications. 15856 */ 15857 class MoveInstallArgs extends InstallArgs { 15858 private File codeFile; 15859 private File resourceFile; 15860 15861 /** New install */ 15862 MoveInstallArgs(InstallParams params) { 15863 super(params.origin, params.move, params.observer, params.installFlags, 15864 params.installerPackageName, params.volumeUuid, 15865 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15866 params.grantedRuntimePermissions, 15867 params.traceMethod, params.traceCookie, params.certificates, 15868 params.installReason); 15869 } 15870 15871 int copyApk(IMediaContainerService imcs, boolean temp) { 15872 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15873 + move.fromUuid + " to " + move.toUuid); 15874 synchronized (mInstaller) { 15875 try { 15876 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15877 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15878 } catch (InstallerException e) { 15879 Slog.w(TAG, "Failed to move app", e); 15880 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15881 } 15882 } 15883 15884 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15885 resourceFile = codeFile; 15886 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15887 15888 return PackageManager.INSTALL_SUCCEEDED; 15889 } 15890 15891 int doPreInstall(int status) { 15892 if (status != PackageManager.INSTALL_SUCCEEDED) { 15893 cleanUp(move.toUuid); 15894 } 15895 return status; 15896 } 15897 15898 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15899 if (status != PackageManager.INSTALL_SUCCEEDED) { 15900 cleanUp(move.toUuid); 15901 return false; 15902 } 15903 15904 // Reflect the move in app info 15905 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15906 pkg.setApplicationInfoCodePath(pkg.codePath); 15907 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15908 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15909 pkg.setApplicationInfoResourcePath(pkg.codePath); 15910 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15911 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15912 15913 return true; 15914 } 15915 15916 int doPostInstall(int status, int uid) { 15917 if (status == PackageManager.INSTALL_SUCCEEDED) { 15918 cleanUp(move.fromUuid); 15919 } else { 15920 cleanUp(move.toUuid); 15921 } 15922 return status; 15923 } 15924 15925 @Override 15926 String getCodePath() { 15927 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15928 } 15929 15930 @Override 15931 String getResourcePath() { 15932 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15933 } 15934 15935 private boolean cleanUp(String volumeUuid) { 15936 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15937 move.dataAppName); 15938 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15939 final int[] userIds = sUserManager.getUserIds(); 15940 synchronized (mInstallLock) { 15941 // Clean up both app data and code 15942 // All package moves are frozen until finished 15943 for (int userId : userIds) { 15944 try { 15945 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15946 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15947 } catch (InstallerException e) { 15948 Slog.w(TAG, String.valueOf(e)); 15949 } 15950 } 15951 removeCodePathLI(codeFile); 15952 } 15953 return true; 15954 } 15955 15956 void cleanUpResourcesLI() { 15957 throw new UnsupportedOperationException(); 15958 } 15959 15960 boolean doPostDeleteLI(boolean delete) { 15961 throw new UnsupportedOperationException(); 15962 } 15963 } 15964 15965 static String getAsecPackageName(String packageCid) { 15966 int idx = packageCid.lastIndexOf("-"); 15967 if (idx == -1) { 15968 return packageCid; 15969 } 15970 return packageCid.substring(0, idx); 15971 } 15972 15973 // Utility method used to create code paths based on package name and available index. 15974 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15975 String idxStr = ""; 15976 int idx = 1; 15977 // Fall back to default value of idx=1 if prefix is not 15978 // part of oldCodePath 15979 if (oldCodePath != null) { 15980 String subStr = oldCodePath; 15981 // Drop the suffix right away 15982 if (suffix != null && subStr.endsWith(suffix)) { 15983 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15984 } 15985 // If oldCodePath already contains prefix find out the 15986 // ending index to either increment or decrement. 15987 int sidx = subStr.lastIndexOf(prefix); 15988 if (sidx != -1) { 15989 subStr = subStr.substring(sidx + prefix.length()); 15990 if (subStr != null) { 15991 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15992 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15993 } 15994 try { 15995 idx = Integer.parseInt(subStr); 15996 if (idx <= 1) { 15997 idx++; 15998 } else { 15999 idx--; 16000 } 16001 } catch(NumberFormatException e) { 16002 } 16003 } 16004 } 16005 } 16006 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 16007 return prefix + idxStr; 16008 } 16009 16010 private File getNextCodePath(File targetDir, String packageName) { 16011 File result; 16012 SecureRandom random = new SecureRandom(); 16013 byte[] bytes = new byte[16]; 16014 do { 16015 random.nextBytes(bytes); 16016 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16017 result = new File(targetDir, packageName + "-" + suffix); 16018 } while (result.exists()); 16019 return result; 16020 } 16021 16022 // Utility method that returns the relative package path with respect 16023 // to the installation directory. Like say for /data/data/com.test-1.apk 16024 // string com.test-1 is returned. 16025 static String deriveCodePathName(String codePath) { 16026 if (codePath == null) { 16027 return null; 16028 } 16029 final File codeFile = new File(codePath); 16030 final String name = codeFile.getName(); 16031 if (codeFile.isDirectory()) { 16032 return name; 16033 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16034 final int lastDot = name.lastIndexOf('.'); 16035 return name.substring(0, lastDot); 16036 } else { 16037 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16038 return null; 16039 } 16040 } 16041 16042 static class PackageInstalledInfo { 16043 String name; 16044 int uid; 16045 // The set of users that originally had this package installed. 16046 int[] origUsers; 16047 // The set of users that now have this package installed. 16048 int[] newUsers; 16049 PackageParser.Package pkg; 16050 int returnCode; 16051 String returnMsg; 16052 PackageRemovedInfo removedInfo; 16053 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16054 16055 public void setError(int code, String msg) { 16056 setReturnCode(code); 16057 setReturnMessage(msg); 16058 Slog.w(TAG, msg); 16059 } 16060 16061 public void setError(String msg, PackageParserException e) { 16062 setReturnCode(e.error); 16063 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16064 Slog.w(TAG, msg, e); 16065 } 16066 16067 public void setError(String msg, PackageManagerException e) { 16068 returnCode = e.error; 16069 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16070 Slog.w(TAG, msg, e); 16071 } 16072 16073 public void setReturnCode(int returnCode) { 16074 this.returnCode = returnCode; 16075 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16076 for (int i = 0; i < childCount; i++) { 16077 addedChildPackages.valueAt(i).returnCode = returnCode; 16078 } 16079 } 16080 16081 private void setReturnMessage(String returnMsg) { 16082 this.returnMsg = returnMsg; 16083 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16084 for (int i = 0; i < childCount; i++) { 16085 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16086 } 16087 } 16088 16089 // In some error cases we want to convey more info back to the observer 16090 String origPackage; 16091 String origPermission; 16092 } 16093 16094 /* 16095 * Install a non-existing package. 16096 */ 16097 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 16098 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 16099 PackageInstalledInfo res, int installReason) { 16100 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 16101 16102 // Remember this for later, in case we need to rollback this install 16103 String pkgName = pkg.packageName; 16104 16105 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 16106 16107 synchronized(mPackages) { 16108 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16109 if (renamedPackage != null) { 16110 // A package with the same name is already installed, though 16111 // it has been renamed to an older name. The package we 16112 // are trying to install should be installed as an update to 16113 // the existing one, but that has not been requested, so bail. 16114 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16115 + " without first uninstalling package running as " 16116 + renamedPackage); 16117 return; 16118 } 16119 if (mPackages.containsKey(pkgName)) { 16120 // Don't allow installation over an existing package with the same name. 16121 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16122 + " without first uninstalling."); 16123 return; 16124 } 16125 } 16126 16127 try { 16128 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 16129 System.currentTimeMillis(), user); 16130 16131 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16132 16133 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16134 prepareAppDataAfterInstallLIF(newPackage); 16135 16136 } else { 16137 // Remove package from internal structures, but keep around any 16138 // data that might have already existed 16139 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16140 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16141 } 16142 } catch (PackageManagerException e) { 16143 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16144 } 16145 16146 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16147 } 16148 16149 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 16150 // Can't rotate keys during boot or if sharedUser. 16151 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 16152 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 16153 return false; 16154 } 16155 // app is using upgradeKeySets; make sure all are valid 16156 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16157 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 16158 for (int i = 0; i < upgradeKeySets.length; i++) { 16159 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 16160 Slog.wtf(TAG, "Package " 16161 + (oldPs.name != null ? oldPs.name : "<null>") 16162 + " contains upgrade-key-set reference to unknown key-set: " 16163 + upgradeKeySets[i] 16164 + " reverting to signatures check."); 16165 return false; 16166 } 16167 } 16168 return true; 16169 } 16170 16171 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 16172 // Upgrade keysets are being used. Determine if new package has a superset of the 16173 // required keys. 16174 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 16175 KeySetManagerService ksms = mSettings.mKeySetManagerService; 16176 for (int i = 0; i < upgradeKeySets.length; i++) { 16177 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 16178 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 16179 return true; 16180 } 16181 } 16182 return false; 16183 } 16184 16185 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16186 try (DigestInputStream digestStream = 16187 new DigestInputStream(new FileInputStream(file), digest)) { 16188 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16189 } 16190 } 16191 16192 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 16193 UserHandle user, String installerPackageName, PackageInstalledInfo res, 16194 int installReason) { 16195 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16196 16197 final PackageParser.Package oldPackage; 16198 final PackageSetting ps; 16199 final String pkgName = pkg.packageName; 16200 final int[] allUsers; 16201 final int[] installedUsers; 16202 16203 synchronized(mPackages) { 16204 oldPackage = mPackages.get(pkgName); 16205 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16206 16207 // don't allow upgrade to target a release SDK from a pre-release SDK 16208 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16209 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16210 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16211 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16212 if (oldTargetsPreRelease 16213 && !newTargetsPreRelease 16214 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16215 Slog.w(TAG, "Can't install package targeting released sdk"); 16216 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16217 return; 16218 } 16219 16220 ps = mSettings.mPackages.get(pkgName); 16221 16222 // verify signatures are valid 16223 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 16224 if (!checkUpgradeKeySetLP(ps, pkg)) { 16225 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16226 "New package not signed by keys specified by upgrade-keysets: " 16227 + pkgName); 16228 return; 16229 } 16230 } else { 16231 // default to original signature matching 16232 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 16233 != PackageManager.SIGNATURE_MATCH) { 16234 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16235 "New package has a different signature: " + pkgName); 16236 return; 16237 } 16238 } 16239 16240 // don't allow a system upgrade unless the upgrade hash matches 16241 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 16242 byte[] digestBytes = null; 16243 try { 16244 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16245 updateDigest(digest, new File(pkg.baseCodePath)); 16246 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16247 for (String path : pkg.splitCodePaths) { 16248 updateDigest(digest, new File(path)); 16249 } 16250 } 16251 digestBytes = digest.digest(); 16252 } catch (NoSuchAlgorithmException | IOException e) { 16253 res.setError(INSTALL_FAILED_INVALID_APK, 16254 "Could not compute hash: " + pkgName); 16255 return; 16256 } 16257 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16258 res.setError(INSTALL_FAILED_INVALID_APK, 16259 "New package fails restrict-update check: " + pkgName); 16260 return; 16261 } 16262 // retain upgrade restriction 16263 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16264 } 16265 16266 // Check for shared user id changes 16267 String invalidPackageName = 16268 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16269 if (invalidPackageName != null) { 16270 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16271 "Package " + invalidPackageName + " tried to change user " 16272 + oldPackage.mSharedUserId); 16273 return; 16274 } 16275 16276 // In case of rollback, remember per-user/profile install state 16277 allUsers = sUserManager.getUserIds(); 16278 installedUsers = ps.queryInstalledUsers(allUsers, true); 16279 16280 // don't allow an upgrade from full to ephemeral 16281 if (isInstantApp) { 16282 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16283 for (int currentUser : allUsers) { 16284 if (!ps.getInstantApp(currentUser)) { 16285 // can't downgrade from full to instant 16286 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16287 + " for user: " + currentUser); 16288 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16289 return; 16290 } 16291 } 16292 } else if (!ps.getInstantApp(user.getIdentifier())) { 16293 // can't downgrade from full to instant 16294 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16295 + " for user: " + user.getIdentifier()); 16296 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16297 return; 16298 } 16299 } 16300 } 16301 16302 // Update what is removed 16303 res.removedInfo = new PackageRemovedInfo(this); 16304 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16305 res.removedInfo.removedPackage = oldPackage.packageName; 16306 res.removedInfo.installerPackageName = ps.installerPackageName; 16307 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16308 res.removedInfo.isUpdate = true; 16309 res.removedInfo.origUsers = installedUsers; 16310 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16311 for (int i = 0; i < installedUsers.length; i++) { 16312 final int userId = installedUsers[i]; 16313 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16314 } 16315 16316 final int childCount = (oldPackage.childPackages != null) 16317 ? oldPackage.childPackages.size() : 0; 16318 for (int i = 0; i < childCount; i++) { 16319 boolean childPackageUpdated = false; 16320 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16321 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16322 if (res.addedChildPackages != null) { 16323 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16324 if (childRes != null) { 16325 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16326 childRes.removedInfo.removedPackage = childPkg.packageName; 16327 if (childPs != null) { 16328 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16329 } 16330 childRes.removedInfo.isUpdate = true; 16331 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16332 childPackageUpdated = true; 16333 } 16334 } 16335 if (!childPackageUpdated) { 16336 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16337 childRemovedRes.removedPackage = childPkg.packageName; 16338 if (childPs != null) { 16339 childRemovedRes.installerPackageName = childPs.installerPackageName; 16340 } 16341 childRemovedRes.isUpdate = false; 16342 childRemovedRes.dataRemoved = true; 16343 synchronized (mPackages) { 16344 if (childPs != null) { 16345 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16346 } 16347 } 16348 if (res.removedInfo.removedChildPackages == null) { 16349 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16350 } 16351 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16352 } 16353 } 16354 16355 boolean sysPkg = (isSystemApp(oldPackage)); 16356 if (sysPkg) { 16357 // Set the system/privileged flags as needed 16358 final boolean privileged = 16359 (oldPackage.applicationInfo.privateFlags 16360 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16361 final int systemPolicyFlags = policyFlags 16362 | PackageParser.PARSE_IS_SYSTEM 16363 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16364 16365 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16366 user, allUsers, installerPackageName, res, installReason); 16367 } else { 16368 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16369 user, allUsers, installerPackageName, res, installReason); 16370 } 16371 } 16372 16373 public List<String> getPreviousCodePaths(String packageName) { 16374 final PackageSetting ps = mSettings.mPackages.get(packageName); 16375 final List<String> result = new ArrayList<String>(); 16376 if (ps != null && ps.oldCodePaths != null) { 16377 result.addAll(ps.oldCodePaths); 16378 } 16379 return result; 16380 } 16381 16382 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16383 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16384 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16385 int installReason) { 16386 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16387 + deletedPackage); 16388 16389 String pkgName = deletedPackage.packageName; 16390 boolean deletedPkg = true; 16391 boolean addedPkg = false; 16392 boolean updatedSettings = false; 16393 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16394 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16395 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16396 16397 final long origUpdateTime = (pkg.mExtras != null) 16398 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16399 16400 // First delete the existing package while retaining the data directory 16401 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16402 res.removedInfo, true, pkg)) { 16403 // If the existing package wasn't successfully deleted 16404 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16405 deletedPkg = false; 16406 } else { 16407 // Successfully deleted the old package; proceed with replace. 16408 16409 // If deleted package lived in a container, give users a chance to 16410 // relinquish resources before killing. 16411 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16412 if (DEBUG_INSTALL) { 16413 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16414 } 16415 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16416 final ArrayList<String> pkgList = new ArrayList<String>(1); 16417 pkgList.add(deletedPackage.applicationInfo.packageName); 16418 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16419 } 16420 16421 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16422 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16423 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16424 16425 try { 16426 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16427 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16428 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16429 installReason); 16430 16431 // Update the in-memory copy of the previous code paths. 16432 PackageSetting ps = mSettings.mPackages.get(pkgName); 16433 if (!killApp) { 16434 if (ps.oldCodePaths == null) { 16435 ps.oldCodePaths = new ArraySet<>(); 16436 } 16437 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16438 if (deletedPackage.splitCodePaths != null) { 16439 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16440 } 16441 } else { 16442 ps.oldCodePaths = null; 16443 } 16444 if (ps.childPackageNames != null) { 16445 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16446 final String childPkgName = ps.childPackageNames.get(i); 16447 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16448 childPs.oldCodePaths = ps.oldCodePaths; 16449 } 16450 } 16451 // set instant app status, but, only if it's explicitly specified 16452 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16453 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16454 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16455 prepareAppDataAfterInstallLIF(newPackage); 16456 addedPkg = true; 16457 mDexManager.notifyPackageUpdated(newPackage.packageName, 16458 newPackage.baseCodePath, newPackage.splitCodePaths); 16459 } catch (PackageManagerException e) { 16460 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16461 } 16462 } 16463 16464 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16465 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16466 16467 // Revert all internal state mutations and added folders for the failed install 16468 if (addedPkg) { 16469 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16470 res.removedInfo, true, null); 16471 } 16472 16473 // Restore the old package 16474 if (deletedPkg) { 16475 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16476 File restoreFile = new File(deletedPackage.codePath); 16477 // Parse old package 16478 boolean oldExternal = isExternal(deletedPackage); 16479 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16480 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16481 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16482 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16483 try { 16484 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16485 null); 16486 } catch (PackageManagerException e) { 16487 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16488 + e.getMessage()); 16489 return; 16490 } 16491 16492 synchronized (mPackages) { 16493 // Ensure the installer package name up to date 16494 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16495 16496 // Update permissions for restored package 16497 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16498 16499 mSettings.writeLPr(); 16500 } 16501 16502 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16503 } 16504 } else { 16505 synchronized (mPackages) { 16506 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16507 if (ps != null) { 16508 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16509 if (res.removedInfo.removedChildPackages != null) { 16510 final int childCount = res.removedInfo.removedChildPackages.size(); 16511 // Iterate in reverse as we may modify the collection 16512 for (int i = childCount - 1; i >= 0; i--) { 16513 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16514 if (res.addedChildPackages.containsKey(childPackageName)) { 16515 res.removedInfo.removedChildPackages.removeAt(i); 16516 } else { 16517 PackageRemovedInfo childInfo = res.removedInfo 16518 .removedChildPackages.valueAt(i); 16519 childInfo.removedForAllUsers = mPackages.get( 16520 childInfo.removedPackage) == null; 16521 } 16522 } 16523 } 16524 } 16525 } 16526 } 16527 } 16528 16529 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16530 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16531 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16532 int installReason) { 16533 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16534 + ", old=" + deletedPackage); 16535 16536 final boolean disabledSystem; 16537 16538 // Remove existing system package 16539 removePackageLI(deletedPackage, true); 16540 16541 synchronized (mPackages) { 16542 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16543 } 16544 if (!disabledSystem) { 16545 // We didn't need to disable the .apk as a current system package, 16546 // which means we are replacing another update that is already 16547 // installed. We need to make sure to delete the older one's .apk. 16548 res.removedInfo.args = createInstallArgsForExisting(0, 16549 deletedPackage.applicationInfo.getCodePath(), 16550 deletedPackage.applicationInfo.getResourcePath(), 16551 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16552 } else { 16553 res.removedInfo.args = null; 16554 } 16555 16556 // Successfully disabled the old package. Now proceed with re-installation 16557 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16558 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16559 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16560 16561 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16562 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16563 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16564 16565 PackageParser.Package newPackage = null; 16566 try { 16567 // Add the package to the internal data structures 16568 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16569 16570 // Set the update and install times 16571 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16572 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16573 System.currentTimeMillis()); 16574 16575 // Update the package dynamic state if succeeded 16576 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16577 // Now that the install succeeded make sure we remove data 16578 // directories for any child package the update removed. 16579 final int deletedChildCount = (deletedPackage.childPackages != null) 16580 ? deletedPackage.childPackages.size() : 0; 16581 final int newChildCount = (newPackage.childPackages != null) 16582 ? newPackage.childPackages.size() : 0; 16583 for (int i = 0; i < deletedChildCount; i++) { 16584 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16585 boolean childPackageDeleted = true; 16586 for (int j = 0; j < newChildCount; j++) { 16587 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16588 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16589 childPackageDeleted = false; 16590 break; 16591 } 16592 } 16593 if (childPackageDeleted) { 16594 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16595 deletedChildPkg.packageName); 16596 if (ps != null && res.removedInfo.removedChildPackages != null) { 16597 PackageRemovedInfo removedChildRes = res.removedInfo 16598 .removedChildPackages.get(deletedChildPkg.packageName); 16599 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16600 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16601 } 16602 } 16603 } 16604 16605 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16606 installReason); 16607 prepareAppDataAfterInstallLIF(newPackage); 16608 16609 mDexManager.notifyPackageUpdated(newPackage.packageName, 16610 newPackage.baseCodePath, newPackage.splitCodePaths); 16611 } 16612 } catch (PackageManagerException e) { 16613 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16614 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16615 } 16616 16617 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16618 // Re installation failed. Restore old information 16619 // Remove new pkg information 16620 if (newPackage != null) { 16621 removeInstalledPackageLI(newPackage, true); 16622 } 16623 // Add back the old system package 16624 try { 16625 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16626 } catch (PackageManagerException e) { 16627 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16628 } 16629 16630 synchronized (mPackages) { 16631 if (disabledSystem) { 16632 enableSystemPackageLPw(deletedPackage); 16633 } 16634 16635 // Ensure the installer package name up to date 16636 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16637 16638 // Update permissions for restored package 16639 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16640 16641 mSettings.writeLPr(); 16642 } 16643 16644 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16645 + " after failed upgrade"); 16646 } 16647 } 16648 16649 /** 16650 * Checks whether the parent or any of the child packages have a change shared 16651 * user. For a package to be a valid update the shred users of the parent and 16652 * the children should match. We may later support changing child shared users. 16653 * @param oldPkg The updated package. 16654 * @param newPkg The update package. 16655 * @return The shared user that change between the versions. 16656 */ 16657 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16658 PackageParser.Package newPkg) { 16659 // Check parent shared user 16660 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16661 return newPkg.packageName; 16662 } 16663 // Check child shared users 16664 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16665 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16666 for (int i = 0; i < newChildCount; i++) { 16667 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16668 // If this child was present, did it have the same shared user? 16669 for (int j = 0; j < oldChildCount; j++) { 16670 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16671 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16672 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16673 return newChildPkg.packageName; 16674 } 16675 } 16676 } 16677 return null; 16678 } 16679 16680 private void removeNativeBinariesLI(PackageSetting ps) { 16681 // Remove the lib path for the parent package 16682 if (ps != null) { 16683 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16684 // Remove the lib path for the child packages 16685 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16686 for (int i = 0; i < childCount; i++) { 16687 PackageSetting childPs = null; 16688 synchronized (mPackages) { 16689 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16690 } 16691 if (childPs != null) { 16692 NativeLibraryHelper.removeNativeBinariesLI(childPs 16693 .legacyNativeLibraryPathString); 16694 } 16695 } 16696 } 16697 } 16698 16699 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16700 // Enable the parent package 16701 mSettings.enableSystemPackageLPw(pkg.packageName); 16702 // Enable the child packages 16703 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16704 for (int i = 0; i < childCount; i++) { 16705 PackageParser.Package childPkg = pkg.childPackages.get(i); 16706 mSettings.enableSystemPackageLPw(childPkg.packageName); 16707 } 16708 } 16709 16710 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16711 PackageParser.Package newPkg) { 16712 // Disable the parent package (parent always replaced) 16713 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16714 // Disable the child packages 16715 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16716 for (int i = 0; i < childCount; i++) { 16717 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16718 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16719 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16720 } 16721 return disabled; 16722 } 16723 16724 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16725 String installerPackageName) { 16726 // Enable the parent package 16727 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16728 // Enable the child packages 16729 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16730 for (int i = 0; i < childCount; i++) { 16731 PackageParser.Package childPkg = pkg.childPackages.get(i); 16732 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16733 } 16734 } 16735 16736 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16737 // Collect all used permissions in the UID 16738 ArraySet<String> usedPermissions = new ArraySet<>(); 16739 final int packageCount = su.packages.size(); 16740 for (int i = 0; i < packageCount; i++) { 16741 PackageSetting ps = su.packages.valueAt(i); 16742 if (ps.pkg == null) { 16743 continue; 16744 } 16745 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16746 for (int j = 0; j < requestedPermCount; j++) { 16747 String permission = ps.pkg.requestedPermissions.get(j); 16748 BasePermission bp = mSettings.mPermissions.get(permission); 16749 if (bp != null) { 16750 usedPermissions.add(permission); 16751 } 16752 } 16753 } 16754 16755 PermissionsState permissionsState = su.getPermissionsState(); 16756 // Prune install permissions 16757 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16758 final int installPermCount = installPermStates.size(); 16759 for (int i = installPermCount - 1; i >= 0; i--) { 16760 PermissionState permissionState = installPermStates.get(i); 16761 if (!usedPermissions.contains(permissionState.getName())) { 16762 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16763 if (bp != null) { 16764 permissionsState.revokeInstallPermission(bp); 16765 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16766 PackageManager.MASK_PERMISSION_FLAGS, 0); 16767 } 16768 } 16769 } 16770 16771 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16772 16773 // Prune runtime permissions 16774 for (int userId : allUserIds) { 16775 List<PermissionState> runtimePermStates = permissionsState 16776 .getRuntimePermissionStates(userId); 16777 final int runtimePermCount = runtimePermStates.size(); 16778 for (int i = runtimePermCount - 1; i >= 0; i--) { 16779 PermissionState permissionState = runtimePermStates.get(i); 16780 if (!usedPermissions.contains(permissionState.getName())) { 16781 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16782 if (bp != null) { 16783 permissionsState.revokeRuntimePermission(bp, userId); 16784 permissionsState.updatePermissionFlags(bp, userId, 16785 PackageManager.MASK_PERMISSION_FLAGS, 0); 16786 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16787 runtimePermissionChangedUserIds, userId); 16788 } 16789 } 16790 } 16791 } 16792 16793 return runtimePermissionChangedUserIds; 16794 } 16795 16796 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16797 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16798 // Update the parent package setting 16799 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16800 res, user, installReason); 16801 // Update the child packages setting 16802 final int childCount = (newPackage.childPackages != null) 16803 ? newPackage.childPackages.size() : 0; 16804 for (int i = 0; i < childCount; i++) { 16805 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16806 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16807 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16808 childRes.origUsers, childRes, user, installReason); 16809 } 16810 } 16811 16812 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16813 String installerPackageName, int[] allUsers, int[] installedForUsers, 16814 PackageInstalledInfo res, UserHandle user, int installReason) { 16815 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16816 16817 String pkgName = newPackage.packageName; 16818 synchronized (mPackages) { 16819 //write settings. the installStatus will be incomplete at this stage. 16820 //note that the new package setting would have already been 16821 //added to mPackages. It hasn't been persisted yet. 16822 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16823 // TODO: Remove this write? It's also written at the end of this method 16824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16825 mSettings.writeLPr(); 16826 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16827 } 16828 16829 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16830 synchronized (mPackages) { 16831 updatePermissionsLPw(newPackage.packageName, newPackage, 16832 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16833 ? UPDATE_PERMISSIONS_ALL : 0)); 16834 // For system-bundled packages, we assume that installing an upgraded version 16835 // of the package implies that the user actually wants to run that new code, 16836 // so we enable the package. 16837 PackageSetting ps = mSettings.mPackages.get(pkgName); 16838 final int userId = user.getIdentifier(); 16839 if (ps != null) { 16840 if (isSystemApp(newPackage)) { 16841 if (DEBUG_INSTALL) { 16842 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16843 } 16844 // Enable system package for requested users 16845 if (res.origUsers != null) { 16846 for (int origUserId : res.origUsers) { 16847 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16848 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16849 origUserId, installerPackageName); 16850 } 16851 } 16852 } 16853 // Also convey the prior install/uninstall state 16854 if (allUsers != null && installedForUsers != null) { 16855 for (int currentUserId : allUsers) { 16856 final boolean installed = ArrayUtils.contains( 16857 installedForUsers, currentUserId); 16858 if (DEBUG_INSTALL) { 16859 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16860 } 16861 ps.setInstalled(installed, currentUserId); 16862 } 16863 // these install state changes will be persisted in the 16864 // upcoming call to mSettings.writeLPr(). 16865 } 16866 } 16867 // It's implied that when a user requests installation, they want the app to be 16868 // installed and enabled. 16869 if (userId != UserHandle.USER_ALL) { 16870 ps.setInstalled(true, userId); 16871 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16872 } 16873 16874 // When replacing an existing package, preserve the original install reason for all 16875 // users that had the package installed before. 16876 final Set<Integer> previousUserIds = new ArraySet<>(); 16877 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16878 final int installReasonCount = res.removedInfo.installReasons.size(); 16879 for (int i = 0; i < installReasonCount; i++) { 16880 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16881 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16882 ps.setInstallReason(previousInstallReason, previousUserId); 16883 previousUserIds.add(previousUserId); 16884 } 16885 } 16886 16887 // Set install reason for users that are having the package newly installed. 16888 if (userId == UserHandle.USER_ALL) { 16889 for (int currentUserId : sUserManager.getUserIds()) { 16890 if (!previousUserIds.contains(currentUserId)) { 16891 ps.setInstallReason(installReason, currentUserId); 16892 } 16893 } 16894 } else if (!previousUserIds.contains(userId)) { 16895 ps.setInstallReason(installReason, userId); 16896 } 16897 mSettings.writeKernelMappingLPr(ps); 16898 } 16899 res.name = pkgName; 16900 res.uid = newPackage.applicationInfo.uid; 16901 res.pkg = newPackage; 16902 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16903 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16904 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16905 //to update install status 16906 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16907 mSettings.writeLPr(); 16908 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16909 } 16910 16911 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16912 } 16913 16914 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16915 try { 16916 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16917 installPackageLI(args, res); 16918 } finally { 16919 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16920 } 16921 } 16922 16923 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16924 final int installFlags = args.installFlags; 16925 final String installerPackageName = args.installerPackageName; 16926 final String volumeUuid = args.volumeUuid; 16927 final File tmpPackageFile = new File(args.getCodePath()); 16928 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16929 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16930 || (args.volumeUuid != null)); 16931 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16932 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16933 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16934 boolean replace = false; 16935 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16936 if (args.move != null) { 16937 // moving a complete application; perform an initial scan on the new install location 16938 scanFlags |= SCAN_INITIAL; 16939 } 16940 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16941 scanFlags |= SCAN_DONT_KILL_APP; 16942 } 16943 if (instantApp) { 16944 scanFlags |= SCAN_AS_INSTANT_APP; 16945 } 16946 if (fullApp) { 16947 scanFlags |= SCAN_AS_FULL_APP; 16948 } 16949 16950 // Result object to be returned 16951 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16952 16953 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16954 16955 // Sanity check 16956 if (instantApp && (forwardLocked || onExternal)) { 16957 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16958 + " external=" + onExternal); 16959 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16960 return; 16961 } 16962 16963 // Retrieve PackageSettings and parse package 16964 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16965 | PackageParser.PARSE_ENFORCE_CODE 16966 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16967 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16968 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16969 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16970 PackageParser pp = new PackageParser(); 16971 pp.setSeparateProcesses(mSeparateProcesses); 16972 pp.setDisplayMetrics(mMetrics); 16973 pp.setCallback(mPackageParserCallback); 16974 16975 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16976 final PackageParser.Package pkg; 16977 try { 16978 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16979 } catch (PackageParserException e) { 16980 res.setError("Failed parse during installPackageLI", e); 16981 return; 16982 } finally { 16983 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16984 } 16985 16986 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16987 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16988 Slog.w(TAG, "Instant app package " + pkg.packageName 16989 + " does not target O, this will be a fatal error."); 16990 // STOPSHIP: Make this a fatal error 16991 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16992 } 16993 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16994 Slog.w(TAG, "Instant app package " + pkg.packageName 16995 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16996 // STOPSHIP: Make this a fatal error 16997 pkg.applicationInfo.targetSandboxVersion = 2; 16998 } 16999 17000 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17001 // Static shared libraries have synthetic package names 17002 renameStaticSharedLibraryPackage(pkg); 17003 17004 // No static shared libs on external storage 17005 if (onExternal) { 17006 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 17007 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17008 "Packages declaring static-shared libs cannot be updated"); 17009 return; 17010 } 17011 } 17012 17013 // If we are installing a clustered package add results for the children 17014 if (pkg.childPackages != null) { 17015 synchronized (mPackages) { 17016 final int childCount = pkg.childPackages.size(); 17017 for (int i = 0; i < childCount; i++) { 17018 PackageParser.Package childPkg = pkg.childPackages.get(i); 17019 PackageInstalledInfo childRes = new PackageInstalledInfo(); 17020 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17021 childRes.pkg = childPkg; 17022 childRes.name = childPkg.packageName; 17023 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17024 if (childPs != null) { 17025 childRes.origUsers = childPs.queryInstalledUsers( 17026 sUserManager.getUserIds(), true); 17027 } 17028 if ((mPackages.containsKey(childPkg.packageName))) { 17029 childRes.removedInfo = new PackageRemovedInfo(this); 17030 childRes.removedInfo.removedPackage = childPkg.packageName; 17031 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17032 } 17033 if (res.addedChildPackages == null) { 17034 res.addedChildPackages = new ArrayMap<>(); 17035 } 17036 res.addedChildPackages.put(childPkg.packageName, childRes); 17037 } 17038 } 17039 } 17040 17041 // If package doesn't declare API override, mark that we have an install 17042 // time CPU ABI override. 17043 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17044 pkg.cpuAbiOverride = args.abiOverride; 17045 } 17046 17047 String pkgName = res.name = pkg.packageName; 17048 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17049 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17050 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17051 return; 17052 } 17053 } 17054 17055 try { 17056 // either use what we've been given or parse directly from the APK 17057 if (args.certificates != null) { 17058 try { 17059 PackageParser.populateCertificates(pkg, args.certificates); 17060 } catch (PackageParserException e) { 17061 // there was something wrong with the certificates we were given; 17062 // try to pull them from the APK 17063 PackageParser.collectCertificates(pkg, parseFlags); 17064 } 17065 } else { 17066 PackageParser.collectCertificates(pkg, parseFlags); 17067 } 17068 } catch (PackageParserException e) { 17069 res.setError("Failed collect during installPackageLI", e); 17070 return; 17071 } 17072 17073 // Get rid of all references to package scan path via parser. 17074 pp = null; 17075 String oldCodePath = null; 17076 boolean systemApp = false; 17077 synchronized (mPackages) { 17078 // Check if installing already existing package 17079 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17080 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17081 if (pkg.mOriginalPackages != null 17082 && pkg.mOriginalPackages.contains(oldName) 17083 && mPackages.containsKey(oldName)) { 17084 // This package is derived from an original package, 17085 // and this device has been updating from that original 17086 // name. We must continue using the original name, so 17087 // rename the new package here. 17088 pkg.setPackageName(oldName); 17089 pkgName = pkg.packageName; 17090 replace = true; 17091 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 17092 + oldName + " pkgName=" + pkgName); 17093 } else if (mPackages.containsKey(pkgName)) { 17094 // This package, under its official name, already exists 17095 // on the device; we should replace it. 17096 replace = true; 17097 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17098 } 17099 17100 // Child packages are installed through the parent package 17101 if (pkg.parentPackage != null) { 17102 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17103 "Package " + pkg.packageName + " is child of package " 17104 + pkg.parentPackage.parentPackage + ". Child packages " 17105 + "can be updated only through the parent package."); 17106 return; 17107 } 17108 17109 if (replace) { 17110 // Prevent apps opting out from runtime permissions 17111 PackageParser.Package oldPackage = mPackages.get(pkgName); 17112 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17113 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17114 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17115 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17116 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17117 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17118 + " doesn't support runtime permissions but the old" 17119 + " target SDK " + oldTargetSdk + " does."); 17120 return; 17121 } 17122 // Prevent apps from downgrading their targetSandbox. 17123 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 17124 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 17125 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 17126 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 17127 "Package " + pkg.packageName + " new target sandbox " 17128 + newTargetSandbox + " is incompatible with the previous value of" 17129 + oldTargetSandbox + "."); 17130 return; 17131 } 17132 17133 // Prevent installing of child packages 17134 if (oldPackage.parentPackage != null) { 17135 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17136 "Package " + pkg.packageName + " is child of package " 17137 + oldPackage.parentPackage + ". Child packages " 17138 + "can be updated only through the parent package."); 17139 return; 17140 } 17141 } 17142 } 17143 17144 PackageSetting ps = mSettings.mPackages.get(pkgName); 17145 if (ps != null) { 17146 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 17147 17148 // Static shared libs have same package with different versions where 17149 // we internally use a synthetic package name to allow multiple versions 17150 // of the same package, therefore we need to compare signatures against 17151 // the package setting for the latest library version. 17152 PackageSetting signatureCheckPs = ps; 17153 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17154 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17155 if (libraryEntry != null) { 17156 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17157 } 17158 } 17159 17160 // Quick sanity check that we're signed correctly if updating; 17161 // we'll check this again later when scanning, but we want to 17162 // bail early here before tripping over redefined permissions. 17163 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 17164 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 17165 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17166 + pkg.packageName + " upgrade keys do not match the " 17167 + "previously installed version"); 17168 return; 17169 } 17170 } else { 17171 try { 17172 verifySignaturesLP(signatureCheckPs, pkg); 17173 } catch (PackageManagerException e) { 17174 res.setError(e.error, e.getMessage()); 17175 return; 17176 } 17177 } 17178 17179 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17180 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17181 systemApp = (ps.pkg.applicationInfo.flags & 17182 ApplicationInfo.FLAG_SYSTEM) != 0; 17183 } 17184 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17185 } 17186 17187 int N = pkg.permissions.size(); 17188 for (int i = N-1; i >= 0; i--) { 17189 PackageParser.Permission perm = pkg.permissions.get(i); 17190 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 17191 17192 // Don't allow anyone but the platform to define ephemeral permissions. 17193 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 17194 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17195 Slog.w(TAG, "Package " + pkg.packageName 17196 + " attempting to delcare ephemeral permission " 17197 + perm.info.name + "; Removing ephemeral."); 17198 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 17199 } 17200 // Check whether the newly-scanned package wants to define an already-defined perm 17201 if (bp != null) { 17202 // If the defining package is signed with our cert, it's okay. This 17203 // also includes the "updating the same package" case, of course. 17204 // "updating same package" could also involve key-rotation. 17205 final boolean sigsOk; 17206 if (bp.sourcePackage.equals(pkg.packageName) 17207 && (bp.packageSetting instanceof PackageSetting) 17208 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 17209 scanFlags))) { 17210 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 17211 } else { 17212 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 17213 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 17214 } 17215 if (!sigsOk) { 17216 // If the owning package is the system itself, we log but allow 17217 // install to proceed; we fail the install on all other permission 17218 // redefinitions. 17219 if (!bp.sourcePackage.equals("android")) { 17220 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17221 + pkg.packageName + " attempting to redeclare permission " 17222 + perm.info.name + " already owned by " + bp.sourcePackage); 17223 res.origPermission = perm.info.name; 17224 res.origPackage = bp.sourcePackage; 17225 return; 17226 } else { 17227 Slog.w(TAG, "Package " + pkg.packageName 17228 + " attempting to redeclare system permission " 17229 + perm.info.name + "; ignoring new declaration"); 17230 pkg.permissions.remove(i); 17231 } 17232 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17233 // Prevent apps to change protection level to dangerous from any other 17234 // type as this would allow a privilege escalation where an app adds a 17235 // normal/signature permission in other app's group and later redefines 17236 // it as dangerous leading to the group auto-grant. 17237 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17238 == PermissionInfo.PROTECTION_DANGEROUS) { 17239 if (bp != null && !bp.isRuntime()) { 17240 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17241 + "non-runtime permission " + perm.info.name 17242 + " to runtime; keeping old protection level"); 17243 perm.info.protectionLevel = bp.protectionLevel; 17244 } 17245 } 17246 } 17247 } 17248 } 17249 } 17250 17251 if (systemApp) { 17252 if (onExternal) { 17253 // Abort update; system app can't be replaced with app on sdcard 17254 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17255 "Cannot install updates to system apps on sdcard"); 17256 return; 17257 } else if (instantApp) { 17258 // Abort update; system app can't be replaced with an instant app 17259 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17260 "Cannot update a system app with an instant app"); 17261 return; 17262 } 17263 } 17264 17265 if (args.move != null) { 17266 // We did an in-place move, so dex is ready to roll 17267 scanFlags |= SCAN_NO_DEX; 17268 scanFlags |= SCAN_MOVE; 17269 17270 synchronized (mPackages) { 17271 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17272 if (ps == null) { 17273 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17274 "Missing settings for moved package " + pkgName); 17275 } 17276 17277 // We moved the entire application as-is, so bring over the 17278 // previously derived ABI information. 17279 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17280 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17281 } 17282 17283 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17284 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17285 scanFlags |= SCAN_NO_DEX; 17286 17287 try { 17288 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17289 args.abiOverride : pkg.cpuAbiOverride); 17290 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 17291 true /*extractLibs*/, mAppLib32InstallDir); 17292 } catch (PackageManagerException pme) { 17293 Slog.e(TAG, "Error deriving application ABI", pme); 17294 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17295 return; 17296 } 17297 17298 // Shared libraries for the package need to be updated. 17299 synchronized (mPackages) { 17300 try { 17301 updateSharedLibrariesLPr(pkg, null); 17302 } catch (PackageManagerException e) { 17303 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17304 } 17305 } 17306 17307 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17308 // Do not run PackageDexOptimizer through the local performDexOpt 17309 // method because `pkg` may not be in `mPackages` yet. 17310 // 17311 // Also, don't fail application installs if the dexopt step fails. 17312 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17313 null /* instructionSets */, false /* checkProfiles */, 17314 getCompilerFilterForReason(REASON_INSTALL), 17315 getOrCreateCompilerPackageStats(pkg), 17316 mDexManager.isUsedByOtherApps(pkg.packageName)); 17317 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17318 17319 // Notify BackgroundDexOptService that the package has been changed. 17320 // If this is an update of a package which used to fail to compile, 17321 // BDOS will remove it from its blacklist. 17322 // TODO: Layering violation 17323 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17324 } 17325 17326 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17327 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17328 return; 17329 } 17330 17331 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17332 17333 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17334 "installPackageLI")) { 17335 if (replace) { 17336 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17337 // Static libs have a synthetic package name containing the version 17338 // and cannot be updated as an update would get a new package name, 17339 // unless this is the exact same version code which is useful for 17340 // development. 17341 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17342 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17343 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17344 + "static-shared libs cannot be updated"); 17345 return; 17346 } 17347 } 17348 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17349 installerPackageName, res, args.installReason); 17350 } else { 17351 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17352 args.user, installerPackageName, volumeUuid, res, args.installReason); 17353 } 17354 } 17355 17356 synchronized (mPackages) { 17357 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17358 if (ps != null) { 17359 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17360 ps.setUpdateAvailable(false /*updateAvailable*/); 17361 } 17362 17363 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17364 for (int i = 0; i < childCount; i++) { 17365 PackageParser.Package childPkg = pkg.childPackages.get(i); 17366 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17367 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17368 if (childPs != null) { 17369 childRes.newUsers = childPs.queryInstalledUsers( 17370 sUserManager.getUserIds(), true); 17371 } 17372 } 17373 17374 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17375 updateSequenceNumberLP(pkgName, res.newUsers); 17376 updateInstantAppInstallerLocked(pkgName); 17377 } 17378 } 17379 } 17380 17381 private void startIntentFilterVerifications(int userId, boolean replacing, 17382 PackageParser.Package pkg) { 17383 if (mIntentFilterVerifierComponent == null) { 17384 Slog.w(TAG, "No IntentFilter verification will not be done as " 17385 + "there is no IntentFilterVerifier available!"); 17386 return; 17387 } 17388 17389 final int verifierUid = getPackageUid( 17390 mIntentFilterVerifierComponent.getPackageName(), 17391 MATCH_DEBUG_TRIAGED_MISSING, 17392 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17393 17394 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17395 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17396 mHandler.sendMessage(msg); 17397 17398 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17399 for (int i = 0; i < childCount; i++) { 17400 PackageParser.Package childPkg = pkg.childPackages.get(i); 17401 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17402 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17403 mHandler.sendMessage(msg); 17404 } 17405 } 17406 17407 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17408 PackageParser.Package pkg) { 17409 int size = pkg.activities.size(); 17410 if (size == 0) { 17411 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17412 "No activity, so no need to verify any IntentFilter!"); 17413 return; 17414 } 17415 17416 final boolean hasDomainURLs = hasDomainURLs(pkg); 17417 if (!hasDomainURLs) { 17418 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17419 "No domain URLs, so no need to verify any IntentFilter!"); 17420 return; 17421 } 17422 17423 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17424 + " if any IntentFilter from the " + size 17425 + " Activities needs verification ..."); 17426 17427 int count = 0; 17428 final String packageName = pkg.packageName; 17429 17430 synchronized (mPackages) { 17431 // If this is a new install and we see that we've already run verification for this 17432 // package, we have nothing to do: it means the state was restored from backup. 17433 if (!replacing) { 17434 IntentFilterVerificationInfo ivi = 17435 mSettings.getIntentFilterVerificationLPr(packageName); 17436 if (ivi != null) { 17437 if (DEBUG_DOMAIN_VERIFICATION) { 17438 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17439 + ivi.getStatusString()); 17440 } 17441 return; 17442 } 17443 } 17444 17445 // If any filters need to be verified, then all need to be. 17446 boolean needToVerify = false; 17447 for (PackageParser.Activity a : pkg.activities) { 17448 for (ActivityIntentInfo filter : a.intents) { 17449 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17450 if (DEBUG_DOMAIN_VERIFICATION) { 17451 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17452 } 17453 needToVerify = true; 17454 break; 17455 } 17456 } 17457 } 17458 17459 if (needToVerify) { 17460 final int verificationId = mIntentFilterVerificationToken++; 17461 for (PackageParser.Activity a : pkg.activities) { 17462 for (ActivityIntentInfo filter : a.intents) { 17463 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17464 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17465 "Verification needed for IntentFilter:" + filter.toString()); 17466 mIntentFilterVerifier.addOneIntentFilterVerification( 17467 verifierUid, userId, verificationId, filter, packageName); 17468 count++; 17469 } 17470 } 17471 } 17472 } 17473 } 17474 17475 if (count > 0) { 17476 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17477 + " IntentFilter verification" + (count > 1 ? "s" : "") 17478 + " for userId:" + userId); 17479 mIntentFilterVerifier.startVerifications(userId); 17480 } else { 17481 if (DEBUG_DOMAIN_VERIFICATION) { 17482 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17483 } 17484 } 17485 } 17486 17487 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17488 final ComponentName cn = filter.activity.getComponentName(); 17489 final String packageName = cn.getPackageName(); 17490 17491 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17492 packageName); 17493 if (ivi == null) { 17494 return true; 17495 } 17496 int status = ivi.getStatus(); 17497 switch (status) { 17498 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17499 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17500 return true; 17501 17502 default: 17503 // Nothing to do 17504 return false; 17505 } 17506 } 17507 17508 private static boolean isMultiArch(ApplicationInfo info) { 17509 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17510 } 17511 17512 private static boolean isExternal(PackageParser.Package pkg) { 17513 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17514 } 17515 17516 private static boolean isExternal(PackageSetting ps) { 17517 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17518 } 17519 17520 private static boolean isSystemApp(PackageParser.Package pkg) { 17521 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17522 } 17523 17524 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17525 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17526 } 17527 17528 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17529 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17530 } 17531 17532 private static boolean isSystemApp(PackageSetting ps) { 17533 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17534 } 17535 17536 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17537 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17538 } 17539 17540 private int packageFlagsToInstallFlags(PackageSetting ps) { 17541 int installFlags = 0; 17542 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17543 // This existing package was an external ASEC install when we have 17544 // the external flag without a UUID 17545 installFlags |= PackageManager.INSTALL_EXTERNAL; 17546 } 17547 if (ps.isForwardLocked()) { 17548 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17549 } 17550 return installFlags; 17551 } 17552 17553 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17554 if (isExternal(pkg)) { 17555 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17556 return StorageManager.UUID_PRIMARY_PHYSICAL; 17557 } else { 17558 return pkg.volumeUuid; 17559 } 17560 } else { 17561 return StorageManager.UUID_PRIVATE_INTERNAL; 17562 } 17563 } 17564 17565 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17566 if (isExternal(pkg)) { 17567 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17568 return mSettings.getExternalVersion(); 17569 } else { 17570 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17571 } 17572 } else { 17573 return mSettings.getInternalVersion(); 17574 } 17575 } 17576 17577 private void deleteTempPackageFiles() { 17578 final FilenameFilter filter = new FilenameFilter() { 17579 public boolean accept(File dir, String name) { 17580 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17581 } 17582 }; 17583 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17584 file.delete(); 17585 } 17586 } 17587 17588 @Override 17589 public void deletePackageAsUser(String packageName, int versionCode, 17590 IPackageDeleteObserver observer, int userId, int flags) { 17591 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17592 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17593 } 17594 17595 @Override 17596 public void deletePackageVersioned(VersionedPackage versionedPackage, 17597 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17598 mContext.enforceCallingOrSelfPermission( 17599 android.Manifest.permission.DELETE_PACKAGES, null); 17600 Preconditions.checkNotNull(versionedPackage); 17601 Preconditions.checkNotNull(observer); 17602 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17603 PackageManager.VERSION_CODE_HIGHEST, 17604 Integer.MAX_VALUE, "versionCode must be >= -1"); 17605 17606 final String packageName = versionedPackage.getPackageName(); 17607 // TODO: We will change version code to long, so in the new API it is long 17608 final int versionCode = (int) versionedPackage.getVersionCode(); 17609 final String internalPackageName; 17610 synchronized (mPackages) { 17611 // Normalize package name to handle renamed packages and static libs 17612 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17613 // TODO: We will change version code to long, so in the new API it is long 17614 (int) versionedPackage.getVersionCode()); 17615 } 17616 17617 final int uid = Binder.getCallingUid(); 17618 if (!isOrphaned(internalPackageName) 17619 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17620 try { 17621 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17622 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17623 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17624 observer.onUserActionRequired(intent); 17625 } catch (RemoteException re) { 17626 } 17627 return; 17628 } 17629 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17630 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17631 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17632 mContext.enforceCallingOrSelfPermission( 17633 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17634 "deletePackage for user " + userId); 17635 } 17636 17637 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17638 try { 17639 observer.onPackageDeleted(packageName, 17640 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17641 } catch (RemoteException re) { 17642 } 17643 return; 17644 } 17645 17646 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17647 try { 17648 observer.onPackageDeleted(packageName, 17649 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17650 } catch (RemoteException re) { 17651 } 17652 return; 17653 } 17654 17655 if (DEBUG_REMOVE) { 17656 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17657 + " deleteAllUsers: " + deleteAllUsers + " version=" 17658 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17659 ? "VERSION_CODE_HIGHEST" : versionCode)); 17660 } 17661 // Queue up an async operation since the package deletion may take a little while. 17662 mHandler.post(new Runnable() { 17663 public void run() { 17664 mHandler.removeCallbacks(this); 17665 int returnCode; 17666 if (!deleteAllUsers) { 17667 returnCode = deletePackageX(internalPackageName, versionCode, 17668 userId, deleteFlags); 17669 } else { 17670 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17671 internalPackageName, users); 17672 // If nobody is blocking uninstall, proceed with delete for all users 17673 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17674 returnCode = deletePackageX(internalPackageName, versionCode, 17675 userId, deleteFlags); 17676 } else { 17677 // Otherwise uninstall individually for users with blockUninstalls=false 17678 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17679 for (int userId : users) { 17680 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17681 returnCode = deletePackageX(internalPackageName, versionCode, 17682 userId, userFlags); 17683 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17684 Slog.w(TAG, "Package delete failed for user " + userId 17685 + ", returnCode " + returnCode); 17686 } 17687 } 17688 } 17689 // The app has only been marked uninstalled for certain users. 17690 // We still need to report that delete was blocked 17691 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17692 } 17693 } 17694 try { 17695 observer.onPackageDeleted(packageName, returnCode, null); 17696 } catch (RemoteException e) { 17697 Log.i(TAG, "Observer no longer exists."); 17698 } //end catch 17699 } //end run 17700 }); 17701 } 17702 17703 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17704 if (pkg.staticSharedLibName != null) { 17705 return pkg.manifestPackageName; 17706 } 17707 return pkg.packageName; 17708 } 17709 17710 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17711 // Handle renamed packages 17712 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17713 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17714 17715 // Is this a static library? 17716 SparseArray<SharedLibraryEntry> versionedLib = 17717 mStaticLibsByDeclaringPackage.get(packageName); 17718 if (versionedLib == null || versionedLib.size() <= 0) { 17719 return packageName; 17720 } 17721 17722 // Figure out which lib versions the caller can see 17723 SparseIntArray versionsCallerCanSee = null; 17724 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17725 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17726 && callingAppId != Process.ROOT_UID) { 17727 versionsCallerCanSee = new SparseIntArray(); 17728 String libName = versionedLib.valueAt(0).info.getName(); 17729 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17730 if (uidPackages != null) { 17731 for (String uidPackage : uidPackages) { 17732 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17733 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17734 if (libIdx >= 0) { 17735 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17736 versionsCallerCanSee.append(libVersion, libVersion); 17737 } 17738 } 17739 } 17740 } 17741 17742 // Caller can see nothing - done 17743 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17744 return packageName; 17745 } 17746 17747 // Find the version the caller can see and the app version code 17748 SharedLibraryEntry highestVersion = null; 17749 final int versionCount = versionedLib.size(); 17750 for (int i = 0; i < versionCount; i++) { 17751 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17752 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17753 // TODO: Remove cast for lib version once internally we support longs. 17754 (int) libEntry.info.getVersion()) < 0) { 17755 continue; 17756 } 17757 // TODO: We will change version code to long, so in the new API it is long 17758 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17759 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17760 if (libVersionCode == versionCode) { 17761 return libEntry.apk; 17762 } 17763 } else if (highestVersion == null) { 17764 highestVersion = libEntry; 17765 } else if (libVersionCode > highestVersion.info 17766 .getDeclaringPackage().getVersionCode()) { 17767 highestVersion = libEntry; 17768 } 17769 } 17770 17771 if (highestVersion != null) { 17772 return highestVersion.apk; 17773 } 17774 17775 return packageName; 17776 } 17777 17778 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17779 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17780 || callingUid == Process.SYSTEM_UID) { 17781 return true; 17782 } 17783 final int callingUserId = UserHandle.getUserId(callingUid); 17784 // If the caller installed the pkgName, then allow it to silently uninstall. 17785 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17786 return true; 17787 } 17788 17789 // Allow package verifier to silently uninstall. 17790 if (mRequiredVerifierPackage != null && 17791 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17792 return true; 17793 } 17794 17795 // Allow package uninstaller to silently uninstall. 17796 if (mRequiredUninstallerPackage != null && 17797 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17798 return true; 17799 } 17800 17801 // Allow storage manager to silently uninstall. 17802 if (mStorageManagerPackage != null && 17803 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17804 return true; 17805 } 17806 return false; 17807 } 17808 17809 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17810 int[] result = EMPTY_INT_ARRAY; 17811 for (int userId : userIds) { 17812 if (getBlockUninstallForUser(packageName, userId)) { 17813 result = ArrayUtils.appendInt(result, userId); 17814 } 17815 } 17816 return result; 17817 } 17818 17819 @Override 17820 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17821 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17822 } 17823 17824 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17825 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17826 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17827 try { 17828 if (dpm != null) { 17829 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17830 /* callingUserOnly =*/ false); 17831 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17832 : deviceOwnerComponentName.getPackageName(); 17833 // Does the package contains the device owner? 17834 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17835 // this check is probably not needed, since DO should be registered as a device 17836 // admin on some user too. (Original bug for this: b/17657954) 17837 if (packageName.equals(deviceOwnerPackageName)) { 17838 return true; 17839 } 17840 // Does it contain a device admin for any user? 17841 int[] users; 17842 if (userId == UserHandle.USER_ALL) { 17843 users = sUserManager.getUserIds(); 17844 } else { 17845 users = new int[]{userId}; 17846 } 17847 for (int i = 0; i < users.length; ++i) { 17848 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17849 return true; 17850 } 17851 } 17852 } 17853 } catch (RemoteException e) { 17854 } 17855 return false; 17856 } 17857 17858 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17859 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17860 } 17861 17862 /** 17863 * This method is an internal method that could be get invoked either 17864 * to delete an installed package or to clean up a failed installation. 17865 * After deleting an installed package, a broadcast is sent to notify any 17866 * listeners that the package has been removed. For cleaning up a failed 17867 * installation, the broadcast is not necessary since the package's 17868 * installation wouldn't have sent the initial broadcast either 17869 * The key steps in deleting a package are 17870 * deleting the package information in internal structures like mPackages, 17871 * deleting the packages base directories through installd 17872 * updating mSettings to reflect current status 17873 * persisting settings for later use 17874 * sending a broadcast if necessary 17875 */ 17876 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17877 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17878 final boolean res; 17879 17880 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17881 ? UserHandle.USER_ALL : userId; 17882 17883 if (isPackageDeviceAdmin(packageName, removeUser)) { 17884 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17885 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17886 } 17887 17888 PackageSetting uninstalledPs = null; 17889 PackageParser.Package pkg = null; 17890 17891 // for the uninstall-updates case and restricted profiles, remember the per- 17892 // user handle installed state 17893 int[] allUsers; 17894 synchronized (mPackages) { 17895 uninstalledPs = mSettings.mPackages.get(packageName); 17896 if (uninstalledPs == null) { 17897 Slog.w(TAG, "Not removing non-existent package " + packageName); 17898 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17899 } 17900 17901 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17902 && uninstalledPs.versionCode != versionCode) { 17903 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17904 + uninstalledPs.versionCode + " != " + versionCode); 17905 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17906 } 17907 17908 // Static shared libs can be declared by any package, so let us not 17909 // allow removing a package if it provides a lib others depend on. 17910 pkg = mPackages.get(packageName); 17911 if (pkg != null && pkg.staticSharedLibName != null) { 17912 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17913 pkg.staticSharedLibVersion); 17914 if (libEntry != null) { 17915 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17916 libEntry.info, 0, userId); 17917 if (!ArrayUtils.isEmpty(libClientPackages)) { 17918 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17919 + " hosting lib " + libEntry.info.getName() + " version " 17920 + libEntry.info.getVersion() + " used by " + libClientPackages); 17921 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17922 } 17923 } 17924 } 17925 17926 allUsers = sUserManager.getUserIds(); 17927 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17928 } 17929 17930 final int freezeUser; 17931 if (isUpdatedSystemApp(uninstalledPs) 17932 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17933 // We're downgrading a system app, which will apply to all users, so 17934 // freeze them all during the downgrade 17935 freezeUser = UserHandle.USER_ALL; 17936 } else { 17937 freezeUser = removeUser; 17938 } 17939 17940 synchronized (mInstallLock) { 17941 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17942 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17943 deleteFlags, "deletePackageX")) { 17944 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17945 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17946 } 17947 synchronized (mPackages) { 17948 if (res) { 17949 if (pkg != null) { 17950 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17951 } 17952 updateSequenceNumberLP(packageName, info.removedUsers); 17953 updateInstantAppInstallerLocked(packageName); 17954 } 17955 } 17956 } 17957 17958 if (res) { 17959 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17960 info.sendPackageRemovedBroadcasts(killApp); 17961 info.sendSystemPackageUpdatedBroadcasts(); 17962 info.sendSystemPackageAppearedBroadcasts(); 17963 } 17964 // Force a gc here. 17965 Runtime.getRuntime().gc(); 17966 // Delete the resources here after sending the broadcast to let 17967 // other processes clean up before deleting resources. 17968 if (info.args != null) { 17969 synchronized (mInstallLock) { 17970 info.args.doPostDeleteLI(true); 17971 } 17972 } 17973 17974 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17975 } 17976 17977 static class PackageRemovedInfo { 17978 final PackageSender packageSender; 17979 String removedPackage; 17980 String installerPackageName; 17981 int uid = -1; 17982 int removedAppId = -1; 17983 int[] origUsers; 17984 int[] removedUsers = null; 17985 int[] broadcastUsers = null; 17986 SparseArray<Integer> installReasons; 17987 boolean isRemovedPackageSystemUpdate = false; 17988 boolean isUpdate; 17989 boolean dataRemoved; 17990 boolean removedForAllUsers; 17991 boolean isStaticSharedLib; 17992 // Clean up resources deleted packages. 17993 InstallArgs args = null; 17994 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17995 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17996 17997 PackageRemovedInfo(PackageSender packageSender) { 17998 this.packageSender = packageSender; 17999 } 18000 18001 void sendPackageRemovedBroadcasts(boolean killApp) { 18002 sendPackageRemovedBroadcastInternal(killApp); 18003 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18004 for (int i = 0; i < childCount; i++) { 18005 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18006 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18007 } 18008 } 18009 18010 void sendSystemPackageUpdatedBroadcasts() { 18011 if (isRemovedPackageSystemUpdate) { 18012 sendSystemPackageUpdatedBroadcastsInternal(); 18013 final int childCount = (removedChildPackages != null) 18014 ? removedChildPackages.size() : 0; 18015 for (int i = 0; i < childCount; i++) { 18016 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18017 if (childInfo.isRemovedPackageSystemUpdate) { 18018 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18019 } 18020 } 18021 } 18022 } 18023 18024 void sendSystemPackageAppearedBroadcasts() { 18025 final int packageCount = (appearedChildPackages != null) 18026 ? appearedChildPackages.size() : 0; 18027 for (int i = 0; i < packageCount; i++) { 18028 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18029 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18030 true, UserHandle.getAppId(installedInfo.uid), 18031 installedInfo.newUsers); 18032 } 18033 } 18034 18035 private void sendSystemPackageUpdatedBroadcastsInternal() { 18036 Bundle extras = new Bundle(2); 18037 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18038 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18039 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18040 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18041 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18042 removedPackage, extras, 0, null /*targetPackage*/, null, null); 18043 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18044 null, null, 0, removedPackage, null, null); 18045 if (installerPackageName != null) { 18046 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18047 removedPackage, extras, 0 /*flags*/, 18048 installerPackageName, null, null); 18049 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18050 removedPackage, extras, 0 /*flags*/, 18051 installerPackageName, null, null); 18052 } 18053 } 18054 18055 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18056 // Don't send static shared library removal broadcasts as these 18057 // libs are visible only the the apps that depend on them an one 18058 // cannot remove the library if it has a dependency. 18059 if (isStaticSharedLib) { 18060 return; 18061 } 18062 Bundle extras = new Bundle(2); 18063 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18064 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18065 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18066 if (isUpdate || isRemovedPackageSystemUpdate) { 18067 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18068 } 18069 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18070 if (removedPackage != null) { 18071 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18072 removedPackage, extras, 0, null /*targetPackage*/, null, broadcastUsers); 18073 if (installerPackageName != null) { 18074 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18075 removedPackage, extras, 0 /*flags*/, 18076 installerPackageName, null, broadcastUsers); 18077 } 18078 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18079 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18080 removedPackage, extras, 18081 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18082 null, null, broadcastUsers); 18083 } 18084 } 18085 if (removedAppId >= 0) { 18086 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 18087 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, null, null, broadcastUsers); 18088 } 18089 } 18090 18091 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18092 removedUsers = userIds; 18093 if (removedUsers == null) { 18094 broadcastUsers = null; 18095 return; 18096 } 18097 18098 broadcastUsers = EMPTY_INT_ARRAY; 18099 for (int i = userIds.length - 1; i >= 0; --i) { 18100 final int userId = userIds[i]; 18101 if (deletedPackageSetting.getInstantApp(userId)) { 18102 continue; 18103 } 18104 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18105 } 18106 } 18107 } 18108 18109 /* 18110 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18111 * flag is not set, the data directory is removed as well. 18112 * make sure this flag is set for partially installed apps. If not its meaningless to 18113 * delete a partially installed application. 18114 */ 18115 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18116 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18117 String packageName = ps.name; 18118 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18119 // Retrieve object to delete permissions for shared user later on 18120 final PackageParser.Package deletedPkg; 18121 final PackageSetting deletedPs; 18122 // reader 18123 synchronized (mPackages) { 18124 deletedPkg = mPackages.get(packageName); 18125 deletedPs = mSettings.mPackages.get(packageName); 18126 if (outInfo != null) { 18127 outInfo.removedPackage = packageName; 18128 outInfo.installerPackageName = ps.installerPackageName; 18129 outInfo.isStaticSharedLib = deletedPkg != null 18130 && deletedPkg.staticSharedLibName != null; 18131 outInfo.populateUsers(deletedPs == null ? null 18132 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18133 } 18134 } 18135 18136 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 18137 18138 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18139 final PackageParser.Package resolvedPkg; 18140 if (deletedPkg != null) { 18141 resolvedPkg = deletedPkg; 18142 } else { 18143 // We don't have a parsed package when it lives on an ejected 18144 // adopted storage device, so fake something together 18145 resolvedPkg = new PackageParser.Package(ps.name); 18146 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18147 } 18148 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18149 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18150 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18151 if (outInfo != null) { 18152 outInfo.dataRemoved = true; 18153 } 18154 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18155 } 18156 18157 int removedAppId = -1; 18158 18159 // writer 18160 synchronized (mPackages) { 18161 boolean installedStateChanged = false; 18162 if (deletedPs != null) { 18163 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18164 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18165 clearDefaultBrowserIfNeeded(packageName); 18166 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18167 removedAppId = mSettings.removePackageLPw(packageName); 18168 if (outInfo != null) { 18169 outInfo.removedAppId = removedAppId; 18170 } 18171 updatePermissionsLPw(deletedPs.name, null, 0); 18172 if (deletedPs.sharedUser != null) { 18173 // Remove permissions associated with package. Since runtime 18174 // permissions are per user we have to kill the removed package 18175 // or packages running under the shared user of the removed 18176 // package if revoking the permissions requested only by the removed 18177 // package is successful and this causes a change in gids. 18178 for (int userId : UserManagerService.getInstance().getUserIds()) { 18179 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18180 userId); 18181 if (userIdToKill == UserHandle.USER_ALL 18182 || userIdToKill >= UserHandle.USER_SYSTEM) { 18183 // If gids changed for this user, kill all affected packages. 18184 mHandler.post(new Runnable() { 18185 @Override 18186 public void run() { 18187 // This has to happen with no lock held. 18188 killApplication(deletedPs.name, deletedPs.appId, 18189 KILL_APP_REASON_GIDS_CHANGED); 18190 } 18191 }); 18192 break; 18193 } 18194 } 18195 } 18196 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18197 } 18198 // make sure to preserve per-user disabled state if this removal was just 18199 // a downgrade of a system app to the factory package 18200 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18201 if (DEBUG_REMOVE) { 18202 Slog.d(TAG, "Propagating install state across downgrade"); 18203 } 18204 for (int userId : allUserHandles) { 18205 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18206 if (DEBUG_REMOVE) { 18207 Slog.d(TAG, " user " + userId + " => " + installed); 18208 } 18209 if (installed != ps.getInstalled(userId)) { 18210 installedStateChanged = true; 18211 } 18212 ps.setInstalled(installed, userId); 18213 } 18214 } 18215 } 18216 // can downgrade to reader 18217 if (writeSettings) { 18218 // Save settings now 18219 mSettings.writeLPr(); 18220 } 18221 if (installedStateChanged) { 18222 mSettings.writeKernelMappingLPr(ps); 18223 } 18224 } 18225 if (removedAppId != -1) { 18226 // A user ID was deleted here. Go through all users and remove it 18227 // from KeyStore. 18228 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18229 } 18230 } 18231 18232 static boolean locationIsPrivileged(File path) { 18233 try { 18234 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 18235 .getCanonicalPath(); 18236 return path.getCanonicalPath().startsWith(privilegedAppDir); 18237 } catch (IOException e) { 18238 Slog.e(TAG, "Unable to access code path " + path); 18239 } 18240 return false; 18241 } 18242 18243 /* 18244 * Tries to delete system package. 18245 */ 18246 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18247 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18248 boolean writeSettings) { 18249 if (deletedPs.parentPackageName != null) { 18250 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18251 return false; 18252 } 18253 18254 final boolean applyUserRestrictions 18255 = (allUserHandles != null) && (outInfo.origUsers != null); 18256 final PackageSetting disabledPs; 18257 // Confirm if the system package has been updated 18258 // An updated system app can be deleted. This will also have to restore 18259 // the system pkg from system partition 18260 // reader 18261 synchronized (mPackages) { 18262 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18263 } 18264 18265 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18266 + " disabledPs=" + disabledPs); 18267 18268 if (disabledPs == null) { 18269 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18270 return false; 18271 } else if (DEBUG_REMOVE) { 18272 Slog.d(TAG, "Deleting system pkg from data partition"); 18273 } 18274 18275 if (DEBUG_REMOVE) { 18276 if (applyUserRestrictions) { 18277 Slog.d(TAG, "Remembering install states:"); 18278 for (int userId : allUserHandles) { 18279 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18280 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18281 } 18282 } 18283 } 18284 18285 // Delete the updated package 18286 outInfo.isRemovedPackageSystemUpdate = true; 18287 if (outInfo.removedChildPackages != null) { 18288 final int childCount = (deletedPs.childPackageNames != null) 18289 ? deletedPs.childPackageNames.size() : 0; 18290 for (int i = 0; i < childCount; i++) { 18291 String childPackageName = deletedPs.childPackageNames.get(i); 18292 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18293 .contains(childPackageName)) { 18294 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18295 childPackageName); 18296 if (childInfo != null) { 18297 childInfo.isRemovedPackageSystemUpdate = true; 18298 } 18299 } 18300 } 18301 } 18302 18303 if (disabledPs.versionCode < deletedPs.versionCode) { 18304 // Delete data for downgrades 18305 flags &= ~PackageManager.DELETE_KEEP_DATA; 18306 } else { 18307 // Preserve data by setting flag 18308 flags |= PackageManager.DELETE_KEEP_DATA; 18309 } 18310 18311 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18312 outInfo, writeSettings, disabledPs.pkg); 18313 if (!ret) { 18314 return false; 18315 } 18316 18317 // writer 18318 synchronized (mPackages) { 18319 // Reinstate the old system package 18320 enableSystemPackageLPw(disabledPs.pkg); 18321 // Remove any native libraries from the upgraded package. 18322 removeNativeBinariesLI(deletedPs); 18323 } 18324 18325 // Install the system package 18326 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18327 int parseFlags = mDefParseFlags 18328 | PackageParser.PARSE_MUST_BE_APK 18329 | PackageParser.PARSE_IS_SYSTEM 18330 | PackageParser.PARSE_IS_SYSTEM_DIR; 18331 if (locationIsPrivileged(disabledPs.codePath)) { 18332 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18333 } 18334 18335 final PackageParser.Package newPkg; 18336 try { 18337 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18338 0 /* currentTime */, null); 18339 } catch (PackageManagerException e) { 18340 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18341 + e.getMessage()); 18342 return false; 18343 } 18344 18345 try { 18346 // update shared libraries for the newly re-installed system package 18347 updateSharedLibrariesLPr(newPkg, null); 18348 } catch (PackageManagerException e) { 18349 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18350 } 18351 18352 prepareAppDataAfterInstallLIF(newPkg); 18353 18354 // writer 18355 synchronized (mPackages) { 18356 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18357 18358 // Propagate the permissions state as we do not want to drop on the floor 18359 // runtime permissions. The update permissions method below will take 18360 // care of removing obsolete permissions and grant install permissions. 18361 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18362 updatePermissionsLPw(newPkg.packageName, newPkg, 18363 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18364 18365 if (applyUserRestrictions) { 18366 boolean installedStateChanged = false; 18367 if (DEBUG_REMOVE) { 18368 Slog.d(TAG, "Propagating install state across reinstall"); 18369 } 18370 for (int userId : allUserHandles) { 18371 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18372 if (DEBUG_REMOVE) { 18373 Slog.d(TAG, " user " + userId + " => " + installed); 18374 } 18375 if (installed != ps.getInstalled(userId)) { 18376 installedStateChanged = true; 18377 } 18378 ps.setInstalled(installed, userId); 18379 18380 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18381 } 18382 // Regardless of writeSettings we need to ensure that this restriction 18383 // state propagation is persisted 18384 mSettings.writeAllUsersPackageRestrictionsLPr(); 18385 if (installedStateChanged) { 18386 mSettings.writeKernelMappingLPr(ps); 18387 } 18388 } 18389 // can downgrade to reader here 18390 if (writeSettings) { 18391 mSettings.writeLPr(); 18392 } 18393 } 18394 return true; 18395 } 18396 18397 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18398 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18399 PackageRemovedInfo outInfo, boolean writeSettings, 18400 PackageParser.Package replacingPackage) { 18401 synchronized (mPackages) { 18402 if (outInfo != null) { 18403 outInfo.uid = ps.appId; 18404 } 18405 18406 if (outInfo != null && outInfo.removedChildPackages != null) { 18407 final int childCount = (ps.childPackageNames != null) 18408 ? ps.childPackageNames.size() : 0; 18409 for (int i = 0; i < childCount; i++) { 18410 String childPackageName = ps.childPackageNames.get(i); 18411 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18412 if (childPs == null) { 18413 return false; 18414 } 18415 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18416 childPackageName); 18417 if (childInfo != null) { 18418 childInfo.uid = childPs.appId; 18419 } 18420 } 18421 } 18422 } 18423 18424 // Delete package data from internal structures and also remove data if flag is set 18425 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18426 18427 // Delete the child packages data 18428 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18429 for (int i = 0; i < childCount; i++) { 18430 PackageSetting childPs; 18431 synchronized (mPackages) { 18432 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18433 } 18434 if (childPs != null) { 18435 PackageRemovedInfo childOutInfo = (outInfo != null 18436 && outInfo.removedChildPackages != null) 18437 ? outInfo.removedChildPackages.get(childPs.name) : null; 18438 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18439 && (replacingPackage != null 18440 && !replacingPackage.hasChildPackage(childPs.name)) 18441 ? flags & ~DELETE_KEEP_DATA : flags; 18442 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18443 deleteFlags, writeSettings); 18444 } 18445 } 18446 18447 // Delete application code and resources only for parent packages 18448 if (ps.parentPackageName == null) { 18449 if (deleteCodeAndResources && (outInfo != null)) { 18450 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18451 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18452 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18453 } 18454 } 18455 18456 return true; 18457 } 18458 18459 @Override 18460 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18461 int userId) { 18462 mContext.enforceCallingOrSelfPermission( 18463 android.Manifest.permission.DELETE_PACKAGES, null); 18464 synchronized (mPackages) { 18465 PackageSetting ps = mSettings.mPackages.get(packageName); 18466 if (ps == null) { 18467 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18468 return false; 18469 } 18470 // Cannot block uninstall of static shared libs as they are 18471 // considered a part of the using app (emulating static linking). 18472 // Also static libs are installed always on internal storage. 18473 PackageParser.Package pkg = mPackages.get(packageName); 18474 if (pkg != null && pkg.staticSharedLibName != null) { 18475 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18476 + " providing static shared library: " + pkg.staticSharedLibName); 18477 return false; 18478 } 18479 if (!ps.getInstalled(userId)) { 18480 // Can't block uninstall for an app that is not installed or enabled. 18481 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18482 return false; 18483 } 18484 ps.setBlockUninstall(blockUninstall, userId); 18485 mSettings.writePackageRestrictionsLPr(userId); 18486 } 18487 return true; 18488 } 18489 18490 @Override 18491 public boolean getBlockUninstallForUser(String packageName, int userId) { 18492 synchronized (mPackages) { 18493 PackageSetting ps = mSettings.mPackages.get(packageName); 18494 if (ps == null) { 18495 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18496 return false; 18497 } 18498 return ps.getBlockUninstall(userId); 18499 } 18500 } 18501 18502 @Override 18503 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18504 int callingUid = Binder.getCallingUid(); 18505 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18506 throw new SecurityException( 18507 "setRequiredForSystemUser can only be run by the system or root"); 18508 } 18509 synchronized (mPackages) { 18510 PackageSetting ps = mSettings.mPackages.get(packageName); 18511 if (ps == null) { 18512 Log.w(TAG, "Package doesn't exist: " + packageName); 18513 return false; 18514 } 18515 if (systemUserApp) { 18516 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18517 } else { 18518 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18519 } 18520 mSettings.writeLPr(); 18521 } 18522 return true; 18523 } 18524 18525 /* 18526 * This method handles package deletion in general 18527 */ 18528 private boolean deletePackageLIF(String packageName, UserHandle user, 18529 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18530 PackageRemovedInfo outInfo, boolean writeSettings, 18531 PackageParser.Package replacingPackage) { 18532 if (packageName == null) { 18533 Slog.w(TAG, "Attempt to delete null packageName."); 18534 return false; 18535 } 18536 18537 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18538 18539 PackageSetting ps; 18540 synchronized (mPackages) { 18541 ps = mSettings.mPackages.get(packageName); 18542 if (ps == null) { 18543 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18544 return false; 18545 } 18546 18547 if (ps.parentPackageName != null && (!isSystemApp(ps) 18548 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18549 if (DEBUG_REMOVE) { 18550 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18551 + ((user == null) ? UserHandle.USER_ALL : user)); 18552 } 18553 final int removedUserId = (user != null) ? user.getIdentifier() 18554 : UserHandle.USER_ALL; 18555 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18556 return false; 18557 } 18558 markPackageUninstalledForUserLPw(ps, user); 18559 scheduleWritePackageRestrictionsLocked(user); 18560 return true; 18561 } 18562 } 18563 18564 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18565 && user.getIdentifier() != UserHandle.USER_ALL)) { 18566 // The caller is asking that the package only be deleted for a single 18567 // user. To do this, we just mark its uninstalled state and delete 18568 // its data. If this is a system app, we only allow this to happen if 18569 // they have set the special DELETE_SYSTEM_APP which requests different 18570 // semantics than normal for uninstalling system apps. 18571 markPackageUninstalledForUserLPw(ps, user); 18572 18573 if (!isSystemApp(ps)) { 18574 // Do not uninstall the APK if an app should be cached 18575 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18576 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18577 // Other user still have this package installed, so all 18578 // we need to do is clear this user's data and save that 18579 // it is uninstalled. 18580 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18581 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18582 return false; 18583 } 18584 scheduleWritePackageRestrictionsLocked(user); 18585 return true; 18586 } else { 18587 // We need to set it back to 'installed' so the uninstall 18588 // broadcasts will be sent correctly. 18589 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18590 ps.setInstalled(true, user.getIdentifier()); 18591 mSettings.writeKernelMappingLPr(ps); 18592 } 18593 } else { 18594 // This is a system app, so we assume that the 18595 // other users still have this package installed, so all 18596 // we need to do is clear this user's data and save that 18597 // it is uninstalled. 18598 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18599 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18600 return false; 18601 } 18602 scheduleWritePackageRestrictionsLocked(user); 18603 return true; 18604 } 18605 } 18606 18607 // If we are deleting a composite package for all users, keep track 18608 // of result for each child. 18609 if (ps.childPackageNames != null && outInfo != null) { 18610 synchronized (mPackages) { 18611 final int childCount = ps.childPackageNames.size(); 18612 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18613 for (int i = 0; i < childCount; i++) { 18614 String childPackageName = ps.childPackageNames.get(i); 18615 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18616 childInfo.removedPackage = childPackageName; 18617 childInfo.installerPackageName = ps.installerPackageName; 18618 outInfo.removedChildPackages.put(childPackageName, childInfo); 18619 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18620 if (childPs != null) { 18621 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18622 } 18623 } 18624 } 18625 } 18626 18627 boolean ret = false; 18628 if (isSystemApp(ps)) { 18629 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18630 // When an updated system application is deleted we delete the existing resources 18631 // as well and fall back to existing code in system partition 18632 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18633 } else { 18634 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18635 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18636 outInfo, writeSettings, replacingPackage); 18637 } 18638 18639 // Take a note whether we deleted the package for all users 18640 if (outInfo != null) { 18641 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18642 if (outInfo.removedChildPackages != null) { 18643 synchronized (mPackages) { 18644 final int childCount = outInfo.removedChildPackages.size(); 18645 for (int i = 0; i < childCount; i++) { 18646 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18647 if (childInfo != null) { 18648 childInfo.removedForAllUsers = mPackages.get( 18649 childInfo.removedPackage) == null; 18650 } 18651 } 18652 } 18653 } 18654 // If we uninstalled an update to a system app there may be some 18655 // child packages that appeared as they are declared in the system 18656 // app but were not declared in the update. 18657 if (isSystemApp(ps)) { 18658 synchronized (mPackages) { 18659 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18660 final int childCount = (updatedPs.childPackageNames != null) 18661 ? updatedPs.childPackageNames.size() : 0; 18662 for (int i = 0; i < childCount; i++) { 18663 String childPackageName = updatedPs.childPackageNames.get(i); 18664 if (outInfo.removedChildPackages == null 18665 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18666 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18667 if (childPs == null) { 18668 continue; 18669 } 18670 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18671 installRes.name = childPackageName; 18672 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18673 installRes.pkg = mPackages.get(childPackageName); 18674 installRes.uid = childPs.pkg.applicationInfo.uid; 18675 if (outInfo.appearedChildPackages == null) { 18676 outInfo.appearedChildPackages = new ArrayMap<>(); 18677 } 18678 outInfo.appearedChildPackages.put(childPackageName, installRes); 18679 } 18680 } 18681 } 18682 } 18683 } 18684 18685 return ret; 18686 } 18687 18688 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18689 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18690 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18691 for (int nextUserId : userIds) { 18692 if (DEBUG_REMOVE) { 18693 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18694 } 18695 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18696 false /*installed*/, 18697 true /*stopped*/, 18698 true /*notLaunched*/, 18699 false /*hidden*/, 18700 false /*suspended*/, 18701 false /*instantApp*/, 18702 null /*lastDisableAppCaller*/, 18703 null /*enabledComponents*/, 18704 null /*disabledComponents*/, 18705 false /*blockUninstall*/, 18706 ps.readUserState(nextUserId).domainVerificationStatus, 18707 0, PackageManager.INSTALL_REASON_UNKNOWN); 18708 } 18709 mSettings.writeKernelMappingLPr(ps); 18710 } 18711 18712 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18713 PackageRemovedInfo outInfo) { 18714 final PackageParser.Package pkg; 18715 synchronized (mPackages) { 18716 pkg = mPackages.get(ps.name); 18717 } 18718 18719 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18720 : new int[] {userId}; 18721 for (int nextUserId : userIds) { 18722 if (DEBUG_REMOVE) { 18723 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18724 + nextUserId); 18725 } 18726 18727 destroyAppDataLIF(pkg, userId, 18728 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18729 destroyAppProfilesLIF(pkg, userId); 18730 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18731 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18732 schedulePackageCleaning(ps.name, nextUserId, false); 18733 synchronized (mPackages) { 18734 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18735 scheduleWritePackageRestrictionsLocked(nextUserId); 18736 } 18737 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18738 } 18739 } 18740 18741 if (outInfo != null) { 18742 outInfo.removedPackage = ps.name; 18743 outInfo.installerPackageName = ps.installerPackageName; 18744 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18745 outInfo.removedAppId = ps.appId; 18746 outInfo.removedUsers = userIds; 18747 outInfo.broadcastUsers = userIds; 18748 } 18749 18750 return true; 18751 } 18752 18753 private final class ClearStorageConnection implements ServiceConnection { 18754 IMediaContainerService mContainerService; 18755 18756 @Override 18757 public void onServiceConnected(ComponentName name, IBinder service) { 18758 synchronized (this) { 18759 mContainerService = IMediaContainerService.Stub 18760 .asInterface(Binder.allowBlocking(service)); 18761 notifyAll(); 18762 } 18763 } 18764 18765 @Override 18766 public void onServiceDisconnected(ComponentName name) { 18767 } 18768 } 18769 18770 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18771 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18772 18773 final boolean mounted; 18774 if (Environment.isExternalStorageEmulated()) { 18775 mounted = true; 18776 } else { 18777 final String status = Environment.getExternalStorageState(); 18778 18779 mounted = status.equals(Environment.MEDIA_MOUNTED) 18780 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18781 } 18782 18783 if (!mounted) { 18784 return; 18785 } 18786 18787 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18788 int[] users; 18789 if (userId == UserHandle.USER_ALL) { 18790 users = sUserManager.getUserIds(); 18791 } else { 18792 users = new int[] { userId }; 18793 } 18794 final ClearStorageConnection conn = new ClearStorageConnection(); 18795 if (mContext.bindServiceAsUser( 18796 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18797 try { 18798 for (int curUser : users) { 18799 long timeout = SystemClock.uptimeMillis() + 5000; 18800 synchronized (conn) { 18801 long now; 18802 while (conn.mContainerService == null && 18803 (now = SystemClock.uptimeMillis()) < timeout) { 18804 try { 18805 conn.wait(timeout - now); 18806 } catch (InterruptedException e) { 18807 } 18808 } 18809 } 18810 if (conn.mContainerService == null) { 18811 return; 18812 } 18813 18814 final UserEnvironment userEnv = new UserEnvironment(curUser); 18815 clearDirectory(conn.mContainerService, 18816 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18817 if (allData) { 18818 clearDirectory(conn.mContainerService, 18819 userEnv.buildExternalStorageAppDataDirs(packageName)); 18820 clearDirectory(conn.mContainerService, 18821 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18822 } 18823 } 18824 } finally { 18825 mContext.unbindService(conn); 18826 } 18827 } 18828 } 18829 18830 @Override 18831 public void clearApplicationProfileData(String packageName) { 18832 enforceSystemOrRoot("Only the system can clear all profile data"); 18833 18834 final PackageParser.Package pkg; 18835 synchronized (mPackages) { 18836 pkg = mPackages.get(packageName); 18837 } 18838 18839 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18840 synchronized (mInstallLock) { 18841 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18842 } 18843 } 18844 } 18845 18846 @Override 18847 public void clearApplicationUserData(final String packageName, 18848 final IPackageDataObserver observer, final int userId) { 18849 mContext.enforceCallingOrSelfPermission( 18850 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18851 18852 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18853 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18854 18855 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18856 throw new SecurityException("Cannot clear data for a protected package: " 18857 + packageName); 18858 } 18859 // Queue up an async operation since the package deletion may take a little while. 18860 mHandler.post(new Runnable() { 18861 public void run() { 18862 mHandler.removeCallbacks(this); 18863 final boolean succeeded; 18864 try (PackageFreezer freezer = freezePackage(packageName, 18865 "clearApplicationUserData")) { 18866 synchronized (mInstallLock) { 18867 succeeded = clearApplicationUserDataLIF(packageName, userId); 18868 } 18869 clearExternalStorageDataSync(packageName, userId, true); 18870 synchronized (mPackages) { 18871 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18872 packageName, userId); 18873 } 18874 } 18875 if (succeeded) { 18876 // invoke DeviceStorageMonitor's update method to clear any notifications 18877 DeviceStorageMonitorInternal dsm = LocalServices 18878 .getService(DeviceStorageMonitorInternal.class); 18879 if (dsm != null) { 18880 dsm.checkMemory(); 18881 } 18882 } 18883 if(observer != null) { 18884 try { 18885 observer.onRemoveCompleted(packageName, succeeded); 18886 } catch (RemoteException e) { 18887 Log.i(TAG, "Observer no longer exists."); 18888 } 18889 } //end if observer 18890 } //end run 18891 }); 18892 } 18893 18894 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18895 if (packageName == null) { 18896 Slog.w(TAG, "Attempt to delete null packageName."); 18897 return false; 18898 } 18899 18900 // Try finding details about the requested package 18901 PackageParser.Package pkg; 18902 synchronized (mPackages) { 18903 pkg = mPackages.get(packageName); 18904 if (pkg == null) { 18905 final PackageSetting ps = mSettings.mPackages.get(packageName); 18906 if (ps != null) { 18907 pkg = ps.pkg; 18908 } 18909 } 18910 18911 if (pkg == null) { 18912 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18913 return false; 18914 } 18915 18916 PackageSetting ps = (PackageSetting) pkg.mExtras; 18917 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18918 } 18919 18920 clearAppDataLIF(pkg, userId, 18921 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18922 18923 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18924 removeKeystoreDataIfNeeded(userId, appId); 18925 18926 UserManagerInternal umInternal = getUserManagerInternal(); 18927 final int flags; 18928 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18929 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18930 } else if (umInternal.isUserRunning(userId)) { 18931 flags = StorageManager.FLAG_STORAGE_DE; 18932 } else { 18933 flags = 0; 18934 } 18935 prepareAppDataContentsLIF(pkg, userId, flags); 18936 18937 return true; 18938 } 18939 18940 /** 18941 * Reverts user permission state changes (permissions and flags) in 18942 * all packages for a given user. 18943 * 18944 * @param userId The device user for which to do a reset. 18945 */ 18946 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18947 final int packageCount = mPackages.size(); 18948 for (int i = 0; i < packageCount; i++) { 18949 PackageParser.Package pkg = mPackages.valueAt(i); 18950 PackageSetting ps = (PackageSetting) pkg.mExtras; 18951 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18952 } 18953 } 18954 18955 private void resetNetworkPolicies(int userId) { 18956 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18957 } 18958 18959 /** 18960 * Reverts user permission state changes (permissions and flags). 18961 * 18962 * @param ps The package for which to reset. 18963 * @param userId The device user for which to do a reset. 18964 */ 18965 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18966 final PackageSetting ps, final int userId) { 18967 if (ps.pkg == null) { 18968 return; 18969 } 18970 18971 // These are flags that can change base on user actions. 18972 final int userSettableMask = FLAG_PERMISSION_USER_SET 18973 | FLAG_PERMISSION_USER_FIXED 18974 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18975 | FLAG_PERMISSION_REVIEW_REQUIRED; 18976 18977 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18978 | FLAG_PERMISSION_POLICY_FIXED; 18979 18980 boolean writeInstallPermissions = false; 18981 boolean writeRuntimePermissions = false; 18982 18983 final int permissionCount = ps.pkg.requestedPermissions.size(); 18984 for (int i = 0; i < permissionCount; i++) { 18985 String permission = ps.pkg.requestedPermissions.get(i); 18986 18987 BasePermission bp = mSettings.mPermissions.get(permission); 18988 if (bp == null) { 18989 continue; 18990 } 18991 18992 // If shared user we just reset the state to which only this app contributed. 18993 if (ps.sharedUser != null) { 18994 boolean used = false; 18995 final int packageCount = ps.sharedUser.packages.size(); 18996 for (int j = 0; j < packageCount; j++) { 18997 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18998 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18999 && pkg.pkg.requestedPermissions.contains(permission)) { 19000 used = true; 19001 break; 19002 } 19003 } 19004 if (used) { 19005 continue; 19006 } 19007 } 19008 19009 PermissionsState permissionsState = ps.getPermissionsState(); 19010 19011 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 19012 19013 // Always clear the user settable flags. 19014 final boolean hasInstallState = permissionsState.getInstallPermissionState( 19015 bp.name) != null; 19016 // If permission review is enabled and this is a legacy app, mark the 19017 // permission as requiring a review as this is the initial state. 19018 int flags = 0; 19019 if (mPermissionReviewRequired 19020 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19021 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19022 } 19023 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19024 if (hasInstallState) { 19025 writeInstallPermissions = true; 19026 } else { 19027 writeRuntimePermissions = true; 19028 } 19029 } 19030 19031 // Below is only runtime permission handling. 19032 if (!bp.isRuntime()) { 19033 continue; 19034 } 19035 19036 // Never clobber system or policy. 19037 if ((oldFlags & policyOrSystemFlags) != 0) { 19038 continue; 19039 } 19040 19041 // If this permission was granted by default, make sure it is. 19042 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19043 if (permissionsState.grantRuntimePermission(bp, userId) 19044 != PERMISSION_OPERATION_FAILURE) { 19045 writeRuntimePermissions = true; 19046 } 19047 // If permission review is enabled the permissions for a legacy apps 19048 // are represented as constantly granted runtime ones, so don't revoke. 19049 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19050 // Otherwise, reset the permission. 19051 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19052 switch (revokeResult) { 19053 case PERMISSION_OPERATION_SUCCESS: 19054 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19055 writeRuntimePermissions = true; 19056 final int appId = ps.appId; 19057 mHandler.post(new Runnable() { 19058 @Override 19059 public void run() { 19060 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19061 } 19062 }); 19063 } break; 19064 } 19065 } 19066 } 19067 19068 // Synchronously write as we are taking permissions away. 19069 if (writeRuntimePermissions) { 19070 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19071 } 19072 19073 // Synchronously write as we are taking permissions away. 19074 if (writeInstallPermissions) { 19075 mSettings.writeLPr(); 19076 } 19077 } 19078 19079 /** 19080 * Remove entries from the keystore daemon. Will only remove it if the 19081 * {@code appId} is valid. 19082 */ 19083 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19084 if (appId < 0) { 19085 return; 19086 } 19087 19088 final KeyStore keyStore = KeyStore.getInstance(); 19089 if (keyStore != null) { 19090 if (userId == UserHandle.USER_ALL) { 19091 for (final int individual : sUserManager.getUserIds()) { 19092 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19093 } 19094 } else { 19095 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19096 } 19097 } else { 19098 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19099 } 19100 } 19101 19102 @Override 19103 public void deleteApplicationCacheFiles(final String packageName, 19104 final IPackageDataObserver observer) { 19105 final int userId = UserHandle.getCallingUserId(); 19106 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19107 } 19108 19109 @Override 19110 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19111 final IPackageDataObserver observer) { 19112 mContext.enforceCallingOrSelfPermission( 19113 android.Manifest.permission.DELETE_CACHE_FILES, null); 19114 enforceCrossUserPermission(Binder.getCallingUid(), userId, 19115 /* requireFullPermission= */ true, /* checkShell= */ false, 19116 "delete application cache files"); 19117 19118 final PackageParser.Package pkg; 19119 synchronized (mPackages) { 19120 pkg = mPackages.get(packageName); 19121 } 19122 19123 // Queue up an async operation since the package deletion may take a little while. 19124 mHandler.post(new Runnable() { 19125 public void run() { 19126 synchronized (mInstallLock) { 19127 final int flags = StorageManager.FLAG_STORAGE_DE 19128 | StorageManager.FLAG_STORAGE_CE; 19129 // We're only clearing cache files, so we don't care if the 19130 // app is unfrozen and still able to run 19131 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19132 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19133 } 19134 clearExternalStorageDataSync(packageName, userId, false); 19135 if (observer != null) { 19136 try { 19137 observer.onRemoveCompleted(packageName, true); 19138 } catch (RemoteException e) { 19139 Log.i(TAG, "Observer no longer exists."); 19140 } 19141 } 19142 } 19143 }); 19144 } 19145 19146 @Override 19147 public void getPackageSizeInfo(final String packageName, int userHandle, 19148 final IPackageStatsObserver observer) { 19149 throw new UnsupportedOperationException( 19150 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19151 } 19152 19153 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19154 final PackageSetting ps; 19155 synchronized (mPackages) { 19156 ps = mSettings.mPackages.get(packageName); 19157 if (ps == null) { 19158 Slog.w(TAG, "Failed to find settings for " + packageName); 19159 return false; 19160 } 19161 } 19162 19163 final String[] packageNames = { packageName }; 19164 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19165 final String[] codePaths = { ps.codePathString }; 19166 19167 try { 19168 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19169 ps.appId, ceDataInodes, codePaths, stats); 19170 19171 // For now, ignore code size of packages on system partition 19172 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19173 stats.codeSize = 0; 19174 } 19175 19176 // External clients expect these to be tracked separately 19177 stats.dataSize -= stats.cacheSize; 19178 19179 } catch (InstallerException e) { 19180 Slog.w(TAG, String.valueOf(e)); 19181 return false; 19182 } 19183 19184 return true; 19185 } 19186 19187 private int getUidTargetSdkVersionLockedLPr(int uid) { 19188 Object obj = mSettings.getUserIdLPr(uid); 19189 if (obj instanceof SharedUserSetting) { 19190 final SharedUserSetting sus = (SharedUserSetting) obj; 19191 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19192 final Iterator<PackageSetting> it = sus.packages.iterator(); 19193 while (it.hasNext()) { 19194 final PackageSetting ps = it.next(); 19195 if (ps.pkg != null) { 19196 int v = ps.pkg.applicationInfo.targetSdkVersion; 19197 if (v < vers) vers = v; 19198 } 19199 } 19200 return vers; 19201 } else if (obj instanceof PackageSetting) { 19202 final PackageSetting ps = (PackageSetting) obj; 19203 if (ps.pkg != null) { 19204 return ps.pkg.applicationInfo.targetSdkVersion; 19205 } 19206 } 19207 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19208 } 19209 19210 @Override 19211 public void addPreferredActivity(IntentFilter filter, int match, 19212 ComponentName[] set, ComponentName activity, int userId) { 19213 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19214 "Adding preferred"); 19215 } 19216 19217 private void addPreferredActivityInternal(IntentFilter filter, int match, 19218 ComponentName[] set, ComponentName activity, boolean always, int userId, 19219 String opname) { 19220 // writer 19221 int callingUid = Binder.getCallingUid(); 19222 enforceCrossUserPermission(callingUid, userId, 19223 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19224 if (filter.countActions() == 0) { 19225 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19226 return; 19227 } 19228 synchronized (mPackages) { 19229 if (mContext.checkCallingOrSelfPermission( 19230 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19231 != PackageManager.PERMISSION_GRANTED) { 19232 if (getUidTargetSdkVersionLockedLPr(callingUid) 19233 < Build.VERSION_CODES.FROYO) { 19234 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19235 + callingUid); 19236 return; 19237 } 19238 mContext.enforceCallingOrSelfPermission( 19239 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19240 } 19241 19242 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19243 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19244 + userId + ":"); 19245 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19246 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19247 scheduleWritePackageRestrictionsLocked(userId); 19248 postPreferredActivityChangedBroadcast(userId); 19249 } 19250 } 19251 19252 private void postPreferredActivityChangedBroadcast(int userId) { 19253 mHandler.post(() -> { 19254 final IActivityManager am = ActivityManager.getService(); 19255 if (am == null) { 19256 return; 19257 } 19258 19259 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19260 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19261 try { 19262 am.broadcastIntent(null, intent, null, null, 19263 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19264 null, false, false, userId); 19265 } catch (RemoteException e) { 19266 } 19267 }); 19268 } 19269 19270 @Override 19271 public void replacePreferredActivity(IntentFilter filter, int match, 19272 ComponentName[] set, ComponentName activity, int userId) { 19273 if (filter.countActions() != 1) { 19274 throw new IllegalArgumentException( 19275 "replacePreferredActivity expects filter to have only 1 action."); 19276 } 19277 if (filter.countDataAuthorities() != 0 19278 || filter.countDataPaths() != 0 19279 || filter.countDataSchemes() > 1 19280 || filter.countDataTypes() != 0) { 19281 throw new IllegalArgumentException( 19282 "replacePreferredActivity expects filter to have no data authorities, " + 19283 "paths, or types; and at most one scheme."); 19284 } 19285 19286 final int callingUid = Binder.getCallingUid(); 19287 enforceCrossUserPermission(callingUid, userId, 19288 true /* requireFullPermission */, false /* checkShell */, 19289 "replace preferred activity"); 19290 synchronized (mPackages) { 19291 if (mContext.checkCallingOrSelfPermission( 19292 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19293 != PackageManager.PERMISSION_GRANTED) { 19294 if (getUidTargetSdkVersionLockedLPr(callingUid) 19295 < Build.VERSION_CODES.FROYO) { 19296 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19297 + Binder.getCallingUid()); 19298 return; 19299 } 19300 mContext.enforceCallingOrSelfPermission( 19301 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19302 } 19303 19304 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19305 if (pir != null) { 19306 // Get all of the existing entries that exactly match this filter. 19307 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19308 if (existing != null && existing.size() == 1) { 19309 PreferredActivity cur = existing.get(0); 19310 if (DEBUG_PREFERRED) { 19311 Slog.i(TAG, "Checking replace of preferred:"); 19312 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19313 if (!cur.mPref.mAlways) { 19314 Slog.i(TAG, " -- CUR; not mAlways!"); 19315 } else { 19316 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19317 Slog.i(TAG, " -- CUR: mSet=" 19318 + Arrays.toString(cur.mPref.mSetComponents)); 19319 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19320 Slog.i(TAG, " -- NEW: mMatch=" 19321 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19322 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19323 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19324 } 19325 } 19326 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19327 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19328 && cur.mPref.sameSet(set)) { 19329 // Setting the preferred activity to what it happens to be already 19330 if (DEBUG_PREFERRED) { 19331 Slog.i(TAG, "Replacing with same preferred activity " 19332 + cur.mPref.mShortComponent + " for user " 19333 + userId + ":"); 19334 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19335 } 19336 return; 19337 } 19338 } 19339 19340 if (existing != null) { 19341 if (DEBUG_PREFERRED) { 19342 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19343 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19344 } 19345 for (int i = 0; i < existing.size(); i++) { 19346 PreferredActivity pa = existing.get(i); 19347 if (DEBUG_PREFERRED) { 19348 Slog.i(TAG, "Removing existing preferred activity " 19349 + pa.mPref.mComponent + ":"); 19350 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19351 } 19352 pir.removeFilter(pa); 19353 } 19354 } 19355 } 19356 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19357 "Replacing preferred"); 19358 } 19359 } 19360 19361 @Override 19362 public void clearPackagePreferredActivities(String packageName) { 19363 final int uid = Binder.getCallingUid(); 19364 // writer 19365 synchronized (mPackages) { 19366 PackageParser.Package pkg = mPackages.get(packageName); 19367 if (pkg == null || pkg.applicationInfo.uid != uid) { 19368 if (mContext.checkCallingOrSelfPermission( 19369 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19370 != PackageManager.PERMISSION_GRANTED) { 19371 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 19372 < Build.VERSION_CODES.FROYO) { 19373 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19374 + Binder.getCallingUid()); 19375 return; 19376 } 19377 mContext.enforceCallingOrSelfPermission( 19378 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19379 } 19380 } 19381 19382 int user = UserHandle.getCallingUserId(); 19383 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19384 scheduleWritePackageRestrictionsLocked(user); 19385 } 19386 } 19387 } 19388 19389 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19390 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19391 ArrayList<PreferredActivity> removed = null; 19392 boolean changed = false; 19393 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19394 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19395 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19396 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19397 continue; 19398 } 19399 Iterator<PreferredActivity> it = pir.filterIterator(); 19400 while (it.hasNext()) { 19401 PreferredActivity pa = it.next(); 19402 // Mark entry for removal only if it matches the package name 19403 // and the entry is of type "always". 19404 if (packageName == null || 19405 (pa.mPref.mComponent.getPackageName().equals(packageName) 19406 && pa.mPref.mAlways)) { 19407 if (removed == null) { 19408 removed = new ArrayList<PreferredActivity>(); 19409 } 19410 removed.add(pa); 19411 } 19412 } 19413 if (removed != null) { 19414 for (int j=0; j<removed.size(); j++) { 19415 PreferredActivity pa = removed.get(j); 19416 pir.removeFilter(pa); 19417 } 19418 changed = true; 19419 } 19420 } 19421 if (changed) { 19422 postPreferredActivityChangedBroadcast(userId); 19423 } 19424 return changed; 19425 } 19426 19427 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19428 private void clearIntentFilterVerificationsLPw(int userId) { 19429 final int packageCount = mPackages.size(); 19430 for (int i = 0; i < packageCount; i++) { 19431 PackageParser.Package pkg = mPackages.valueAt(i); 19432 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19433 } 19434 } 19435 19436 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19437 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19438 if (userId == UserHandle.USER_ALL) { 19439 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19440 sUserManager.getUserIds())) { 19441 for (int oneUserId : sUserManager.getUserIds()) { 19442 scheduleWritePackageRestrictionsLocked(oneUserId); 19443 } 19444 } 19445 } else { 19446 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19447 scheduleWritePackageRestrictionsLocked(userId); 19448 } 19449 } 19450 } 19451 19452 /** Clears state for all users, and touches intent filter verification policy */ 19453 void clearDefaultBrowserIfNeeded(String packageName) { 19454 for (int oneUserId : sUserManager.getUserIds()) { 19455 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19456 } 19457 } 19458 19459 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19460 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19461 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19462 if (packageName.equals(defaultBrowserPackageName)) { 19463 setDefaultBrowserPackageName(null, userId); 19464 } 19465 } 19466 } 19467 19468 @Override 19469 public void resetApplicationPreferences(int userId) { 19470 mContext.enforceCallingOrSelfPermission( 19471 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19472 final long identity = Binder.clearCallingIdentity(); 19473 // writer 19474 try { 19475 synchronized (mPackages) { 19476 clearPackagePreferredActivitiesLPw(null, userId); 19477 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19478 // TODO: We have to reset the default SMS and Phone. This requires 19479 // significant refactoring to keep all default apps in the package 19480 // manager (cleaner but more work) or have the services provide 19481 // callbacks to the package manager to request a default app reset. 19482 applyFactoryDefaultBrowserLPw(userId); 19483 clearIntentFilterVerificationsLPw(userId); 19484 primeDomainVerificationsLPw(userId); 19485 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19486 scheduleWritePackageRestrictionsLocked(userId); 19487 } 19488 resetNetworkPolicies(userId); 19489 } finally { 19490 Binder.restoreCallingIdentity(identity); 19491 } 19492 } 19493 19494 @Override 19495 public int getPreferredActivities(List<IntentFilter> outFilters, 19496 List<ComponentName> outActivities, String packageName) { 19497 19498 int num = 0; 19499 final int userId = UserHandle.getCallingUserId(); 19500 // reader 19501 synchronized (mPackages) { 19502 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19503 if (pir != null) { 19504 final Iterator<PreferredActivity> it = pir.filterIterator(); 19505 while (it.hasNext()) { 19506 final PreferredActivity pa = it.next(); 19507 if (packageName == null 19508 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19509 && pa.mPref.mAlways)) { 19510 if (outFilters != null) { 19511 outFilters.add(new IntentFilter(pa)); 19512 } 19513 if (outActivities != null) { 19514 outActivities.add(pa.mPref.mComponent); 19515 } 19516 } 19517 } 19518 } 19519 } 19520 19521 return num; 19522 } 19523 19524 @Override 19525 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19526 int userId) { 19527 int callingUid = Binder.getCallingUid(); 19528 if (callingUid != Process.SYSTEM_UID) { 19529 throw new SecurityException( 19530 "addPersistentPreferredActivity can only be run by the system"); 19531 } 19532 if (filter.countActions() == 0) { 19533 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19534 return; 19535 } 19536 synchronized (mPackages) { 19537 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19538 ":"); 19539 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19540 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19541 new PersistentPreferredActivity(filter, activity)); 19542 scheduleWritePackageRestrictionsLocked(userId); 19543 postPreferredActivityChangedBroadcast(userId); 19544 } 19545 } 19546 19547 @Override 19548 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19549 int callingUid = Binder.getCallingUid(); 19550 if (callingUid != Process.SYSTEM_UID) { 19551 throw new SecurityException( 19552 "clearPackagePersistentPreferredActivities can only be run by the system"); 19553 } 19554 ArrayList<PersistentPreferredActivity> removed = null; 19555 boolean changed = false; 19556 synchronized (mPackages) { 19557 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19558 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19559 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19560 .valueAt(i); 19561 if (userId != thisUserId) { 19562 continue; 19563 } 19564 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19565 while (it.hasNext()) { 19566 PersistentPreferredActivity ppa = it.next(); 19567 // Mark entry for removal only if it matches the package name. 19568 if (ppa.mComponent.getPackageName().equals(packageName)) { 19569 if (removed == null) { 19570 removed = new ArrayList<PersistentPreferredActivity>(); 19571 } 19572 removed.add(ppa); 19573 } 19574 } 19575 if (removed != null) { 19576 for (int j=0; j<removed.size(); j++) { 19577 PersistentPreferredActivity ppa = removed.get(j); 19578 ppir.removeFilter(ppa); 19579 } 19580 changed = true; 19581 } 19582 } 19583 19584 if (changed) { 19585 scheduleWritePackageRestrictionsLocked(userId); 19586 postPreferredActivityChangedBroadcast(userId); 19587 } 19588 } 19589 } 19590 19591 /** 19592 * Common machinery for picking apart a restored XML blob and passing 19593 * it to a caller-supplied functor to be applied to the running system. 19594 */ 19595 private void restoreFromXml(XmlPullParser parser, int userId, 19596 String expectedStartTag, BlobXmlRestorer functor) 19597 throws IOException, XmlPullParserException { 19598 int type; 19599 while ((type = parser.next()) != XmlPullParser.START_TAG 19600 && type != XmlPullParser.END_DOCUMENT) { 19601 } 19602 if (type != XmlPullParser.START_TAG) { 19603 // oops didn't find a start tag?! 19604 if (DEBUG_BACKUP) { 19605 Slog.e(TAG, "Didn't find start tag during restore"); 19606 } 19607 return; 19608 } 19609Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19610 // this is supposed to be TAG_PREFERRED_BACKUP 19611 if (!expectedStartTag.equals(parser.getName())) { 19612 if (DEBUG_BACKUP) { 19613 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19614 } 19615 return; 19616 } 19617 19618 // skip interfering stuff, then we're aligned with the backing implementation 19619 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19620Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19621 functor.apply(parser, userId); 19622 } 19623 19624 private interface BlobXmlRestorer { 19625 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19626 } 19627 19628 /** 19629 * Non-Binder method, support for the backup/restore mechanism: write the 19630 * full set of preferred activities in its canonical XML format. Returns the 19631 * XML output as a byte array, or null if there is none. 19632 */ 19633 @Override 19634 public byte[] getPreferredActivityBackup(int userId) { 19635 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19636 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19637 } 19638 19639 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19640 try { 19641 final XmlSerializer serializer = new FastXmlSerializer(); 19642 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19643 serializer.startDocument(null, true); 19644 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19645 19646 synchronized (mPackages) { 19647 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19648 } 19649 19650 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19651 serializer.endDocument(); 19652 serializer.flush(); 19653 } catch (Exception e) { 19654 if (DEBUG_BACKUP) { 19655 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19656 } 19657 return null; 19658 } 19659 19660 return dataStream.toByteArray(); 19661 } 19662 19663 @Override 19664 public void restorePreferredActivities(byte[] backup, int userId) { 19665 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19666 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19667 } 19668 19669 try { 19670 final XmlPullParser parser = Xml.newPullParser(); 19671 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19672 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19673 new BlobXmlRestorer() { 19674 @Override 19675 public void apply(XmlPullParser parser, int userId) 19676 throws XmlPullParserException, IOException { 19677 synchronized (mPackages) { 19678 mSettings.readPreferredActivitiesLPw(parser, userId); 19679 } 19680 } 19681 } ); 19682 } catch (Exception e) { 19683 if (DEBUG_BACKUP) { 19684 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19685 } 19686 } 19687 } 19688 19689 /** 19690 * Non-Binder method, support for the backup/restore mechanism: write the 19691 * default browser (etc) settings in its canonical XML format. Returns the default 19692 * browser XML representation as a byte array, or null if there is none. 19693 */ 19694 @Override 19695 public byte[] getDefaultAppsBackup(int userId) { 19696 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19697 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19698 } 19699 19700 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19701 try { 19702 final XmlSerializer serializer = new FastXmlSerializer(); 19703 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19704 serializer.startDocument(null, true); 19705 serializer.startTag(null, TAG_DEFAULT_APPS); 19706 19707 synchronized (mPackages) { 19708 mSettings.writeDefaultAppsLPr(serializer, userId); 19709 } 19710 19711 serializer.endTag(null, TAG_DEFAULT_APPS); 19712 serializer.endDocument(); 19713 serializer.flush(); 19714 } catch (Exception e) { 19715 if (DEBUG_BACKUP) { 19716 Slog.e(TAG, "Unable to write default apps for backup", e); 19717 } 19718 return null; 19719 } 19720 19721 return dataStream.toByteArray(); 19722 } 19723 19724 @Override 19725 public void restoreDefaultApps(byte[] backup, int userId) { 19726 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19727 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19728 } 19729 19730 try { 19731 final XmlPullParser parser = Xml.newPullParser(); 19732 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19733 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19734 new BlobXmlRestorer() { 19735 @Override 19736 public void apply(XmlPullParser parser, int userId) 19737 throws XmlPullParserException, IOException { 19738 synchronized (mPackages) { 19739 mSettings.readDefaultAppsLPw(parser, userId); 19740 } 19741 } 19742 } ); 19743 } catch (Exception e) { 19744 if (DEBUG_BACKUP) { 19745 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19746 } 19747 } 19748 } 19749 19750 @Override 19751 public byte[] getIntentFilterVerificationBackup(int userId) { 19752 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19753 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19754 } 19755 19756 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19757 try { 19758 final XmlSerializer serializer = new FastXmlSerializer(); 19759 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19760 serializer.startDocument(null, true); 19761 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19762 19763 synchronized (mPackages) { 19764 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19765 } 19766 19767 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19768 serializer.endDocument(); 19769 serializer.flush(); 19770 } catch (Exception e) { 19771 if (DEBUG_BACKUP) { 19772 Slog.e(TAG, "Unable to write default apps for backup", e); 19773 } 19774 return null; 19775 } 19776 19777 return dataStream.toByteArray(); 19778 } 19779 19780 @Override 19781 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19782 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19783 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19784 } 19785 19786 try { 19787 final XmlPullParser parser = Xml.newPullParser(); 19788 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19789 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19790 new BlobXmlRestorer() { 19791 @Override 19792 public void apply(XmlPullParser parser, int userId) 19793 throws XmlPullParserException, IOException { 19794 synchronized (mPackages) { 19795 mSettings.readAllDomainVerificationsLPr(parser, userId); 19796 mSettings.writeLPr(); 19797 } 19798 } 19799 } ); 19800 } catch (Exception e) { 19801 if (DEBUG_BACKUP) { 19802 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19803 } 19804 } 19805 } 19806 19807 @Override 19808 public byte[] getPermissionGrantBackup(int userId) { 19809 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19810 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19811 } 19812 19813 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19814 try { 19815 final XmlSerializer serializer = new FastXmlSerializer(); 19816 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19817 serializer.startDocument(null, true); 19818 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19819 19820 synchronized (mPackages) { 19821 serializeRuntimePermissionGrantsLPr(serializer, userId); 19822 } 19823 19824 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19825 serializer.endDocument(); 19826 serializer.flush(); 19827 } catch (Exception e) { 19828 if (DEBUG_BACKUP) { 19829 Slog.e(TAG, "Unable to write default apps for backup", e); 19830 } 19831 return null; 19832 } 19833 19834 return dataStream.toByteArray(); 19835 } 19836 19837 @Override 19838 public void restorePermissionGrants(byte[] backup, int userId) { 19839 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19840 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19841 } 19842 19843 try { 19844 final XmlPullParser parser = Xml.newPullParser(); 19845 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19846 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19847 new BlobXmlRestorer() { 19848 @Override 19849 public void apply(XmlPullParser parser, int userId) 19850 throws XmlPullParserException, IOException { 19851 synchronized (mPackages) { 19852 processRestoredPermissionGrantsLPr(parser, userId); 19853 } 19854 } 19855 } ); 19856 } catch (Exception e) { 19857 if (DEBUG_BACKUP) { 19858 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19859 } 19860 } 19861 } 19862 19863 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19864 throws IOException { 19865 serializer.startTag(null, TAG_ALL_GRANTS); 19866 19867 final int N = mSettings.mPackages.size(); 19868 for (int i = 0; i < N; i++) { 19869 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19870 boolean pkgGrantsKnown = false; 19871 19872 PermissionsState packagePerms = ps.getPermissionsState(); 19873 19874 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19875 final int grantFlags = state.getFlags(); 19876 // only look at grants that are not system/policy fixed 19877 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19878 final boolean isGranted = state.isGranted(); 19879 // And only back up the user-twiddled state bits 19880 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19881 final String packageName = mSettings.mPackages.keyAt(i); 19882 if (!pkgGrantsKnown) { 19883 serializer.startTag(null, TAG_GRANT); 19884 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19885 pkgGrantsKnown = true; 19886 } 19887 19888 final boolean userSet = 19889 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19890 final boolean userFixed = 19891 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19892 final boolean revoke = 19893 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19894 19895 serializer.startTag(null, TAG_PERMISSION); 19896 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19897 if (isGranted) { 19898 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19899 } 19900 if (userSet) { 19901 serializer.attribute(null, ATTR_USER_SET, "true"); 19902 } 19903 if (userFixed) { 19904 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19905 } 19906 if (revoke) { 19907 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19908 } 19909 serializer.endTag(null, TAG_PERMISSION); 19910 } 19911 } 19912 } 19913 19914 if (pkgGrantsKnown) { 19915 serializer.endTag(null, TAG_GRANT); 19916 } 19917 } 19918 19919 serializer.endTag(null, TAG_ALL_GRANTS); 19920 } 19921 19922 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19923 throws XmlPullParserException, IOException { 19924 String pkgName = null; 19925 int outerDepth = parser.getDepth(); 19926 int type; 19927 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19928 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19929 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19930 continue; 19931 } 19932 19933 final String tagName = parser.getName(); 19934 if (tagName.equals(TAG_GRANT)) { 19935 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19936 if (DEBUG_BACKUP) { 19937 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19938 } 19939 } else if (tagName.equals(TAG_PERMISSION)) { 19940 19941 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19942 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19943 19944 int newFlagSet = 0; 19945 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19946 newFlagSet |= FLAG_PERMISSION_USER_SET; 19947 } 19948 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19949 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19950 } 19951 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19952 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19953 } 19954 if (DEBUG_BACKUP) { 19955 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19956 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19957 } 19958 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19959 if (ps != null) { 19960 // Already installed so we apply the grant immediately 19961 if (DEBUG_BACKUP) { 19962 Slog.v(TAG, " + already installed; applying"); 19963 } 19964 PermissionsState perms = ps.getPermissionsState(); 19965 BasePermission bp = mSettings.mPermissions.get(permName); 19966 if (bp != null) { 19967 if (isGranted) { 19968 perms.grantRuntimePermission(bp, userId); 19969 } 19970 if (newFlagSet != 0) { 19971 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19972 } 19973 } 19974 } else { 19975 // Need to wait for post-restore install to apply the grant 19976 if (DEBUG_BACKUP) { 19977 Slog.v(TAG, " - not yet installed; saving for later"); 19978 } 19979 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19980 isGranted, newFlagSet, userId); 19981 } 19982 } else { 19983 PackageManagerService.reportSettingsProblem(Log.WARN, 19984 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19985 XmlUtils.skipCurrentTag(parser); 19986 } 19987 } 19988 19989 scheduleWriteSettingsLocked(); 19990 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19991 } 19992 19993 @Override 19994 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19995 int sourceUserId, int targetUserId, int flags) { 19996 mContext.enforceCallingOrSelfPermission( 19997 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19998 int callingUid = Binder.getCallingUid(); 19999 enforceOwnerRights(ownerPackage, callingUid); 20000 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20001 if (intentFilter.countActions() == 0) { 20002 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20003 return; 20004 } 20005 synchronized (mPackages) { 20006 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20007 ownerPackage, targetUserId, flags); 20008 CrossProfileIntentResolver resolver = 20009 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20010 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20011 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20012 if (existing != null) { 20013 int size = existing.size(); 20014 for (int i = 0; i < size; i++) { 20015 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20016 return; 20017 } 20018 } 20019 } 20020 resolver.addFilter(newFilter); 20021 scheduleWritePackageRestrictionsLocked(sourceUserId); 20022 } 20023 } 20024 20025 @Override 20026 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20027 mContext.enforceCallingOrSelfPermission( 20028 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20029 int callingUid = Binder.getCallingUid(); 20030 enforceOwnerRights(ownerPackage, callingUid); 20031 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20032 synchronized (mPackages) { 20033 CrossProfileIntentResolver resolver = 20034 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20035 ArraySet<CrossProfileIntentFilter> set = 20036 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20037 for (CrossProfileIntentFilter filter : set) { 20038 if (filter.getOwnerPackage().equals(ownerPackage)) { 20039 resolver.removeFilter(filter); 20040 } 20041 } 20042 scheduleWritePackageRestrictionsLocked(sourceUserId); 20043 } 20044 } 20045 20046 // Enforcing that callingUid is owning pkg on userId 20047 private void enforceOwnerRights(String pkg, int callingUid) { 20048 // The system owns everything. 20049 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20050 return; 20051 } 20052 int callingUserId = UserHandle.getUserId(callingUid); 20053 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20054 if (pi == null) { 20055 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20056 + callingUserId); 20057 } 20058 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20059 throw new SecurityException("Calling uid " + callingUid 20060 + " does not own package " + pkg); 20061 } 20062 } 20063 20064 @Override 20065 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20066 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20067 } 20068 20069 /** 20070 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20071 * then reports the most likely home activity or null if there are more than one. 20072 */ 20073 public ComponentName getDefaultHomeActivity(int userId) { 20074 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20075 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20076 if (cn != null) { 20077 return cn; 20078 } 20079 20080 // Find the launcher with the highest priority and return that component if there are no 20081 // other home activity with the same priority. 20082 int lastPriority = Integer.MIN_VALUE; 20083 ComponentName lastComponent = null; 20084 final int size = allHomeCandidates.size(); 20085 for (int i = 0; i < size; i++) { 20086 final ResolveInfo ri = allHomeCandidates.get(i); 20087 if (ri.priority > lastPriority) { 20088 lastComponent = ri.activityInfo.getComponentName(); 20089 lastPriority = ri.priority; 20090 } else if (ri.priority == lastPriority) { 20091 // Two components found with same priority. 20092 lastComponent = null; 20093 } 20094 } 20095 return lastComponent; 20096 } 20097 20098 private Intent getHomeIntent() { 20099 Intent intent = new Intent(Intent.ACTION_MAIN); 20100 intent.addCategory(Intent.CATEGORY_HOME); 20101 intent.addCategory(Intent.CATEGORY_DEFAULT); 20102 return intent; 20103 } 20104 20105 private IntentFilter getHomeFilter() { 20106 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20107 filter.addCategory(Intent.CATEGORY_HOME); 20108 filter.addCategory(Intent.CATEGORY_DEFAULT); 20109 return filter; 20110 } 20111 20112 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20113 int userId) { 20114 Intent intent = getHomeIntent(); 20115 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20116 PackageManager.GET_META_DATA, userId); 20117 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20118 true, false, false, userId); 20119 20120 allHomeCandidates.clear(); 20121 if (list != null) { 20122 for (ResolveInfo ri : list) { 20123 allHomeCandidates.add(ri); 20124 } 20125 } 20126 return (preferred == null || preferred.activityInfo == null) 20127 ? null 20128 : new ComponentName(preferred.activityInfo.packageName, 20129 preferred.activityInfo.name); 20130 } 20131 20132 @Override 20133 public void setHomeActivity(ComponentName comp, int userId) { 20134 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20135 getHomeActivitiesAsUser(homeActivities, userId); 20136 20137 boolean found = false; 20138 20139 final int size = homeActivities.size(); 20140 final ComponentName[] set = new ComponentName[size]; 20141 for (int i = 0; i < size; i++) { 20142 final ResolveInfo candidate = homeActivities.get(i); 20143 final ActivityInfo info = candidate.activityInfo; 20144 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20145 set[i] = activityName; 20146 if (!found && activityName.equals(comp)) { 20147 found = true; 20148 } 20149 } 20150 if (!found) { 20151 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20152 + userId); 20153 } 20154 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20155 set, comp, userId); 20156 } 20157 20158 private @Nullable String getSetupWizardPackageName() { 20159 final Intent intent = new Intent(Intent.ACTION_MAIN); 20160 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20161 20162 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20163 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20164 | MATCH_DISABLED_COMPONENTS, 20165 UserHandle.myUserId()); 20166 if (matches.size() == 1) { 20167 return matches.get(0).getComponentInfo().packageName; 20168 } else { 20169 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20170 + ": matches=" + matches); 20171 return null; 20172 } 20173 } 20174 20175 private @Nullable String getStorageManagerPackageName() { 20176 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20177 20178 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20179 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20180 | MATCH_DISABLED_COMPONENTS, 20181 UserHandle.myUserId()); 20182 if (matches.size() == 1) { 20183 return matches.get(0).getComponentInfo().packageName; 20184 } else { 20185 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20186 + matches.size() + ": matches=" + matches); 20187 return null; 20188 } 20189 } 20190 20191 @Override 20192 public void setApplicationEnabledSetting(String appPackageName, 20193 int newState, int flags, int userId, String callingPackage) { 20194 if (!sUserManager.exists(userId)) return; 20195 if (callingPackage == null) { 20196 callingPackage = Integer.toString(Binder.getCallingUid()); 20197 } 20198 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20199 } 20200 20201 @Override 20202 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20203 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20204 synchronized (mPackages) { 20205 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20206 if (pkgSetting != null) { 20207 pkgSetting.setUpdateAvailable(updateAvailable); 20208 } 20209 } 20210 } 20211 20212 @Override 20213 public void setComponentEnabledSetting(ComponentName componentName, 20214 int newState, int flags, int userId) { 20215 if (!sUserManager.exists(userId)) return; 20216 setEnabledSetting(componentName.getPackageName(), 20217 componentName.getClassName(), newState, flags, userId, null); 20218 } 20219 20220 private void setEnabledSetting(final String packageName, String className, int newState, 20221 final int flags, int userId, String callingPackage) { 20222 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20223 || newState == COMPONENT_ENABLED_STATE_ENABLED 20224 || newState == COMPONENT_ENABLED_STATE_DISABLED 20225 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20226 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20227 throw new IllegalArgumentException("Invalid new component state: " 20228 + newState); 20229 } 20230 PackageSetting pkgSetting; 20231 final int uid = Binder.getCallingUid(); 20232 final int permission; 20233 if (uid == Process.SYSTEM_UID) { 20234 permission = PackageManager.PERMISSION_GRANTED; 20235 } else { 20236 permission = mContext.checkCallingOrSelfPermission( 20237 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20238 } 20239 enforceCrossUserPermission(uid, userId, 20240 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20241 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20242 boolean sendNow = false; 20243 boolean isApp = (className == null); 20244 String componentName = isApp ? packageName : className; 20245 int packageUid = -1; 20246 ArrayList<String> components; 20247 20248 // writer 20249 synchronized (mPackages) { 20250 pkgSetting = mSettings.mPackages.get(packageName); 20251 if (pkgSetting == null) { 20252 if (className == null) { 20253 throw new IllegalArgumentException("Unknown package: " + packageName); 20254 } 20255 throw new IllegalArgumentException( 20256 "Unknown component: " + packageName + "/" + className); 20257 } 20258 } 20259 20260 // Limit who can change which apps 20261 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 20262 // Don't allow apps that don't have permission to modify other apps 20263 if (!allowedByPermission) { 20264 throw new SecurityException( 20265 "Permission Denial: attempt to change component state from pid=" 20266 + Binder.getCallingPid() 20267 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 20268 } 20269 // Don't allow changing protected packages. 20270 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20271 throw new SecurityException("Cannot disable a protected package: " + packageName); 20272 } 20273 } 20274 20275 synchronized (mPackages) { 20276 if (uid == Process.SHELL_UID 20277 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20278 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20279 // unless it is a test package. 20280 int oldState = pkgSetting.getEnabled(userId); 20281 if (className == null 20282 && 20283 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20284 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20285 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20286 && 20287 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20288 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20289 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20290 // ok 20291 } else { 20292 throw new SecurityException( 20293 "Shell cannot change component state for " + packageName + "/" 20294 + className + " to " + newState); 20295 } 20296 } 20297 if (className == null) { 20298 // We're dealing with an application/package level state change 20299 if (pkgSetting.getEnabled(userId) == newState) { 20300 // Nothing to do 20301 return; 20302 } 20303 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20304 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20305 // Don't care about who enables an app. 20306 callingPackage = null; 20307 } 20308 pkgSetting.setEnabled(newState, userId, callingPackage); 20309 // pkgSetting.pkg.mSetEnabled = newState; 20310 } else { 20311 // We're dealing with a component level state change 20312 // First, verify that this is a valid class name. 20313 PackageParser.Package pkg = pkgSetting.pkg; 20314 if (pkg == null || !pkg.hasComponentClassName(className)) { 20315 if (pkg != null && 20316 pkg.applicationInfo.targetSdkVersion >= 20317 Build.VERSION_CODES.JELLY_BEAN) { 20318 throw new IllegalArgumentException("Component class " + className 20319 + " does not exist in " + packageName); 20320 } else { 20321 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20322 + className + " does not exist in " + packageName); 20323 } 20324 } 20325 switch (newState) { 20326 case COMPONENT_ENABLED_STATE_ENABLED: 20327 if (!pkgSetting.enableComponentLPw(className, userId)) { 20328 return; 20329 } 20330 break; 20331 case COMPONENT_ENABLED_STATE_DISABLED: 20332 if (!pkgSetting.disableComponentLPw(className, userId)) { 20333 return; 20334 } 20335 break; 20336 case COMPONENT_ENABLED_STATE_DEFAULT: 20337 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20338 return; 20339 } 20340 break; 20341 default: 20342 Slog.e(TAG, "Invalid new component state: " + newState); 20343 return; 20344 } 20345 } 20346 scheduleWritePackageRestrictionsLocked(userId); 20347 updateSequenceNumberLP(packageName, new int[] { userId }); 20348 final long callingId = Binder.clearCallingIdentity(); 20349 try { 20350 updateInstantAppInstallerLocked(packageName); 20351 } finally { 20352 Binder.restoreCallingIdentity(callingId); 20353 } 20354 components = mPendingBroadcasts.get(userId, packageName); 20355 final boolean newPackage = components == null; 20356 if (newPackage) { 20357 components = new ArrayList<String>(); 20358 } 20359 if (!components.contains(componentName)) { 20360 components.add(componentName); 20361 } 20362 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20363 sendNow = true; 20364 // Purge entry from pending broadcast list if another one exists already 20365 // since we are sending one right away. 20366 mPendingBroadcasts.remove(userId, packageName); 20367 } else { 20368 if (newPackage) { 20369 mPendingBroadcasts.put(userId, packageName, components); 20370 } 20371 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20372 // Schedule a message 20373 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20374 } 20375 } 20376 } 20377 20378 long callingId = Binder.clearCallingIdentity(); 20379 try { 20380 if (sendNow) { 20381 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20382 sendPackageChangedBroadcast(packageName, 20383 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20384 } 20385 } finally { 20386 Binder.restoreCallingIdentity(callingId); 20387 } 20388 } 20389 20390 @Override 20391 public void flushPackageRestrictionsAsUser(int userId) { 20392 if (!sUserManager.exists(userId)) { 20393 return; 20394 } 20395 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20396 false /* checkShell */, "flushPackageRestrictions"); 20397 synchronized (mPackages) { 20398 mSettings.writePackageRestrictionsLPr(userId); 20399 mDirtyUsers.remove(userId); 20400 if (mDirtyUsers.isEmpty()) { 20401 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20402 } 20403 } 20404 } 20405 20406 private void sendPackageChangedBroadcast(String packageName, 20407 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20408 if (DEBUG_INSTALL) 20409 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20410 + componentNames); 20411 Bundle extras = new Bundle(4); 20412 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20413 String nameList[] = new String[componentNames.size()]; 20414 componentNames.toArray(nameList); 20415 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20416 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20417 extras.putInt(Intent.EXTRA_UID, packageUid); 20418 // If this is not reporting a change of the overall package, then only send it 20419 // to registered receivers. We don't want to launch a swath of apps for every 20420 // little component state change. 20421 final int flags = !componentNames.contains(packageName) 20422 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20423 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20424 new int[] {UserHandle.getUserId(packageUid)}); 20425 } 20426 20427 @Override 20428 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20429 if (!sUserManager.exists(userId)) return; 20430 final int uid = Binder.getCallingUid(); 20431 final int permission = mContext.checkCallingOrSelfPermission( 20432 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20433 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20434 enforceCrossUserPermission(uid, userId, 20435 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20436 // writer 20437 synchronized (mPackages) { 20438 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20439 allowedByPermission, uid, userId)) { 20440 scheduleWritePackageRestrictionsLocked(userId); 20441 } 20442 } 20443 } 20444 20445 @Override 20446 public String getInstallerPackageName(String packageName) { 20447 // reader 20448 synchronized (mPackages) { 20449 return mSettings.getInstallerPackageNameLPr(packageName); 20450 } 20451 } 20452 20453 public boolean isOrphaned(String packageName) { 20454 // reader 20455 synchronized (mPackages) { 20456 return mSettings.isOrphaned(packageName); 20457 } 20458 } 20459 20460 @Override 20461 public int getApplicationEnabledSetting(String packageName, int userId) { 20462 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20463 int uid = Binder.getCallingUid(); 20464 enforceCrossUserPermission(uid, userId, 20465 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20466 // reader 20467 synchronized (mPackages) { 20468 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20469 } 20470 } 20471 20472 @Override 20473 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20474 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20475 int uid = Binder.getCallingUid(); 20476 enforceCrossUserPermission(uid, userId, 20477 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20478 // reader 20479 synchronized (mPackages) { 20480 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20481 } 20482 } 20483 20484 @Override 20485 public void enterSafeMode() { 20486 enforceSystemOrRoot("Only the system can request entering safe mode"); 20487 20488 if (!mSystemReady) { 20489 mSafeMode = true; 20490 } 20491 } 20492 20493 @Override 20494 public void systemReady() { 20495 mSystemReady = true; 20496 final ContentResolver resolver = mContext.getContentResolver(); 20497 ContentObserver co = new ContentObserver(mHandler) { 20498 @Override 20499 public void onChange(boolean selfChange) { 20500 mEphemeralAppsDisabled = 20501 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20502 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20503 } 20504 }; 20505 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20506 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20507 false, co, UserHandle.USER_SYSTEM); 20508 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20509 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20510 co.onChange(true); 20511 20512 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20513 // disabled after already being started. 20514 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20515 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20516 20517 // Read the compatibilty setting when the system is ready. 20518 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20519 mContext.getContentResolver(), 20520 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20521 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20522 if (DEBUG_SETTINGS) { 20523 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20524 } 20525 20526 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20527 20528 synchronized (mPackages) { 20529 // Verify that all of the preferred activity components actually 20530 // exist. It is possible for applications to be updated and at 20531 // that point remove a previously declared activity component that 20532 // had been set as a preferred activity. We try to clean this up 20533 // the next time we encounter that preferred activity, but it is 20534 // possible for the user flow to never be able to return to that 20535 // situation so here we do a sanity check to make sure we haven't 20536 // left any junk around. 20537 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20538 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20539 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20540 removed.clear(); 20541 for (PreferredActivity pa : pir.filterSet()) { 20542 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20543 removed.add(pa); 20544 } 20545 } 20546 if (removed.size() > 0) { 20547 for (int r=0; r<removed.size(); r++) { 20548 PreferredActivity pa = removed.get(r); 20549 Slog.w(TAG, "Removing dangling preferred activity: " 20550 + pa.mPref.mComponent); 20551 pir.removeFilter(pa); 20552 } 20553 mSettings.writePackageRestrictionsLPr( 20554 mSettings.mPreferredActivities.keyAt(i)); 20555 } 20556 } 20557 20558 for (int userId : UserManagerService.getInstance().getUserIds()) { 20559 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20560 grantPermissionsUserIds = ArrayUtils.appendInt( 20561 grantPermissionsUserIds, userId); 20562 } 20563 } 20564 } 20565 sUserManager.systemReady(); 20566 20567 // If we upgraded grant all default permissions before kicking off. 20568 for (int userId : grantPermissionsUserIds) { 20569 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20570 } 20571 20572 // If we did not grant default permissions, we preload from this the 20573 // default permission exceptions lazily to ensure we don't hit the 20574 // disk on a new user creation. 20575 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20576 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20577 } 20578 20579 // Kick off any messages waiting for system ready 20580 if (mPostSystemReadyMessages != null) { 20581 for (Message msg : mPostSystemReadyMessages) { 20582 msg.sendToTarget(); 20583 } 20584 mPostSystemReadyMessages = null; 20585 } 20586 20587 // Watch for external volumes that come and go over time 20588 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20589 storage.registerListener(mStorageListener); 20590 20591 mInstallerService.systemReady(); 20592 mPackageDexOptimizer.systemReady(); 20593 20594 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20595 StorageManagerInternal.class); 20596 StorageManagerInternal.addExternalStoragePolicy( 20597 new StorageManagerInternal.ExternalStorageMountPolicy() { 20598 @Override 20599 public int getMountMode(int uid, String packageName) { 20600 if (Process.isIsolated(uid)) { 20601 return Zygote.MOUNT_EXTERNAL_NONE; 20602 } 20603 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20604 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20605 } 20606 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20607 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20608 } 20609 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20610 return Zygote.MOUNT_EXTERNAL_READ; 20611 } 20612 return Zygote.MOUNT_EXTERNAL_WRITE; 20613 } 20614 20615 @Override 20616 public boolean hasExternalStorage(int uid, String packageName) { 20617 return true; 20618 } 20619 }); 20620 20621 // Now that we're mostly running, clean up stale users and apps 20622 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20623 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20624 20625 if (mPrivappPermissionsViolations != null) { 20626 Slog.wtf(TAG,"Signature|privileged permissions not in " 20627 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20628 mPrivappPermissionsViolations = null; 20629 } 20630 } 20631 20632 public void waitForAppDataPrepared() { 20633 if (mPrepareAppDataFuture == null) { 20634 return; 20635 } 20636 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20637 mPrepareAppDataFuture = null; 20638 } 20639 20640 @Override 20641 public boolean isSafeMode() { 20642 return mSafeMode; 20643 } 20644 20645 @Override 20646 public boolean hasSystemUidErrors() { 20647 return mHasSystemUidErrors; 20648 } 20649 20650 static String arrayToString(int[] array) { 20651 StringBuffer buf = new StringBuffer(128); 20652 buf.append('['); 20653 if (array != null) { 20654 for (int i=0; i<array.length; i++) { 20655 if (i > 0) buf.append(", "); 20656 buf.append(array[i]); 20657 } 20658 } 20659 buf.append(']'); 20660 return buf.toString(); 20661 } 20662 20663 static class DumpState { 20664 public static final int DUMP_LIBS = 1 << 0; 20665 public static final int DUMP_FEATURES = 1 << 1; 20666 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20667 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20668 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20669 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20670 public static final int DUMP_PERMISSIONS = 1 << 6; 20671 public static final int DUMP_PACKAGES = 1 << 7; 20672 public static final int DUMP_SHARED_USERS = 1 << 8; 20673 public static final int DUMP_MESSAGES = 1 << 9; 20674 public static final int DUMP_PROVIDERS = 1 << 10; 20675 public static final int DUMP_VERIFIERS = 1 << 11; 20676 public static final int DUMP_PREFERRED = 1 << 12; 20677 public static final int DUMP_PREFERRED_XML = 1 << 13; 20678 public static final int DUMP_KEYSETS = 1 << 14; 20679 public static final int DUMP_VERSION = 1 << 15; 20680 public static final int DUMP_INSTALLS = 1 << 16; 20681 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20682 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20683 public static final int DUMP_FROZEN = 1 << 19; 20684 public static final int DUMP_DEXOPT = 1 << 20; 20685 public static final int DUMP_COMPILER_STATS = 1 << 21; 20686 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20687 20688 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20689 20690 private int mTypes; 20691 20692 private int mOptions; 20693 20694 private boolean mTitlePrinted; 20695 20696 private SharedUserSetting mSharedUser; 20697 20698 public boolean isDumping(int type) { 20699 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20700 return true; 20701 } 20702 20703 return (mTypes & type) != 0; 20704 } 20705 20706 public void setDump(int type) { 20707 mTypes |= type; 20708 } 20709 20710 public boolean isOptionEnabled(int option) { 20711 return (mOptions & option) != 0; 20712 } 20713 20714 public void setOptionEnabled(int option) { 20715 mOptions |= option; 20716 } 20717 20718 public boolean onTitlePrinted() { 20719 final boolean printed = mTitlePrinted; 20720 mTitlePrinted = true; 20721 return printed; 20722 } 20723 20724 public boolean getTitlePrinted() { 20725 return mTitlePrinted; 20726 } 20727 20728 public void setTitlePrinted(boolean enabled) { 20729 mTitlePrinted = enabled; 20730 } 20731 20732 public SharedUserSetting getSharedUser() { 20733 return mSharedUser; 20734 } 20735 20736 public void setSharedUser(SharedUserSetting user) { 20737 mSharedUser = user; 20738 } 20739 } 20740 20741 @Override 20742 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20743 FileDescriptor err, String[] args, ShellCallback callback, 20744 ResultReceiver resultReceiver) { 20745 (new PackageManagerShellCommand(this)).exec( 20746 this, in, out, err, args, callback, resultReceiver); 20747 } 20748 20749 @Override 20750 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20751 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20752 20753 DumpState dumpState = new DumpState(); 20754 boolean fullPreferred = false; 20755 boolean checkin = false; 20756 20757 String packageName = null; 20758 ArraySet<String> permissionNames = null; 20759 20760 int opti = 0; 20761 while (opti < args.length) { 20762 String opt = args[opti]; 20763 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20764 break; 20765 } 20766 opti++; 20767 20768 if ("-a".equals(opt)) { 20769 // Right now we only know how to print all. 20770 } else if ("-h".equals(opt)) { 20771 pw.println("Package manager dump options:"); 20772 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20773 pw.println(" --checkin: dump for a checkin"); 20774 pw.println(" -f: print details of intent filters"); 20775 pw.println(" -h: print this help"); 20776 pw.println(" cmd may be one of:"); 20777 pw.println(" l[ibraries]: list known shared libraries"); 20778 pw.println(" f[eatures]: list device features"); 20779 pw.println(" k[eysets]: print known keysets"); 20780 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20781 pw.println(" perm[issions]: dump permissions"); 20782 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20783 pw.println(" pref[erred]: print preferred package settings"); 20784 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20785 pw.println(" prov[iders]: dump content providers"); 20786 pw.println(" p[ackages]: dump installed packages"); 20787 pw.println(" s[hared-users]: dump shared user IDs"); 20788 pw.println(" m[essages]: print collected runtime messages"); 20789 pw.println(" v[erifiers]: print package verifier info"); 20790 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20791 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20792 pw.println(" version: print database version info"); 20793 pw.println(" write: write current settings now"); 20794 pw.println(" installs: details about install sessions"); 20795 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20796 pw.println(" dexopt: dump dexopt state"); 20797 pw.println(" compiler-stats: dump compiler statistics"); 20798 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20799 pw.println(" <package.name>: info about given package"); 20800 return; 20801 } else if ("--checkin".equals(opt)) { 20802 checkin = true; 20803 } else if ("-f".equals(opt)) { 20804 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20805 } else if ("--proto".equals(opt)) { 20806 dumpProto(fd); 20807 return; 20808 } else { 20809 pw.println("Unknown argument: " + opt + "; use -h for help"); 20810 } 20811 } 20812 20813 // Is the caller requesting to dump a particular piece of data? 20814 if (opti < args.length) { 20815 String cmd = args[opti]; 20816 opti++; 20817 // Is this a package name? 20818 if ("android".equals(cmd) || cmd.contains(".")) { 20819 packageName = cmd; 20820 // When dumping a single package, we always dump all of its 20821 // filter information since the amount of data will be reasonable. 20822 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20823 } else if ("check-permission".equals(cmd)) { 20824 if (opti >= args.length) { 20825 pw.println("Error: check-permission missing permission argument"); 20826 return; 20827 } 20828 String perm = args[opti]; 20829 opti++; 20830 if (opti >= args.length) { 20831 pw.println("Error: check-permission missing package argument"); 20832 return; 20833 } 20834 20835 String pkg = args[opti]; 20836 opti++; 20837 int user = UserHandle.getUserId(Binder.getCallingUid()); 20838 if (opti < args.length) { 20839 try { 20840 user = Integer.parseInt(args[opti]); 20841 } catch (NumberFormatException e) { 20842 pw.println("Error: check-permission user argument is not a number: " 20843 + args[opti]); 20844 return; 20845 } 20846 } 20847 20848 // Normalize package name to handle renamed packages and static libs 20849 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20850 20851 pw.println(checkPermission(perm, pkg, user)); 20852 return; 20853 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20854 dumpState.setDump(DumpState.DUMP_LIBS); 20855 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20856 dumpState.setDump(DumpState.DUMP_FEATURES); 20857 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20858 if (opti >= args.length) { 20859 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20860 | DumpState.DUMP_SERVICE_RESOLVERS 20861 | DumpState.DUMP_RECEIVER_RESOLVERS 20862 | DumpState.DUMP_CONTENT_RESOLVERS); 20863 } else { 20864 while (opti < args.length) { 20865 String name = args[opti]; 20866 if ("a".equals(name) || "activity".equals(name)) { 20867 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20868 } else if ("s".equals(name) || "service".equals(name)) { 20869 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20870 } else if ("r".equals(name) || "receiver".equals(name)) { 20871 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20872 } else if ("c".equals(name) || "content".equals(name)) { 20873 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20874 } else { 20875 pw.println("Error: unknown resolver table type: " + name); 20876 return; 20877 } 20878 opti++; 20879 } 20880 } 20881 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20882 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20883 } else if ("permission".equals(cmd)) { 20884 if (opti >= args.length) { 20885 pw.println("Error: permission requires permission name"); 20886 return; 20887 } 20888 permissionNames = new ArraySet<>(); 20889 while (opti < args.length) { 20890 permissionNames.add(args[opti]); 20891 opti++; 20892 } 20893 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20894 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20895 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20896 dumpState.setDump(DumpState.DUMP_PREFERRED); 20897 } else if ("preferred-xml".equals(cmd)) { 20898 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20899 if (opti < args.length && "--full".equals(args[opti])) { 20900 fullPreferred = true; 20901 opti++; 20902 } 20903 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20904 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20905 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20906 dumpState.setDump(DumpState.DUMP_PACKAGES); 20907 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20908 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20909 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20910 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20911 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20912 dumpState.setDump(DumpState.DUMP_MESSAGES); 20913 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20914 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20915 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20916 || "intent-filter-verifiers".equals(cmd)) { 20917 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20918 } else if ("version".equals(cmd)) { 20919 dumpState.setDump(DumpState.DUMP_VERSION); 20920 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20921 dumpState.setDump(DumpState.DUMP_KEYSETS); 20922 } else if ("installs".equals(cmd)) { 20923 dumpState.setDump(DumpState.DUMP_INSTALLS); 20924 } else if ("frozen".equals(cmd)) { 20925 dumpState.setDump(DumpState.DUMP_FROZEN); 20926 } else if ("dexopt".equals(cmd)) { 20927 dumpState.setDump(DumpState.DUMP_DEXOPT); 20928 } else if ("compiler-stats".equals(cmd)) { 20929 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20930 } else if ("enabled-overlays".equals(cmd)) { 20931 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20932 } else if ("write".equals(cmd)) { 20933 synchronized (mPackages) { 20934 mSettings.writeLPr(); 20935 pw.println("Settings written."); 20936 return; 20937 } 20938 } 20939 } 20940 20941 if (checkin) { 20942 pw.println("vers,1"); 20943 } 20944 20945 // reader 20946 synchronized (mPackages) { 20947 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20948 if (!checkin) { 20949 if (dumpState.onTitlePrinted()) 20950 pw.println(); 20951 pw.println("Database versions:"); 20952 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20953 } 20954 } 20955 20956 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20957 if (!checkin) { 20958 if (dumpState.onTitlePrinted()) 20959 pw.println(); 20960 pw.println("Verifiers:"); 20961 pw.print(" Required: "); 20962 pw.print(mRequiredVerifierPackage); 20963 pw.print(" (uid="); 20964 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20965 UserHandle.USER_SYSTEM)); 20966 pw.println(")"); 20967 } else if (mRequiredVerifierPackage != null) { 20968 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20969 pw.print(","); 20970 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20971 UserHandle.USER_SYSTEM)); 20972 } 20973 } 20974 20975 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20976 packageName == null) { 20977 if (mIntentFilterVerifierComponent != null) { 20978 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20979 if (!checkin) { 20980 if (dumpState.onTitlePrinted()) 20981 pw.println(); 20982 pw.println("Intent Filter Verifier:"); 20983 pw.print(" Using: "); 20984 pw.print(verifierPackageName); 20985 pw.print(" (uid="); 20986 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20987 UserHandle.USER_SYSTEM)); 20988 pw.println(")"); 20989 } else if (verifierPackageName != null) { 20990 pw.print("ifv,"); pw.print(verifierPackageName); 20991 pw.print(","); 20992 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20993 UserHandle.USER_SYSTEM)); 20994 } 20995 } else { 20996 pw.println(); 20997 pw.println("No Intent Filter Verifier available!"); 20998 } 20999 } 21000 21001 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21002 boolean printedHeader = false; 21003 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21004 while (it.hasNext()) { 21005 String libName = it.next(); 21006 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21007 if (versionedLib == null) { 21008 continue; 21009 } 21010 final int versionCount = versionedLib.size(); 21011 for (int i = 0; i < versionCount; i++) { 21012 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21013 if (!checkin) { 21014 if (!printedHeader) { 21015 if (dumpState.onTitlePrinted()) 21016 pw.println(); 21017 pw.println("Libraries:"); 21018 printedHeader = true; 21019 } 21020 pw.print(" "); 21021 } else { 21022 pw.print("lib,"); 21023 } 21024 pw.print(libEntry.info.getName()); 21025 if (libEntry.info.isStatic()) { 21026 pw.print(" version=" + libEntry.info.getVersion()); 21027 } 21028 if (!checkin) { 21029 pw.print(" -> "); 21030 } 21031 if (libEntry.path != null) { 21032 pw.print(" (jar) "); 21033 pw.print(libEntry.path); 21034 } else { 21035 pw.print(" (apk) "); 21036 pw.print(libEntry.apk); 21037 } 21038 pw.println(); 21039 } 21040 } 21041 } 21042 21043 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21044 if (dumpState.onTitlePrinted()) 21045 pw.println(); 21046 if (!checkin) { 21047 pw.println("Features:"); 21048 } 21049 21050 synchronized (mAvailableFeatures) { 21051 for (FeatureInfo feat : mAvailableFeatures.values()) { 21052 if (checkin) { 21053 pw.print("feat,"); 21054 pw.print(feat.name); 21055 pw.print(","); 21056 pw.println(feat.version); 21057 } else { 21058 pw.print(" "); 21059 pw.print(feat.name); 21060 if (feat.version > 0) { 21061 pw.print(" version="); 21062 pw.print(feat.version); 21063 } 21064 pw.println(); 21065 } 21066 } 21067 } 21068 } 21069 21070 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21071 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21072 : "Activity Resolver Table:", " ", packageName, 21073 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21074 dumpState.setTitlePrinted(true); 21075 } 21076 } 21077 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21078 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21079 : "Receiver Resolver Table:", " ", packageName, 21080 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21081 dumpState.setTitlePrinted(true); 21082 } 21083 } 21084 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21085 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21086 : "Service Resolver Table:", " ", packageName, 21087 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21088 dumpState.setTitlePrinted(true); 21089 } 21090 } 21091 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21092 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21093 : "Provider Resolver Table:", " ", packageName, 21094 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21095 dumpState.setTitlePrinted(true); 21096 } 21097 } 21098 21099 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21100 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21101 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21102 int user = mSettings.mPreferredActivities.keyAt(i); 21103 if (pir.dump(pw, 21104 dumpState.getTitlePrinted() 21105 ? "\nPreferred Activities User " + user + ":" 21106 : "Preferred Activities User " + user + ":", " ", 21107 packageName, true, false)) { 21108 dumpState.setTitlePrinted(true); 21109 } 21110 } 21111 } 21112 21113 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21114 pw.flush(); 21115 FileOutputStream fout = new FileOutputStream(fd); 21116 BufferedOutputStream str = new BufferedOutputStream(fout); 21117 XmlSerializer serializer = new FastXmlSerializer(); 21118 try { 21119 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21120 serializer.startDocument(null, true); 21121 serializer.setFeature( 21122 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21123 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21124 serializer.endDocument(); 21125 serializer.flush(); 21126 } catch (IllegalArgumentException e) { 21127 pw.println("Failed writing: " + e); 21128 } catch (IllegalStateException e) { 21129 pw.println("Failed writing: " + e); 21130 } catch (IOException e) { 21131 pw.println("Failed writing: " + e); 21132 } 21133 } 21134 21135 if (!checkin 21136 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21137 && packageName == null) { 21138 pw.println(); 21139 int count = mSettings.mPackages.size(); 21140 if (count == 0) { 21141 pw.println("No applications!"); 21142 pw.println(); 21143 } else { 21144 final String prefix = " "; 21145 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21146 if (allPackageSettings.size() == 0) { 21147 pw.println("No domain preferred apps!"); 21148 pw.println(); 21149 } else { 21150 pw.println("App verification status:"); 21151 pw.println(); 21152 count = 0; 21153 for (PackageSetting ps : allPackageSettings) { 21154 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21155 if (ivi == null || ivi.getPackageName() == null) continue; 21156 pw.println(prefix + "Package: " + ivi.getPackageName()); 21157 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21158 pw.println(prefix + "Status: " + ivi.getStatusString()); 21159 pw.println(); 21160 count++; 21161 } 21162 if (count == 0) { 21163 pw.println(prefix + "No app verification established."); 21164 pw.println(); 21165 } 21166 for (int userId : sUserManager.getUserIds()) { 21167 pw.println("App linkages for user " + userId + ":"); 21168 pw.println(); 21169 count = 0; 21170 for (PackageSetting ps : allPackageSettings) { 21171 final long status = ps.getDomainVerificationStatusForUser(userId); 21172 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21173 && !DEBUG_DOMAIN_VERIFICATION) { 21174 continue; 21175 } 21176 pw.println(prefix + "Package: " + ps.name); 21177 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21178 String statusStr = IntentFilterVerificationInfo. 21179 getStatusStringFromValue(status); 21180 pw.println(prefix + "Status: " + statusStr); 21181 pw.println(); 21182 count++; 21183 } 21184 if (count == 0) { 21185 pw.println(prefix + "No configured app linkages."); 21186 pw.println(); 21187 } 21188 } 21189 } 21190 } 21191 } 21192 21193 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21194 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21195 if (packageName == null && permissionNames == null) { 21196 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 21197 if (iperm == 0) { 21198 if (dumpState.onTitlePrinted()) 21199 pw.println(); 21200 pw.println("AppOp Permissions:"); 21201 } 21202 pw.print(" AppOp Permission "); 21203 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 21204 pw.println(":"); 21205 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 21206 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 21207 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 21208 } 21209 } 21210 } 21211 } 21212 21213 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21214 boolean printedSomething = false; 21215 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21216 if (packageName != null && !packageName.equals(p.info.packageName)) { 21217 continue; 21218 } 21219 if (!printedSomething) { 21220 if (dumpState.onTitlePrinted()) 21221 pw.println(); 21222 pw.println("Registered ContentProviders:"); 21223 printedSomething = true; 21224 } 21225 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21226 pw.print(" "); pw.println(p.toString()); 21227 } 21228 printedSomething = false; 21229 for (Map.Entry<String, PackageParser.Provider> entry : 21230 mProvidersByAuthority.entrySet()) { 21231 PackageParser.Provider p = entry.getValue(); 21232 if (packageName != null && !packageName.equals(p.info.packageName)) { 21233 continue; 21234 } 21235 if (!printedSomething) { 21236 if (dumpState.onTitlePrinted()) 21237 pw.println(); 21238 pw.println("ContentProvider Authorities:"); 21239 printedSomething = true; 21240 } 21241 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21242 pw.print(" "); pw.println(p.toString()); 21243 if (p.info != null && p.info.applicationInfo != null) { 21244 final String appInfo = p.info.applicationInfo.toString(); 21245 pw.print(" applicationInfo="); pw.println(appInfo); 21246 } 21247 } 21248 } 21249 21250 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21251 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21252 } 21253 21254 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21255 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21256 } 21257 21258 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21259 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21260 } 21261 21262 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21263 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21264 } 21265 21266 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21267 // XXX should handle packageName != null by dumping only install data that 21268 // the given package is involved with. 21269 if (dumpState.onTitlePrinted()) pw.println(); 21270 21271 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21272 ipw.println(); 21273 ipw.println("Frozen packages:"); 21274 ipw.increaseIndent(); 21275 if (mFrozenPackages.size() == 0) { 21276 ipw.println("(none)"); 21277 } else { 21278 for (int i = 0; i < mFrozenPackages.size(); i++) { 21279 ipw.println(mFrozenPackages.valueAt(i)); 21280 } 21281 } 21282 ipw.decreaseIndent(); 21283 } 21284 21285 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21286 if (dumpState.onTitlePrinted()) pw.println(); 21287 dumpDexoptStateLPr(pw, packageName); 21288 } 21289 21290 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21291 if (dumpState.onTitlePrinted()) pw.println(); 21292 dumpCompilerStatsLPr(pw, packageName); 21293 } 21294 21295 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 21296 if (dumpState.onTitlePrinted()) pw.println(); 21297 dumpEnabledOverlaysLPr(pw); 21298 } 21299 21300 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21301 if (dumpState.onTitlePrinted()) pw.println(); 21302 mSettings.dumpReadMessagesLPr(pw, dumpState); 21303 21304 pw.println(); 21305 pw.println("Package warning messages:"); 21306 BufferedReader in = null; 21307 String line = null; 21308 try { 21309 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21310 while ((line = in.readLine()) != null) { 21311 if (line.contains("ignored: updated version")) continue; 21312 pw.println(line); 21313 } 21314 } catch (IOException ignored) { 21315 } finally { 21316 IoUtils.closeQuietly(in); 21317 } 21318 } 21319 21320 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21321 BufferedReader in = null; 21322 String line = null; 21323 try { 21324 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21325 while ((line = in.readLine()) != null) { 21326 if (line.contains("ignored: updated version")) continue; 21327 pw.print("msg,"); 21328 pw.println(line); 21329 } 21330 } catch (IOException ignored) { 21331 } finally { 21332 IoUtils.closeQuietly(in); 21333 } 21334 } 21335 } 21336 21337 // PackageInstaller should be called outside of mPackages lock 21338 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21339 // XXX should handle packageName != null by dumping only install data that 21340 // the given package is involved with. 21341 if (dumpState.onTitlePrinted()) pw.println(); 21342 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21343 } 21344 } 21345 21346 private void dumpProto(FileDescriptor fd) { 21347 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21348 21349 synchronized (mPackages) { 21350 final long requiredVerifierPackageToken = 21351 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21352 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21353 proto.write( 21354 PackageServiceDumpProto.PackageShortProto.UID, 21355 getPackageUid( 21356 mRequiredVerifierPackage, 21357 MATCH_DEBUG_TRIAGED_MISSING, 21358 UserHandle.USER_SYSTEM)); 21359 proto.end(requiredVerifierPackageToken); 21360 21361 if (mIntentFilterVerifierComponent != null) { 21362 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21363 final long verifierPackageToken = 21364 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21365 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21366 proto.write( 21367 PackageServiceDumpProto.PackageShortProto.UID, 21368 getPackageUid( 21369 verifierPackageName, 21370 MATCH_DEBUG_TRIAGED_MISSING, 21371 UserHandle.USER_SYSTEM)); 21372 proto.end(verifierPackageToken); 21373 } 21374 21375 dumpSharedLibrariesProto(proto); 21376 dumpFeaturesProto(proto); 21377 mSettings.dumpPackagesProto(proto); 21378 mSettings.dumpSharedUsersProto(proto); 21379 dumpMessagesProto(proto); 21380 } 21381 proto.flush(); 21382 } 21383 21384 private void dumpMessagesProto(ProtoOutputStream proto) { 21385 BufferedReader in = null; 21386 String line = null; 21387 try { 21388 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21389 while ((line = in.readLine()) != null) { 21390 if (line.contains("ignored: updated version")) continue; 21391 proto.write(PackageServiceDumpProto.MESSAGES, line); 21392 } 21393 } catch (IOException ignored) { 21394 } finally { 21395 IoUtils.closeQuietly(in); 21396 } 21397 } 21398 21399 private void dumpFeaturesProto(ProtoOutputStream proto) { 21400 synchronized (mAvailableFeatures) { 21401 final int count = mAvailableFeatures.size(); 21402 for (int i = 0; i < count; i++) { 21403 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21404 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21405 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21406 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21407 proto.end(featureToken); 21408 } 21409 } 21410 } 21411 21412 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21413 final int count = mSharedLibraries.size(); 21414 for (int i = 0; i < count; i++) { 21415 final String libName = mSharedLibraries.keyAt(i); 21416 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21417 if (versionedLib == null) { 21418 continue; 21419 } 21420 final int versionCount = versionedLib.size(); 21421 for (int j = 0; j < versionCount; j++) { 21422 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21423 final long sharedLibraryToken = 21424 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21425 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21426 final boolean isJar = (libEntry.path != null); 21427 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21428 if (isJar) { 21429 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21430 } else { 21431 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21432 } 21433 proto.end(sharedLibraryToken); 21434 } 21435 } 21436 } 21437 21438 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21439 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21440 ipw.println(); 21441 ipw.println("Dexopt state:"); 21442 ipw.increaseIndent(); 21443 Collection<PackageParser.Package> packages = null; 21444 if (packageName != null) { 21445 PackageParser.Package targetPackage = mPackages.get(packageName); 21446 if (targetPackage != null) { 21447 packages = Collections.singletonList(targetPackage); 21448 } else { 21449 ipw.println("Unable to find package: " + packageName); 21450 return; 21451 } 21452 } else { 21453 packages = mPackages.values(); 21454 } 21455 21456 for (PackageParser.Package pkg : packages) { 21457 ipw.println("[" + pkg.packageName + "]"); 21458 ipw.increaseIndent(); 21459 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21460 ipw.decreaseIndent(); 21461 } 21462 } 21463 21464 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21465 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21466 ipw.println(); 21467 ipw.println("Compiler stats:"); 21468 ipw.increaseIndent(); 21469 Collection<PackageParser.Package> packages = null; 21470 if (packageName != null) { 21471 PackageParser.Package targetPackage = mPackages.get(packageName); 21472 if (targetPackage != null) { 21473 packages = Collections.singletonList(targetPackage); 21474 } else { 21475 ipw.println("Unable to find package: " + packageName); 21476 return; 21477 } 21478 } else { 21479 packages = mPackages.values(); 21480 } 21481 21482 for (PackageParser.Package pkg : packages) { 21483 ipw.println("[" + pkg.packageName + "]"); 21484 ipw.increaseIndent(); 21485 21486 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21487 if (stats == null) { 21488 ipw.println("(No recorded stats)"); 21489 } else { 21490 stats.dump(ipw); 21491 } 21492 ipw.decreaseIndent(); 21493 } 21494 } 21495 21496 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21497 pw.println("Enabled overlay paths:"); 21498 final int N = mEnabledOverlayPaths.size(); 21499 for (int i = 0; i < N; i++) { 21500 final int userId = mEnabledOverlayPaths.keyAt(i); 21501 pw.println(String.format(" User %d:", userId)); 21502 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21503 mEnabledOverlayPaths.valueAt(i); 21504 final int M = userSpecificOverlays.size(); 21505 for (int j = 0; j < M; j++) { 21506 final String targetPackageName = userSpecificOverlays.keyAt(j); 21507 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21508 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21509 } 21510 } 21511 } 21512 21513 private String dumpDomainString(String packageName) { 21514 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21515 .getList(); 21516 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21517 21518 ArraySet<String> result = new ArraySet<>(); 21519 if (iviList.size() > 0) { 21520 for (IntentFilterVerificationInfo ivi : iviList) { 21521 for (String host : ivi.getDomains()) { 21522 result.add(host); 21523 } 21524 } 21525 } 21526 if (filters != null && filters.size() > 0) { 21527 for (IntentFilter filter : filters) { 21528 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21529 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21530 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21531 result.addAll(filter.getHostsList()); 21532 } 21533 } 21534 } 21535 21536 StringBuilder sb = new StringBuilder(result.size() * 16); 21537 for (String domain : result) { 21538 if (sb.length() > 0) sb.append(" "); 21539 sb.append(domain); 21540 } 21541 return sb.toString(); 21542 } 21543 21544 // ------- apps on sdcard specific code ------- 21545 static final boolean DEBUG_SD_INSTALL = false; 21546 21547 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21548 21549 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21550 21551 private boolean mMediaMounted = false; 21552 21553 static String getEncryptKey() { 21554 try { 21555 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21556 SD_ENCRYPTION_KEYSTORE_NAME); 21557 if (sdEncKey == null) { 21558 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21559 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21560 if (sdEncKey == null) { 21561 Slog.e(TAG, "Failed to create encryption keys"); 21562 return null; 21563 } 21564 } 21565 return sdEncKey; 21566 } catch (NoSuchAlgorithmException nsae) { 21567 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21568 return null; 21569 } catch (IOException ioe) { 21570 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21571 return null; 21572 } 21573 } 21574 21575 /* 21576 * Update media status on PackageManager. 21577 */ 21578 @Override 21579 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21580 int callingUid = Binder.getCallingUid(); 21581 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21582 throw new SecurityException("Media status can only be updated by the system"); 21583 } 21584 // reader; this apparently protects mMediaMounted, but should probably 21585 // be a different lock in that case. 21586 synchronized (mPackages) { 21587 Log.i(TAG, "Updating external media status from " 21588 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21589 + (mediaStatus ? "mounted" : "unmounted")); 21590 if (DEBUG_SD_INSTALL) 21591 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21592 + ", mMediaMounted=" + mMediaMounted); 21593 if (mediaStatus == mMediaMounted) { 21594 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21595 : 0, -1); 21596 mHandler.sendMessage(msg); 21597 return; 21598 } 21599 mMediaMounted = mediaStatus; 21600 } 21601 // Queue up an async operation since the package installation may take a 21602 // little while. 21603 mHandler.post(new Runnable() { 21604 public void run() { 21605 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21606 } 21607 }); 21608 } 21609 21610 /** 21611 * Called by StorageManagerService when the initial ASECs to scan are available. 21612 * Should block until all the ASEC containers are finished being scanned. 21613 */ 21614 public void scanAvailableAsecs() { 21615 updateExternalMediaStatusInner(true, false, false); 21616 } 21617 21618 /* 21619 * Collect information of applications on external media, map them against 21620 * existing containers and update information based on current mount status. 21621 * Please note that we always have to report status if reportStatus has been 21622 * set to true especially when unloading packages. 21623 */ 21624 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21625 boolean externalStorage) { 21626 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21627 int[] uidArr = EmptyArray.INT; 21628 21629 final String[] list = PackageHelper.getSecureContainerList(); 21630 if (ArrayUtils.isEmpty(list)) { 21631 Log.i(TAG, "No secure containers found"); 21632 } else { 21633 // Process list of secure containers and categorize them 21634 // as active or stale based on their package internal state. 21635 21636 // reader 21637 synchronized (mPackages) { 21638 for (String cid : list) { 21639 // Leave stages untouched for now; installer service owns them 21640 if (PackageInstallerService.isStageName(cid)) continue; 21641 21642 if (DEBUG_SD_INSTALL) 21643 Log.i(TAG, "Processing container " + cid); 21644 String pkgName = getAsecPackageName(cid); 21645 if (pkgName == null) { 21646 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21647 continue; 21648 } 21649 if (DEBUG_SD_INSTALL) 21650 Log.i(TAG, "Looking for pkg : " + pkgName); 21651 21652 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21653 if (ps == null) { 21654 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21655 continue; 21656 } 21657 21658 /* 21659 * Skip packages that are not external if we're unmounting 21660 * external storage. 21661 */ 21662 if (externalStorage && !isMounted && !isExternal(ps)) { 21663 continue; 21664 } 21665 21666 final AsecInstallArgs args = new AsecInstallArgs(cid, 21667 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21668 // The package status is changed only if the code path 21669 // matches between settings and the container id. 21670 if (ps.codePathString != null 21671 && ps.codePathString.startsWith(args.getCodePath())) { 21672 if (DEBUG_SD_INSTALL) { 21673 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21674 + " at code path: " + ps.codePathString); 21675 } 21676 21677 // We do have a valid package installed on sdcard 21678 processCids.put(args, ps.codePathString); 21679 final int uid = ps.appId; 21680 if (uid != -1) { 21681 uidArr = ArrayUtils.appendInt(uidArr, uid); 21682 } 21683 } else { 21684 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21685 + ps.codePathString); 21686 } 21687 } 21688 } 21689 21690 Arrays.sort(uidArr); 21691 } 21692 21693 // Process packages with valid entries. 21694 if (isMounted) { 21695 if (DEBUG_SD_INSTALL) 21696 Log.i(TAG, "Loading packages"); 21697 loadMediaPackages(processCids, uidArr, externalStorage); 21698 startCleaningPackages(); 21699 mInstallerService.onSecureContainersAvailable(); 21700 } else { 21701 if (DEBUG_SD_INSTALL) 21702 Log.i(TAG, "Unloading packages"); 21703 unloadMediaPackages(processCids, uidArr, reportStatus); 21704 } 21705 } 21706 21707 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21708 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21709 final int size = infos.size(); 21710 final String[] packageNames = new String[size]; 21711 final int[] packageUids = new int[size]; 21712 for (int i = 0; i < size; i++) { 21713 final ApplicationInfo info = infos.get(i); 21714 packageNames[i] = info.packageName; 21715 packageUids[i] = info.uid; 21716 } 21717 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21718 finishedReceiver); 21719 } 21720 21721 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21722 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21723 sendResourcesChangedBroadcast(mediaStatus, replacing, 21724 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21725 } 21726 21727 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21728 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21729 int size = pkgList.length; 21730 if (size > 0) { 21731 // Send broadcasts here 21732 Bundle extras = new Bundle(); 21733 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21734 if (uidArr != null) { 21735 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21736 } 21737 if (replacing) { 21738 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21739 } 21740 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21741 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21742 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21743 } 21744 } 21745 21746 /* 21747 * Look at potentially valid container ids from processCids If package 21748 * information doesn't match the one on record or package scanning fails, 21749 * the cid is added to list of removeCids. We currently don't delete stale 21750 * containers. 21751 */ 21752 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21753 boolean externalStorage) { 21754 ArrayList<String> pkgList = new ArrayList<String>(); 21755 Set<AsecInstallArgs> keys = processCids.keySet(); 21756 21757 for (AsecInstallArgs args : keys) { 21758 String codePath = processCids.get(args); 21759 if (DEBUG_SD_INSTALL) 21760 Log.i(TAG, "Loading container : " + args.cid); 21761 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21762 try { 21763 // Make sure there are no container errors first. 21764 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21765 Slog.e(TAG, "Failed to mount cid : " + args.cid 21766 + " when installing from sdcard"); 21767 continue; 21768 } 21769 // Check code path here. 21770 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21771 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21772 + " does not match one in settings " + codePath); 21773 continue; 21774 } 21775 // Parse package 21776 int parseFlags = mDefParseFlags; 21777 if (args.isExternalAsec()) { 21778 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21779 } 21780 if (args.isFwdLocked()) { 21781 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21782 } 21783 21784 synchronized (mInstallLock) { 21785 PackageParser.Package pkg = null; 21786 try { 21787 // Sadly we don't know the package name yet to freeze it 21788 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21789 SCAN_IGNORE_FROZEN, 0, null); 21790 } catch (PackageManagerException e) { 21791 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21792 } 21793 // Scan the package 21794 if (pkg != null) { 21795 /* 21796 * TODO why is the lock being held? doPostInstall is 21797 * called in other places without the lock. This needs 21798 * to be straightened out. 21799 */ 21800 // writer 21801 synchronized (mPackages) { 21802 retCode = PackageManager.INSTALL_SUCCEEDED; 21803 pkgList.add(pkg.packageName); 21804 // Post process args 21805 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21806 pkg.applicationInfo.uid); 21807 } 21808 } else { 21809 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21810 } 21811 } 21812 21813 } finally { 21814 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21815 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21816 } 21817 } 21818 } 21819 // writer 21820 synchronized (mPackages) { 21821 // If the platform SDK has changed since the last time we booted, 21822 // we need to re-grant app permission to catch any new ones that 21823 // appear. This is really a hack, and means that apps can in some 21824 // cases get permissions that the user didn't initially explicitly 21825 // allow... it would be nice to have some better way to handle 21826 // this situation. 21827 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21828 : mSettings.getInternalVersion(); 21829 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21830 : StorageManager.UUID_PRIVATE_INTERNAL; 21831 21832 int updateFlags = UPDATE_PERMISSIONS_ALL; 21833 if (ver.sdkVersion != mSdkVersion) { 21834 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21835 + mSdkVersion + "; regranting permissions for external"); 21836 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21837 } 21838 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21839 21840 // Yay, everything is now upgraded 21841 ver.forceCurrent(); 21842 21843 // can downgrade to reader 21844 // Persist settings 21845 mSettings.writeLPr(); 21846 } 21847 // Send a broadcast to let everyone know we are done processing 21848 if (pkgList.size() > 0) { 21849 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21850 } 21851 } 21852 21853 /* 21854 * Utility method to unload a list of specified containers 21855 */ 21856 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21857 // Just unmount all valid containers. 21858 for (AsecInstallArgs arg : cidArgs) { 21859 synchronized (mInstallLock) { 21860 arg.doPostDeleteLI(false); 21861 } 21862 } 21863 } 21864 21865 /* 21866 * Unload packages mounted on external media. This involves deleting package 21867 * data from internal structures, sending broadcasts about disabled packages, 21868 * gc'ing to free up references, unmounting all secure containers 21869 * corresponding to packages on external media, and posting a 21870 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21871 * that we always have to post this message if status has been requested no 21872 * matter what. 21873 */ 21874 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21875 final boolean reportStatus) { 21876 if (DEBUG_SD_INSTALL) 21877 Log.i(TAG, "unloading media packages"); 21878 ArrayList<String> pkgList = new ArrayList<String>(); 21879 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21880 final Set<AsecInstallArgs> keys = processCids.keySet(); 21881 for (AsecInstallArgs args : keys) { 21882 String pkgName = args.getPackageName(); 21883 if (DEBUG_SD_INSTALL) 21884 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21885 // Delete package internally 21886 PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21887 synchronized (mInstallLock) { 21888 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21889 final boolean res; 21890 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21891 "unloadMediaPackages")) { 21892 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21893 null); 21894 } 21895 if (res) { 21896 pkgList.add(pkgName); 21897 } else { 21898 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21899 failedList.add(args); 21900 } 21901 } 21902 } 21903 21904 // reader 21905 synchronized (mPackages) { 21906 // We didn't update the settings after removing each package; 21907 // write them now for all packages. 21908 mSettings.writeLPr(); 21909 } 21910 21911 // We have to absolutely send UPDATED_MEDIA_STATUS only 21912 // after confirming that all the receivers processed the ordered 21913 // broadcast when packages get disabled, force a gc to clean things up. 21914 // and unload all the containers. 21915 if (pkgList.size() > 0) { 21916 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21917 new IIntentReceiver.Stub() { 21918 public void performReceive(Intent intent, int resultCode, String data, 21919 Bundle extras, boolean ordered, boolean sticky, 21920 int sendingUser) throws RemoteException { 21921 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21922 reportStatus ? 1 : 0, 1, keys); 21923 mHandler.sendMessage(msg); 21924 } 21925 }); 21926 } else { 21927 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21928 keys); 21929 mHandler.sendMessage(msg); 21930 } 21931 } 21932 21933 private void loadPrivatePackages(final VolumeInfo vol) { 21934 mHandler.post(new Runnable() { 21935 @Override 21936 public void run() { 21937 loadPrivatePackagesInner(vol); 21938 } 21939 }); 21940 } 21941 21942 private void loadPrivatePackagesInner(VolumeInfo vol) { 21943 final String volumeUuid = vol.fsUuid; 21944 if (TextUtils.isEmpty(volumeUuid)) { 21945 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21946 return; 21947 } 21948 21949 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21950 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21951 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21952 21953 final VersionInfo ver; 21954 final List<PackageSetting> packages; 21955 synchronized (mPackages) { 21956 ver = mSettings.findOrCreateVersion(volumeUuid); 21957 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21958 } 21959 21960 for (PackageSetting ps : packages) { 21961 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21962 synchronized (mInstallLock) { 21963 final PackageParser.Package pkg; 21964 try { 21965 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21966 loaded.add(pkg.applicationInfo); 21967 21968 } catch (PackageManagerException e) { 21969 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21970 } 21971 21972 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21973 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21974 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21975 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21976 } 21977 } 21978 } 21979 21980 // Reconcile app data for all started/unlocked users 21981 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21982 final UserManager um = mContext.getSystemService(UserManager.class); 21983 UserManagerInternal umInternal = getUserManagerInternal(); 21984 for (UserInfo user : um.getUsers()) { 21985 final int flags; 21986 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21987 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21988 } else if (umInternal.isUserRunning(user.id)) { 21989 flags = StorageManager.FLAG_STORAGE_DE; 21990 } else { 21991 continue; 21992 } 21993 21994 try { 21995 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21996 synchronized (mInstallLock) { 21997 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21998 } 21999 } catch (IllegalStateException e) { 22000 // Device was probably ejected, and we'll process that event momentarily 22001 Slog.w(TAG, "Failed to prepare storage: " + e); 22002 } 22003 } 22004 22005 synchronized (mPackages) { 22006 int updateFlags = UPDATE_PERMISSIONS_ALL; 22007 if (ver.sdkVersion != mSdkVersion) { 22008 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22009 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22010 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 22011 } 22012 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 22013 22014 // Yay, everything is now upgraded 22015 ver.forceCurrent(); 22016 22017 mSettings.writeLPr(); 22018 } 22019 22020 for (PackageFreezer freezer : freezers) { 22021 freezer.close(); 22022 } 22023 22024 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22025 sendResourcesChangedBroadcast(true, false, loaded, null); 22026 } 22027 22028 private void unloadPrivatePackages(final VolumeInfo vol) { 22029 mHandler.post(new Runnable() { 22030 @Override 22031 public void run() { 22032 unloadPrivatePackagesInner(vol); 22033 } 22034 }); 22035 } 22036 22037 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22038 final String volumeUuid = vol.fsUuid; 22039 if (TextUtils.isEmpty(volumeUuid)) { 22040 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22041 return; 22042 } 22043 22044 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22045 synchronized (mInstallLock) { 22046 synchronized (mPackages) { 22047 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22048 for (PackageSetting ps : packages) { 22049 if (ps.pkg == null) continue; 22050 22051 final ApplicationInfo info = ps.pkg.applicationInfo; 22052 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22053 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22054 22055 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22056 "unloadPrivatePackagesInner")) { 22057 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22058 false, null)) { 22059 unloaded.add(info); 22060 } else { 22061 Slog.w(TAG, "Failed to unload " + ps.codePath); 22062 } 22063 } 22064 22065 // Try very hard to release any references to this package 22066 // so we don't risk the system server being killed due to 22067 // open FDs 22068 AttributeCache.instance().removePackage(ps.name); 22069 } 22070 22071 mSettings.writeLPr(); 22072 } 22073 } 22074 22075 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22076 sendResourcesChangedBroadcast(false, false, unloaded, null); 22077 22078 // Try very hard to release any references to this path so we don't risk 22079 // the system server being killed due to open FDs 22080 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22081 22082 for (int i = 0; i < 3; i++) { 22083 System.gc(); 22084 System.runFinalization(); 22085 } 22086 } 22087 22088 private void assertPackageKnown(String volumeUuid, String packageName) 22089 throws PackageManagerException { 22090 synchronized (mPackages) { 22091 // Normalize package name to handle renamed packages 22092 packageName = normalizePackageNameLPr(packageName); 22093 22094 final PackageSetting ps = mSettings.mPackages.get(packageName); 22095 if (ps == null) { 22096 throw new PackageManagerException("Package " + packageName + " is unknown"); 22097 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22098 throw new PackageManagerException( 22099 "Package " + packageName + " found on unknown volume " + volumeUuid 22100 + "; expected volume " + ps.volumeUuid); 22101 } 22102 } 22103 } 22104 22105 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22106 throws PackageManagerException { 22107 synchronized (mPackages) { 22108 // Normalize package name to handle renamed packages 22109 packageName = normalizePackageNameLPr(packageName); 22110 22111 final PackageSetting ps = mSettings.mPackages.get(packageName); 22112 if (ps == null) { 22113 throw new PackageManagerException("Package " + packageName + " is unknown"); 22114 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22115 throw new PackageManagerException( 22116 "Package " + packageName + " found on unknown volume " + volumeUuid 22117 + "; expected volume " + ps.volumeUuid); 22118 } else if (!ps.getInstalled(userId)) { 22119 throw new PackageManagerException( 22120 "Package " + packageName + " not installed for user " + userId); 22121 } 22122 } 22123 } 22124 22125 private List<String> collectAbsoluteCodePaths() { 22126 synchronized (mPackages) { 22127 List<String> codePaths = new ArrayList<>(); 22128 final int packageCount = mSettings.mPackages.size(); 22129 for (int i = 0; i < packageCount; i++) { 22130 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22131 codePaths.add(ps.codePath.getAbsolutePath()); 22132 } 22133 return codePaths; 22134 } 22135 } 22136 22137 /** 22138 * Examine all apps present on given mounted volume, and destroy apps that 22139 * aren't expected, either due to uninstallation or reinstallation on 22140 * another volume. 22141 */ 22142 private void reconcileApps(String volumeUuid) { 22143 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22144 List<File> filesToDelete = null; 22145 22146 final File[] files = FileUtils.listFilesOrEmpty( 22147 Environment.getDataAppDirectory(volumeUuid)); 22148 for (File file : files) { 22149 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22150 && !PackageInstallerService.isStageName(file.getName()); 22151 if (!isPackage) { 22152 // Ignore entries which are not packages 22153 continue; 22154 } 22155 22156 String absolutePath = file.getAbsolutePath(); 22157 22158 boolean pathValid = false; 22159 final int absoluteCodePathCount = absoluteCodePaths.size(); 22160 for (int i = 0; i < absoluteCodePathCount; i++) { 22161 String absoluteCodePath = absoluteCodePaths.get(i); 22162 if (absolutePath.startsWith(absoluteCodePath)) { 22163 pathValid = true; 22164 break; 22165 } 22166 } 22167 22168 if (!pathValid) { 22169 if (filesToDelete == null) { 22170 filesToDelete = new ArrayList<>(); 22171 } 22172 filesToDelete.add(file); 22173 } 22174 } 22175 22176 if (filesToDelete != null) { 22177 final int fileToDeleteCount = filesToDelete.size(); 22178 for (int i = 0; i < fileToDeleteCount; i++) { 22179 File fileToDelete = filesToDelete.get(i); 22180 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22181 synchronized (mInstallLock) { 22182 removeCodePathLI(fileToDelete); 22183 } 22184 } 22185 } 22186 } 22187 22188 /** 22189 * Reconcile all app data for the given user. 22190 * <p> 22191 * Verifies that directories exist and that ownership and labeling is 22192 * correct for all installed apps on all mounted volumes. 22193 */ 22194 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22195 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22196 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22197 final String volumeUuid = vol.getFsUuid(); 22198 synchronized (mInstallLock) { 22199 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22200 } 22201 } 22202 } 22203 22204 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22205 boolean migrateAppData) { 22206 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22207 } 22208 22209 /** 22210 * Reconcile all app data on given mounted volume. 22211 * <p> 22212 * Destroys app data that isn't expected, either due to uninstallation or 22213 * reinstallation on another volume. 22214 * <p> 22215 * Verifies that directories exist and that ownership and labeling is 22216 * correct for all installed apps. 22217 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22218 */ 22219 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22220 boolean migrateAppData, boolean onlyCoreApps) { 22221 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22222 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22223 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22224 22225 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22226 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22227 22228 // First look for stale data that doesn't belong, and check if things 22229 // have changed since we did our last restorecon 22230 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22231 if (StorageManager.isFileEncryptedNativeOrEmulated() 22232 && !StorageManager.isUserKeyUnlocked(userId)) { 22233 throw new RuntimeException( 22234 "Yikes, someone asked us to reconcile CE storage while " + userId 22235 + " was still locked; this would have caused massive data loss!"); 22236 } 22237 22238 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22239 for (File file : files) { 22240 final String packageName = file.getName(); 22241 try { 22242 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22243 } catch (PackageManagerException e) { 22244 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22245 try { 22246 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22247 StorageManager.FLAG_STORAGE_CE, 0); 22248 } catch (InstallerException e2) { 22249 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22250 } 22251 } 22252 } 22253 } 22254 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22255 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22256 for (File file : files) { 22257 final String packageName = file.getName(); 22258 try { 22259 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22260 } catch (PackageManagerException e) { 22261 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22262 try { 22263 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22264 StorageManager.FLAG_STORAGE_DE, 0); 22265 } catch (InstallerException e2) { 22266 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22267 } 22268 } 22269 } 22270 } 22271 22272 // Ensure that data directories are ready to roll for all packages 22273 // installed for this volume and user 22274 final List<PackageSetting> packages; 22275 synchronized (mPackages) { 22276 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22277 } 22278 int preparedCount = 0; 22279 for (PackageSetting ps : packages) { 22280 final String packageName = ps.name; 22281 if (ps.pkg == null) { 22282 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22283 // TODO: might be due to legacy ASEC apps; we should circle back 22284 // and reconcile again once they're scanned 22285 continue; 22286 } 22287 // Skip non-core apps if requested 22288 if (onlyCoreApps && !ps.pkg.coreApp) { 22289 result.add(packageName); 22290 continue; 22291 } 22292 22293 if (ps.getInstalled(userId)) { 22294 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22295 preparedCount++; 22296 } 22297 } 22298 22299 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22300 return result; 22301 } 22302 22303 /** 22304 * Prepare app data for the given app just after it was installed or 22305 * upgraded. This method carefully only touches users that it's installed 22306 * for, and it forces a restorecon to handle any seinfo changes. 22307 * <p> 22308 * Verifies that directories exist and that ownership and labeling is 22309 * correct for all installed apps. If there is an ownership mismatch, it 22310 * will try recovering system apps by wiping data; third-party app data is 22311 * left intact. 22312 * <p> 22313 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22314 */ 22315 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22316 final PackageSetting ps; 22317 synchronized (mPackages) { 22318 ps = mSettings.mPackages.get(pkg.packageName); 22319 mSettings.writeKernelMappingLPr(ps); 22320 } 22321 22322 final UserManager um = mContext.getSystemService(UserManager.class); 22323 UserManagerInternal umInternal = getUserManagerInternal(); 22324 for (UserInfo user : um.getUsers()) { 22325 final int flags; 22326 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22327 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22328 } else if (umInternal.isUserRunning(user.id)) { 22329 flags = StorageManager.FLAG_STORAGE_DE; 22330 } else { 22331 continue; 22332 } 22333 22334 if (ps.getInstalled(user.id)) { 22335 // TODO: when user data is locked, mark that we're still dirty 22336 prepareAppDataLIF(pkg, user.id, flags); 22337 } 22338 } 22339 } 22340 22341 /** 22342 * Prepare app data for the given app. 22343 * <p> 22344 * Verifies that directories exist and that ownership and labeling is 22345 * correct for all installed apps. If there is an ownership mismatch, this 22346 * will try recovering system apps by wiping data; third-party app data is 22347 * left intact. 22348 */ 22349 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22350 if (pkg == null) { 22351 Slog.wtf(TAG, "Package was null!", new Throwable()); 22352 return; 22353 } 22354 prepareAppDataLeafLIF(pkg, userId, flags); 22355 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22356 for (int i = 0; i < childCount; i++) { 22357 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22358 } 22359 } 22360 22361 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22362 boolean maybeMigrateAppData) { 22363 prepareAppDataLIF(pkg, userId, flags); 22364 22365 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22366 // We may have just shuffled around app data directories, so 22367 // prepare them one more time 22368 prepareAppDataLIF(pkg, userId, flags); 22369 } 22370 } 22371 22372 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22373 if (DEBUG_APP_DATA) { 22374 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22375 + Integer.toHexString(flags)); 22376 } 22377 22378 final String volumeUuid = pkg.volumeUuid; 22379 final String packageName = pkg.packageName; 22380 final ApplicationInfo app = pkg.applicationInfo; 22381 final int appId = UserHandle.getAppId(app.uid); 22382 22383 Preconditions.checkNotNull(app.seInfo); 22384 22385 long ceDataInode = -1; 22386 try { 22387 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22388 appId, app.seInfo, app.targetSdkVersion); 22389 } catch (InstallerException e) { 22390 if (app.isSystemApp()) { 22391 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22392 + ", but trying to recover: " + e); 22393 destroyAppDataLeafLIF(pkg, userId, flags); 22394 try { 22395 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22396 appId, app.seInfo, app.targetSdkVersion); 22397 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22398 } catch (InstallerException e2) { 22399 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22400 } 22401 } else { 22402 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22403 } 22404 } 22405 22406 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22407 // TODO: mark this structure as dirty so we persist it! 22408 synchronized (mPackages) { 22409 final PackageSetting ps = mSettings.mPackages.get(packageName); 22410 if (ps != null) { 22411 ps.setCeDataInode(ceDataInode, userId); 22412 } 22413 } 22414 } 22415 22416 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22417 } 22418 22419 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22420 if (pkg == null) { 22421 Slog.wtf(TAG, "Package was null!", new Throwable()); 22422 return; 22423 } 22424 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22425 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22426 for (int i = 0; i < childCount; i++) { 22427 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22428 } 22429 } 22430 22431 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22432 final String volumeUuid = pkg.volumeUuid; 22433 final String packageName = pkg.packageName; 22434 final ApplicationInfo app = pkg.applicationInfo; 22435 22436 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22437 // Create a native library symlink only if we have native libraries 22438 // and if the native libraries are 32 bit libraries. We do not provide 22439 // this symlink for 64 bit libraries. 22440 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22441 final String nativeLibPath = app.nativeLibraryDir; 22442 try { 22443 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22444 nativeLibPath, userId); 22445 } catch (InstallerException e) { 22446 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22447 } 22448 } 22449 } 22450 } 22451 22452 /** 22453 * For system apps on non-FBE devices, this method migrates any existing 22454 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22455 * requested by the app. 22456 */ 22457 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22458 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22459 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22460 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22461 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22462 try { 22463 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22464 storageTarget); 22465 } catch (InstallerException e) { 22466 logCriticalInfo(Log.WARN, 22467 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22468 } 22469 return true; 22470 } else { 22471 return false; 22472 } 22473 } 22474 22475 public PackageFreezer freezePackage(String packageName, String killReason) { 22476 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22477 } 22478 22479 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22480 return new PackageFreezer(packageName, userId, killReason); 22481 } 22482 22483 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22484 String killReason) { 22485 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22486 } 22487 22488 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22489 String killReason) { 22490 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22491 return new PackageFreezer(); 22492 } else { 22493 return freezePackage(packageName, userId, killReason); 22494 } 22495 } 22496 22497 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22498 String killReason) { 22499 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22500 } 22501 22502 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22503 String killReason) { 22504 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22505 return new PackageFreezer(); 22506 } else { 22507 return freezePackage(packageName, userId, killReason); 22508 } 22509 } 22510 22511 /** 22512 * Class that freezes and kills the given package upon creation, and 22513 * unfreezes it upon closing. This is typically used when doing surgery on 22514 * app code/data to prevent the app from running while you're working. 22515 */ 22516 private class PackageFreezer implements AutoCloseable { 22517 private final String mPackageName; 22518 private final PackageFreezer[] mChildren; 22519 22520 private final boolean mWeFroze; 22521 22522 private final AtomicBoolean mClosed = new AtomicBoolean(); 22523 private final CloseGuard mCloseGuard = CloseGuard.get(); 22524 22525 /** 22526 * Create and return a stub freezer that doesn't actually do anything, 22527 * typically used when someone requested 22528 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22529 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22530 */ 22531 public PackageFreezer() { 22532 mPackageName = null; 22533 mChildren = null; 22534 mWeFroze = false; 22535 mCloseGuard.open("close"); 22536 } 22537 22538 public PackageFreezer(String packageName, int userId, String killReason) { 22539 synchronized (mPackages) { 22540 mPackageName = packageName; 22541 mWeFroze = mFrozenPackages.add(mPackageName); 22542 22543 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22544 if (ps != null) { 22545 killApplication(ps.name, ps.appId, userId, killReason); 22546 } 22547 22548 final PackageParser.Package p = mPackages.get(packageName); 22549 if (p != null && p.childPackages != null) { 22550 final int N = p.childPackages.size(); 22551 mChildren = new PackageFreezer[N]; 22552 for (int i = 0; i < N; i++) { 22553 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22554 userId, killReason); 22555 } 22556 } else { 22557 mChildren = null; 22558 } 22559 } 22560 mCloseGuard.open("close"); 22561 } 22562 22563 @Override 22564 protected void finalize() throws Throwable { 22565 try { 22566 mCloseGuard.warnIfOpen(); 22567 close(); 22568 } finally { 22569 super.finalize(); 22570 } 22571 } 22572 22573 @Override 22574 public void close() { 22575 mCloseGuard.close(); 22576 if (mClosed.compareAndSet(false, true)) { 22577 synchronized (mPackages) { 22578 if (mWeFroze) { 22579 mFrozenPackages.remove(mPackageName); 22580 } 22581 22582 if (mChildren != null) { 22583 for (PackageFreezer freezer : mChildren) { 22584 freezer.close(); 22585 } 22586 } 22587 } 22588 } 22589 } 22590 } 22591 22592 /** 22593 * Verify that given package is currently frozen. 22594 */ 22595 private void checkPackageFrozen(String packageName) { 22596 synchronized (mPackages) { 22597 if (!mFrozenPackages.contains(packageName)) { 22598 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22599 } 22600 } 22601 } 22602 22603 @Override 22604 public int movePackage(final String packageName, final String volumeUuid) { 22605 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22606 22607 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22608 final int moveId = mNextMoveId.getAndIncrement(); 22609 mHandler.post(new Runnable() { 22610 @Override 22611 public void run() { 22612 try { 22613 movePackageInternal(packageName, volumeUuid, moveId, user); 22614 } catch (PackageManagerException e) { 22615 Slog.w(TAG, "Failed to move " + packageName, e); 22616 mMoveCallbacks.notifyStatusChanged(moveId, 22617 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22618 } 22619 } 22620 }); 22621 return moveId; 22622 } 22623 22624 private void movePackageInternal(final String packageName, final String volumeUuid, 22625 final int moveId, UserHandle user) throws PackageManagerException { 22626 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22627 final PackageManager pm = mContext.getPackageManager(); 22628 22629 final boolean currentAsec; 22630 final String currentVolumeUuid; 22631 final File codeFile; 22632 final String installerPackageName; 22633 final String packageAbiOverride; 22634 final int appId; 22635 final String seinfo; 22636 final String label; 22637 final int targetSdkVersion; 22638 final PackageFreezer freezer; 22639 final int[] installedUserIds; 22640 22641 // reader 22642 synchronized (mPackages) { 22643 final PackageParser.Package pkg = mPackages.get(packageName); 22644 final PackageSetting ps = mSettings.mPackages.get(packageName); 22645 if (pkg == null || ps == null) { 22646 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22647 } 22648 22649 if (pkg.applicationInfo.isSystemApp()) { 22650 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22651 "Cannot move system application"); 22652 } 22653 22654 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22655 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22656 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22657 if (isInternalStorage && !allow3rdPartyOnInternal) { 22658 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22659 "3rd party apps are not allowed on internal storage"); 22660 } 22661 22662 if (pkg.applicationInfo.isExternalAsec()) { 22663 currentAsec = true; 22664 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22665 } else if (pkg.applicationInfo.isForwardLocked()) { 22666 currentAsec = true; 22667 currentVolumeUuid = "forward_locked"; 22668 } else { 22669 currentAsec = false; 22670 currentVolumeUuid = ps.volumeUuid; 22671 22672 final File probe = new File(pkg.codePath); 22673 final File probeOat = new File(probe, "oat"); 22674 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22675 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22676 "Move only supported for modern cluster style installs"); 22677 } 22678 } 22679 22680 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22681 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22682 "Package already moved to " + volumeUuid); 22683 } 22684 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22685 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22686 "Device admin cannot be moved"); 22687 } 22688 22689 if (mFrozenPackages.contains(packageName)) { 22690 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22691 "Failed to move already frozen package"); 22692 } 22693 22694 codeFile = new File(pkg.codePath); 22695 installerPackageName = ps.installerPackageName; 22696 packageAbiOverride = ps.cpuAbiOverrideString; 22697 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22698 seinfo = pkg.applicationInfo.seInfo; 22699 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22700 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22701 freezer = freezePackage(packageName, "movePackageInternal"); 22702 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22703 } 22704 22705 final Bundle extras = new Bundle(); 22706 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22707 extras.putString(Intent.EXTRA_TITLE, label); 22708 mMoveCallbacks.notifyCreated(moveId, extras); 22709 22710 int installFlags; 22711 final boolean moveCompleteApp; 22712 final File measurePath; 22713 22714 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22715 installFlags = INSTALL_INTERNAL; 22716 moveCompleteApp = !currentAsec; 22717 measurePath = Environment.getDataAppDirectory(volumeUuid); 22718 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22719 installFlags = INSTALL_EXTERNAL; 22720 moveCompleteApp = false; 22721 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22722 } else { 22723 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22724 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22725 || !volume.isMountedWritable()) { 22726 freezer.close(); 22727 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22728 "Move location not mounted private volume"); 22729 } 22730 22731 Preconditions.checkState(!currentAsec); 22732 22733 installFlags = INSTALL_INTERNAL; 22734 moveCompleteApp = true; 22735 measurePath = Environment.getDataAppDirectory(volumeUuid); 22736 } 22737 22738 final PackageStats stats = new PackageStats(null, -1); 22739 synchronized (mInstaller) { 22740 for (int userId : installedUserIds) { 22741 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22742 freezer.close(); 22743 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22744 "Failed to measure package size"); 22745 } 22746 } 22747 } 22748 22749 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22750 + stats.dataSize); 22751 22752 final long startFreeBytes = measurePath.getUsableSpace(); 22753 final long sizeBytes; 22754 if (moveCompleteApp) { 22755 sizeBytes = stats.codeSize + stats.dataSize; 22756 } else { 22757 sizeBytes = stats.codeSize; 22758 } 22759 22760 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22761 freezer.close(); 22762 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22763 "Not enough free space to move"); 22764 } 22765 22766 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22767 22768 final CountDownLatch installedLatch = new CountDownLatch(1); 22769 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22770 @Override 22771 public void onUserActionRequired(Intent intent) throws RemoteException { 22772 throw new IllegalStateException(); 22773 } 22774 22775 @Override 22776 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22777 Bundle extras) throws RemoteException { 22778 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22779 + PackageManager.installStatusToString(returnCode, msg)); 22780 22781 installedLatch.countDown(); 22782 freezer.close(); 22783 22784 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22785 switch (status) { 22786 case PackageInstaller.STATUS_SUCCESS: 22787 mMoveCallbacks.notifyStatusChanged(moveId, 22788 PackageManager.MOVE_SUCCEEDED); 22789 break; 22790 case PackageInstaller.STATUS_FAILURE_STORAGE: 22791 mMoveCallbacks.notifyStatusChanged(moveId, 22792 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22793 break; 22794 default: 22795 mMoveCallbacks.notifyStatusChanged(moveId, 22796 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22797 break; 22798 } 22799 } 22800 }; 22801 22802 final MoveInfo move; 22803 if (moveCompleteApp) { 22804 // Kick off a thread to report progress estimates 22805 new Thread() { 22806 @Override 22807 public void run() { 22808 while (true) { 22809 try { 22810 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22811 break; 22812 } 22813 } catch (InterruptedException ignored) { 22814 } 22815 22816 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22817 final int progress = 10 + (int) MathUtils.constrain( 22818 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22819 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22820 } 22821 } 22822 }.start(); 22823 22824 final String dataAppName = codeFile.getName(); 22825 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22826 dataAppName, appId, seinfo, targetSdkVersion); 22827 } else { 22828 move = null; 22829 } 22830 22831 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22832 22833 final Message msg = mHandler.obtainMessage(INIT_COPY); 22834 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22835 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22836 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22837 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22838 PackageManager.INSTALL_REASON_UNKNOWN); 22839 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22840 msg.obj = params; 22841 22842 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22843 System.identityHashCode(msg.obj)); 22844 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22845 System.identityHashCode(msg.obj)); 22846 22847 mHandler.sendMessage(msg); 22848 } 22849 22850 @Override 22851 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22852 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22853 22854 final int realMoveId = mNextMoveId.getAndIncrement(); 22855 final Bundle extras = new Bundle(); 22856 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22857 mMoveCallbacks.notifyCreated(realMoveId, extras); 22858 22859 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22860 @Override 22861 public void onCreated(int moveId, Bundle extras) { 22862 // Ignored 22863 } 22864 22865 @Override 22866 public void onStatusChanged(int moveId, int status, long estMillis) { 22867 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22868 } 22869 }; 22870 22871 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22872 storage.setPrimaryStorageUuid(volumeUuid, callback); 22873 return realMoveId; 22874 } 22875 22876 @Override 22877 public int getMoveStatus(int moveId) { 22878 mContext.enforceCallingOrSelfPermission( 22879 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22880 return mMoveCallbacks.mLastStatus.get(moveId); 22881 } 22882 22883 @Override 22884 public void registerMoveCallback(IPackageMoveObserver callback) { 22885 mContext.enforceCallingOrSelfPermission( 22886 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22887 mMoveCallbacks.register(callback); 22888 } 22889 22890 @Override 22891 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22892 mContext.enforceCallingOrSelfPermission( 22893 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22894 mMoveCallbacks.unregister(callback); 22895 } 22896 22897 @Override 22898 public boolean setInstallLocation(int loc) { 22899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22900 null); 22901 if (getInstallLocation() == loc) { 22902 return true; 22903 } 22904 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22905 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22906 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22907 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22908 return true; 22909 } 22910 return false; 22911 } 22912 22913 @Override 22914 public int getInstallLocation() { 22915 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22916 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22917 PackageHelper.APP_INSTALL_AUTO); 22918 } 22919 22920 /** Called by UserManagerService */ 22921 void cleanUpUser(UserManagerService userManager, int userHandle) { 22922 synchronized (mPackages) { 22923 mDirtyUsers.remove(userHandle); 22924 mUserNeedsBadging.delete(userHandle); 22925 mSettings.removeUserLPw(userHandle); 22926 mPendingBroadcasts.remove(userHandle); 22927 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22928 removeUnusedPackagesLPw(userManager, userHandle); 22929 } 22930 } 22931 22932 /** 22933 * We're removing userHandle and would like to remove any downloaded packages 22934 * that are no longer in use by any other user. 22935 * @param userHandle the user being removed 22936 */ 22937 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22938 final boolean DEBUG_CLEAN_APKS = false; 22939 int [] users = userManager.getUserIds(); 22940 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22941 while (psit.hasNext()) { 22942 PackageSetting ps = psit.next(); 22943 if (ps.pkg == null) { 22944 continue; 22945 } 22946 final String packageName = ps.pkg.packageName; 22947 // Skip over if system app 22948 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22949 continue; 22950 } 22951 if (DEBUG_CLEAN_APKS) { 22952 Slog.i(TAG, "Checking package " + packageName); 22953 } 22954 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22955 if (keep) { 22956 if (DEBUG_CLEAN_APKS) { 22957 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22958 } 22959 } else { 22960 for (int i = 0; i < users.length; i++) { 22961 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22962 keep = true; 22963 if (DEBUG_CLEAN_APKS) { 22964 Slog.i(TAG, " Keeping package " + packageName + " for user " 22965 + users[i]); 22966 } 22967 break; 22968 } 22969 } 22970 } 22971 if (!keep) { 22972 if (DEBUG_CLEAN_APKS) { 22973 Slog.i(TAG, " Removing package " + packageName); 22974 } 22975 mHandler.post(new Runnable() { 22976 public void run() { 22977 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22978 userHandle, 0); 22979 } //end run 22980 }); 22981 } 22982 } 22983 } 22984 22985 /** Called by UserManagerService */ 22986 void createNewUser(int userId, String[] disallowedPackages) { 22987 synchronized (mInstallLock) { 22988 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22989 } 22990 synchronized (mPackages) { 22991 scheduleWritePackageRestrictionsLocked(userId); 22992 scheduleWritePackageListLocked(userId); 22993 applyFactoryDefaultBrowserLPw(userId); 22994 primeDomainVerificationsLPw(userId); 22995 } 22996 } 22997 22998 void onNewUserCreated(final int userId) { 22999 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23000 // If permission review for legacy apps is required, we represent 23001 // dagerous permissions for such apps as always granted runtime 23002 // permissions to keep per user flag state whether review is needed. 23003 // Hence, if a new user is added we have to propagate dangerous 23004 // permission grants for these legacy apps. 23005 if (mPermissionReviewRequired) { 23006 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 23007 | UPDATE_PERMISSIONS_REPLACE_ALL); 23008 } 23009 } 23010 23011 @Override 23012 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23013 mContext.enforceCallingOrSelfPermission( 23014 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23015 "Only package verification agents can read the verifier device identity"); 23016 23017 synchronized (mPackages) { 23018 return mSettings.getVerifierDeviceIdentityLPw(); 23019 } 23020 } 23021 23022 @Override 23023 public void setPermissionEnforced(String permission, boolean enforced) { 23024 // TODO: Now that we no longer change GID for storage, this should to away. 23025 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23026 "setPermissionEnforced"); 23027 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23028 synchronized (mPackages) { 23029 if (mSettings.mReadExternalStorageEnforced == null 23030 || mSettings.mReadExternalStorageEnforced != enforced) { 23031 mSettings.mReadExternalStorageEnforced = enforced; 23032 mSettings.writeLPr(); 23033 } 23034 } 23035 // kill any non-foreground processes so we restart them and 23036 // grant/revoke the GID. 23037 final IActivityManager am = ActivityManager.getService(); 23038 if (am != null) { 23039 final long token = Binder.clearCallingIdentity(); 23040 try { 23041 am.killProcessesBelowForeground("setPermissionEnforcement"); 23042 } catch (RemoteException e) { 23043 } finally { 23044 Binder.restoreCallingIdentity(token); 23045 } 23046 } 23047 } else { 23048 throw new IllegalArgumentException("No selective enforcement for " + permission); 23049 } 23050 } 23051 23052 @Override 23053 @Deprecated 23054 public boolean isPermissionEnforced(String permission) { 23055 return true; 23056 } 23057 23058 @Override 23059 public boolean isStorageLow() { 23060 final long token = Binder.clearCallingIdentity(); 23061 try { 23062 final DeviceStorageMonitorInternal 23063 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23064 if (dsm != null) { 23065 return dsm.isMemoryLow(); 23066 } else { 23067 return false; 23068 } 23069 } finally { 23070 Binder.restoreCallingIdentity(token); 23071 } 23072 } 23073 23074 @Override 23075 public IPackageInstaller getPackageInstaller() { 23076 return mInstallerService; 23077 } 23078 23079 private boolean userNeedsBadging(int userId) { 23080 int index = mUserNeedsBadging.indexOfKey(userId); 23081 if (index < 0) { 23082 final UserInfo userInfo; 23083 final long token = Binder.clearCallingIdentity(); 23084 try { 23085 userInfo = sUserManager.getUserInfo(userId); 23086 } finally { 23087 Binder.restoreCallingIdentity(token); 23088 } 23089 final boolean b; 23090 if (userInfo != null && userInfo.isManagedProfile()) { 23091 b = true; 23092 } else { 23093 b = false; 23094 } 23095 mUserNeedsBadging.put(userId, b); 23096 return b; 23097 } 23098 return mUserNeedsBadging.valueAt(index); 23099 } 23100 23101 @Override 23102 public KeySet getKeySetByAlias(String packageName, String alias) { 23103 if (packageName == null || alias == null) { 23104 return null; 23105 } 23106 synchronized(mPackages) { 23107 final PackageParser.Package pkg = mPackages.get(packageName); 23108 if (pkg == null) { 23109 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23110 throw new IllegalArgumentException("Unknown package: " + packageName); 23111 } 23112 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23113 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23114 } 23115 } 23116 23117 @Override 23118 public KeySet getSigningKeySet(String packageName) { 23119 if (packageName == null) { 23120 return null; 23121 } 23122 synchronized(mPackages) { 23123 final PackageParser.Package pkg = mPackages.get(packageName); 23124 if (pkg == null) { 23125 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23126 throw new IllegalArgumentException("Unknown package: " + packageName); 23127 } 23128 if (pkg.applicationInfo.uid != Binder.getCallingUid() 23129 && Process.SYSTEM_UID != Binder.getCallingUid()) { 23130 throw new SecurityException("May not access signing KeySet of other apps."); 23131 } 23132 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23133 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23134 } 23135 } 23136 23137 @Override 23138 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23139 if (packageName == null || ks == null) { 23140 return false; 23141 } 23142 synchronized(mPackages) { 23143 final PackageParser.Package pkg = mPackages.get(packageName); 23144 if (pkg == null) { 23145 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23146 throw new IllegalArgumentException("Unknown package: " + packageName); 23147 } 23148 IBinder ksh = ks.getToken(); 23149 if (ksh instanceof KeySetHandle) { 23150 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23151 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23152 } 23153 return false; 23154 } 23155 } 23156 23157 @Override 23158 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23159 if (packageName == null || ks == null) { 23160 return false; 23161 } 23162 synchronized(mPackages) { 23163 final PackageParser.Package pkg = mPackages.get(packageName); 23164 if (pkg == null) { 23165 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23166 throw new IllegalArgumentException("Unknown package: " + packageName); 23167 } 23168 IBinder ksh = ks.getToken(); 23169 if (ksh instanceof KeySetHandle) { 23170 KeySetManagerService ksms = mSettings.mKeySetManagerService; 23171 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23172 } 23173 return false; 23174 } 23175 } 23176 23177 private void deletePackageIfUnusedLPr(final String packageName) { 23178 PackageSetting ps = mSettings.mPackages.get(packageName); 23179 if (ps == null) { 23180 return; 23181 } 23182 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23183 // TODO Implement atomic delete if package is unused 23184 // It is currently possible that the package will be deleted even if it is installed 23185 // after this method returns. 23186 mHandler.post(new Runnable() { 23187 public void run() { 23188 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23189 0, PackageManager.DELETE_ALL_USERS); 23190 } 23191 }); 23192 } 23193 } 23194 23195 /** 23196 * Check and throw if the given before/after packages would be considered a 23197 * downgrade. 23198 */ 23199 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23200 throws PackageManagerException { 23201 if (after.versionCode < before.mVersionCode) { 23202 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23203 "Update version code " + after.versionCode + " is older than current " 23204 + before.mVersionCode); 23205 } else if (after.versionCode == before.mVersionCode) { 23206 if (after.baseRevisionCode < before.baseRevisionCode) { 23207 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23208 "Update base revision code " + after.baseRevisionCode 23209 + " is older than current " + before.baseRevisionCode); 23210 } 23211 23212 if (!ArrayUtils.isEmpty(after.splitNames)) { 23213 for (int i = 0; i < after.splitNames.length; i++) { 23214 final String splitName = after.splitNames[i]; 23215 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23216 if (j != -1) { 23217 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23218 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23219 "Update split " + splitName + " revision code " 23220 + after.splitRevisionCodes[i] + " is older than current " 23221 + before.splitRevisionCodes[j]); 23222 } 23223 } 23224 } 23225 } 23226 } 23227 } 23228 23229 private static class MoveCallbacks extends Handler { 23230 private static final int MSG_CREATED = 1; 23231 private static final int MSG_STATUS_CHANGED = 2; 23232 23233 private final RemoteCallbackList<IPackageMoveObserver> 23234 mCallbacks = new RemoteCallbackList<>(); 23235 23236 private final SparseIntArray mLastStatus = new SparseIntArray(); 23237 23238 public MoveCallbacks(Looper looper) { 23239 super(looper); 23240 } 23241 23242 public void register(IPackageMoveObserver callback) { 23243 mCallbacks.register(callback); 23244 } 23245 23246 public void unregister(IPackageMoveObserver callback) { 23247 mCallbacks.unregister(callback); 23248 } 23249 23250 @Override 23251 public void handleMessage(Message msg) { 23252 final SomeArgs args = (SomeArgs) msg.obj; 23253 final int n = mCallbacks.beginBroadcast(); 23254 for (int i = 0; i < n; i++) { 23255 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23256 try { 23257 invokeCallback(callback, msg.what, args); 23258 } catch (RemoteException ignored) { 23259 } 23260 } 23261 mCallbacks.finishBroadcast(); 23262 args.recycle(); 23263 } 23264 23265 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23266 throws RemoteException { 23267 switch (what) { 23268 case MSG_CREATED: { 23269 callback.onCreated(args.argi1, (Bundle) args.arg2); 23270 break; 23271 } 23272 case MSG_STATUS_CHANGED: { 23273 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23274 break; 23275 } 23276 } 23277 } 23278 23279 private void notifyCreated(int moveId, Bundle extras) { 23280 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23281 23282 final SomeArgs args = SomeArgs.obtain(); 23283 args.argi1 = moveId; 23284 args.arg2 = extras; 23285 obtainMessage(MSG_CREATED, args).sendToTarget(); 23286 } 23287 23288 private void notifyStatusChanged(int moveId, int status) { 23289 notifyStatusChanged(moveId, status, -1); 23290 } 23291 23292 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23293 Slog.v(TAG, "Move " + moveId + " status " + status); 23294 23295 final SomeArgs args = SomeArgs.obtain(); 23296 args.argi1 = moveId; 23297 args.argi2 = status; 23298 args.arg3 = estMillis; 23299 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23300 23301 synchronized (mLastStatus) { 23302 mLastStatus.put(moveId, status); 23303 } 23304 } 23305 } 23306 23307 private final static class OnPermissionChangeListeners extends Handler { 23308 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23309 23310 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23311 new RemoteCallbackList<>(); 23312 23313 public OnPermissionChangeListeners(Looper looper) { 23314 super(looper); 23315 } 23316 23317 @Override 23318 public void handleMessage(Message msg) { 23319 switch (msg.what) { 23320 case MSG_ON_PERMISSIONS_CHANGED: { 23321 final int uid = msg.arg1; 23322 handleOnPermissionsChanged(uid); 23323 } break; 23324 } 23325 } 23326 23327 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23328 mPermissionListeners.register(listener); 23329 23330 } 23331 23332 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23333 mPermissionListeners.unregister(listener); 23334 } 23335 23336 public void onPermissionsChanged(int uid) { 23337 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23338 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23339 } 23340 } 23341 23342 private void handleOnPermissionsChanged(int uid) { 23343 final int count = mPermissionListeners.beginBroadcast(); 23344 try { 23345 for (int i = 0; i < count; i++) { 23346 IOnPermissionsChangeListener callback = mPermissionListeners 23347 .getBroadcastItem(i); 23348 try { 23349 callback.onPermissionsChanged(uid); 23350 } catch (RemoteException e) { 23351 Log.e(TAG, "Permission listener is dead", e); 23352 } 23353 } 23354 } finally { 23355 mPermissionListeners.finishBroadcast(); 23356 } 23357 } 23358 } 23359 23360 private class PackageManagerInternalImpl extends PackageManagerInternal { 23361 @Override 23362 public void setLocationPackagesProvider(PackagesProvider provider) { 23363 synchronized (mPackages) { 23364 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 23365 } 23366 } 23367 23368 @Override 23369 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23370 synchronized (mPackages) { 23371 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 23372 } 23373 } 23374 23375 @Override 23376 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23377 synchronized (mPackages) { 23378 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 23379 } 23380 } 23381 23382 @Override 23383 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23384 synchronized (mPackages) { 23385 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 23386 } 23387 } 23388 23389 @Override 23390 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23391 synchronized (mPackages) { 23392 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 23393 } 23394 } 23395 23396 @Override 23397 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23398 synchronized (mPackages) { 23399 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 23400 } 23401 } 23402 23403 @Override 23404 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23405 synchronized (mPackages) { 23406 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23407 packageName, userId); 23408 } 23409 } 23410 23411 @Override 23412 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23413 synchronized (mPackages) { 23414 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23415 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23416 packageName, userId); 23417 } 23418 } 23419 23420 @Override 23421 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23422 synchronized (mPackages) { 23423 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23424 packageName, userId); 23425 } 23426 } 23427 23428 @Override 23429 public void setKeepUninstalledPackages(final List<String> packageList) { 23430 Preconditions.checkNotNull(packageList); 23431 List<String> removedFromList = null; 23432 synchronized (mPackages) { 23433 if (mKeepUninstalledPackages != null) { 23434 final int packagesCount = mKeepUninstalledPackages.size(); 23435 for (int i = 0; i < packagesCount; i++) { 23436 String oldPackage = mKeepUninstalledPackages.get(i); 23437 if (packageList != null && packageList.contains(oldPackage)) { 23438 continue; 23439 } 23440 if (removedFromList == null) { 23441 removedFromList = new ArrayList<>(); 23442 } 23443 removedFromList.add(oldPackage); 23444 } 23445 } 23446 mKeepUninstalledPackages = new ArrayList<>(packageList); 23447 if (removedFromList != null) { 23448 final int removedCount = removedFromList.size(); 23449 for (int i = 0; i < removedCount; i++) { 23450 deletePackageIfUnusedLPr(removedFromList.get(i)); 23451 } 23452 } 23453 } 23454 } 23455 23456 @Override 23457 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23458 synchronized (mPackages) { 23459 // If we do not support permission review, done. 23460 if (!mPermissionReviewRequired) { 23461 return false; 23462 } 23463 23464 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23465 if (packageSetting == null) { 23466 return false; 23467 } 23468 23469 // Permission review applies only to apps not supporting the new permission model. 23470 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23471 return false; 23472 } 23473 23474 // Legacy apps have the permission and get user consent on launch. 23475 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23476 return permissionsState.isPermissionReviewRequired(userId); 23477 } 23478 } 23479 23480 @Override 23481 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23482 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23483 } 23484 23485 @Override 23486 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23487 int userId) { 23488 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23489 } 23490 23491 @Override 23492 public void setDeviceAndProfileOwnerPackages( 23493 int deviceOwnerUserId, String deviceOwnerPackage, 23494 SparseArray<String> profileOwnerPackages) { 23495 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23496 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23497 } 23498 23499 @Override 23500 public boolean isPackageDataProtected(int userId, String packageName) { 23501 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23502 } 23503 23504 @Override 23505 public boolean isPackageEphemeral(int userId, String packageName) { 23506 synchronized (mPackages) { 23507 final PackageSetting ps = mSettings.mPackages.get(packageName); 23508 return ps != null ? ps.getInstantApp(userId) : false; 23509 } 23510 } 23511 23512 @Override 23513 public boolean wasPackageEverLaunched(String packageName, int userId) { 23514 synchronized (mPackages) { 23515 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23516 } 23517 } 23518 23519 @Override 23520 public void grantRuntimePermission(String packageName, String name, int userId, 23521 boolean overridePolicy) { 23522 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23523 overridePolicy); 23524 } 23525 23526 @Override 23527 public void revokeRuntimePermission(String packageName, String name, int userId, 23528 boolean overridePolicy) { 23529 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23530 overridePolicy); 23531 } 23532 23533 @Override 23534 public String getNameForUid(int uid) { 23535 return PackageManagerService.this.getNameForUid(uid); 23536 } 23537 23538 @Override 23539 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23540 Intent origIntent, String resolvedType, String callingPackage, 23541 Bundle verificationBundle, int userId) { 23542 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23543 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23544 userId); 23545 } 23546 23547 @Override 23548 public void grantEphemeralAccess(int userId, Intent intent, 23549 int targetAppId, int ephemeralAppId) { 23550 synchronized (mPackages) { 23551 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23552 targetAppId, ephemeralAppId); 23553 } 23554 } 23555 23556 @Override 23557 public boolean isInstantAppInstallerComponent(ComponentName component) { 23558 synchronized (mPackages) { 23559 return mInstantAppInstallerActivity != null 23560 && mInstantAppInstallerActivity.getComponentName().equals(component); 23561 } 23562 } 23563 23564 @Override 23565 public void pruneInstantApps() { 23566 synchronized (mPackages) { 23567 mInstantAppRegistry.pruneInstantAppsLPw(); 23568 } 23569 } 23570 23571 @Override 23572 public String getSetupWizardPackageName() { 23573 return mSetupWizardPackage; 23574 } 23575 23576 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23577 if (policy != null) { 23578 mExternalSourcesPolicy = policy; 23579 } 23580 } 23581 23582 @Override 23583 public boolean isPackagePersistent(String packageName) { 23584 synchronized (mPackages) { 23585 PackageParser.Package pkg = mPackages.get(packageName); 23586 return pkg != null 23587 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23588 | ApplicationInfo.FLAG_PERSISTENT)) == 23589 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23590 : false; 23591 } 23592 } 23593 23594 @Override 23595 public List<PackageInfo> getOverlayPackages(int userId) { 23596 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23597 synchronized (mPackages) { 23598 for (PackageParser.Package p : mPackages.values()) { 23599 if (p.mOverlayTarget != null) { 23600 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23601 if (pkg != null) { 23602 overlayPackages.add(pkg); 23603 } 23604 } 23605 } 23606 } 23607 return overlayPackages; 23608 } 23609 23610 @Override 23611 public List<String> getTargetPackageNames(int userId) { 23612 List<String> targetPackages = new ArrayList<>(); 23613 synchronized (mPackages) { 23614 for (PackageParser.Package p : mPackages.values()) { 23615 if (p.mOverlayTarget == null) { 23616 targetPackages.add(p.packageName); 23617 } 23618 } 23619 } 23620 return targetPackages; 23621 } 23622 23623 @Override 23624 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23625 @Nullable List<String> overlayPackageNames) { 23626 synchronized (mPackages) { 23627 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23628 Slog.e(TAG, "failed to find package " + targetPackageName); 23629 return false; 23630 } 23631 23632 ArrayList<String> paths = null; 23633 if (overlayPackageNames != null) { 23634 final int N = overlayPackageNames.size(); 23635 paths = new ArrayList<>(N); 23636 for (int i = 0; i < N; i++) { 23637 final String packageName = overlayPackageNames.get(i); 23638 final PackageParser.Package pkg = mPackages.get(packageName); 23639 if (pkg == null) { 23640 Slog.e(TAG, "failed to find package " + packageName); 23641 return false; 23642 } 23643 paths.add(pkg.baseCodePath); 23644 } 23645 } 23646 23647 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23648 mEnabledOverlayPaths.get(userId); 23649 if (userSpecificOverlays == null) { 23650 userSpecificOverlays = new ArrayMap<>(); 23651 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23652 } 23653 23654 if (paths != null && paths.size() > 0) { 23655 userSpecificOverlays.put(targetPackageName, paths); 23656 } else { 23657 userSpecificOverlays.remove(targetPackageName); 23658 } 23659 return true; 23660 } 23661 } 23662 23663 @Override 23664 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23665 int flags, int userId) { 23666 return resolveIntentInternal( 23667 intent, resolvedType, flags, userId, true /*resolveForStart*/); 23668 } 23669 23670 @Override 23671 public ResolveInfo resolveService(Intent intent, String resolvedType, 23672 int flags, int userId, int callingUid) { 23673 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23674 } 23675 23676 @Override 23677 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23678 synchronized (mPackages) { 23679 mIsolatedOwners.put(isolatedUid, ownerUid); 23680 } 23681 } 23682 23683 @Override 23684 public void removeIsolatedUid(int isolatedUid) { 23685 synchronized (mPackages) { 23686 mIsolatedOwners.delete(isolatedUid); 23687 } 23688 } 23689 23690 @Override 23691 public int getUidTargetSdkVersion(int uid) { 23692 synchronized (mPackages) { 23693 return getUidTargetSdkVersionLockedLPr(uid); 23694 } 23695 } 23696 } 23697 23698 @Override 23699 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23700 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23701 synchronized (mPackages) { 23702 final long identity = Binder.clearCallingIdentity(); 23703 try { 23704 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23705 packageNames, userId); 23706 } finally { 23707 Binder.restoreCallingIdentity(identity); 23708 } 23709 } 23710 } 23711 23712 @Override 23713 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23714 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23715 synchronized (mPackages) { 23716 final long identity = Binder.clearCallingIdentity(); 23717 try { 23718 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23719 packageNames, userId); 23720 } finally { 23721 Binder.restoreCallingIdentity(identity); 23722 } 23723 } 23724 } 23725 23726 private static void enforceSystemOrPhoneCaller(String tag) { 23727 int callingUid = Binder.getCallingUid(); 23728 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23729 throw new SecurityException( 23730 "Cannot call " + tag + " from UID " + callingUid); 23731 } 23732 } 23733 23734 boolean isHistoricalPackageUsageAvailable() { 23735 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23736 } 23737 23738 /** 23739 * Return a <b>copy</b> of the collection of packages known to the package manager. 23740 * @return A copy of the values of mPackages. 23741 */ 23742 Collection<PackageParser.Package> getPackages() { 23743 synchronized (mPackages) { 23744 return new ArrayList<>(mPackages.values()); 23745 } 23746 } 23747 23748 /** 23749 * Logs process start information (including base APK hash) to the security log. 23750 * @hide 23751 */ 23752 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23753 String apkFile, int pid) { 23754 if (!SecurityLog.isLoggingEnabled()) { 23755 return; 23756 } 23757 Bundle data = new Bundle(); 23758 data.putLong("startTimestamp", System.currentTimeMillis()); 23759 data.putString("processName", processName); 23760 data.putInt("uid", uid); 23761 data.putString("seinfo", seinfo); 23762 data.putString("apkFile", apkFile); 23763 data.putInt("pid", pid); 23764 Message msg = mProcessLoggingHandler.obtainMessage( 23765 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23766 msg.setData(data); 23767 mProcessLoggingHandler.sendMessage(msg); 23768 } 23769 23770 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23771 return mCompilerStats.getPackageStats(pkgName); 23772 } 23773 23774 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23775 return getOrCreateCompilerPackageStats(pkg.packageName); 23776 } 23777 23778 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23779 return mCompilerStats.getOrCreatePackageStats(pkgName); 23780 } 23781 23782 public void deleteCompilerPackageStats(String pkgName) { 23783 mCompilerStats.deletePackageStats(pkgName); 23784 } 23785 23786 @Override 23787 public int getInstallReason(String packageName, int userId) { 23788 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23789 true /* requireFullPermission */, false /* checkShell */, 23790 "get install reason"); 23791 synchronized (mPackages) { 23792 final PackageSetting ps = mSettings.mPackages.get(packageName); 23793 if (ps != null) { 23794 return ps.getInstallReason(userId); 23795 } 23796 } 23797 return PackageManager.INSTALL_REASON_UNKNOWN; 23798 } 23799 23800 @Override 23801 public boolean canRequestPackageInstalls(String packageName, int userId) { 23802 int callingUid = Binder.getCallingUid(); 23803 int uid = getPackageUid(packageName, 0, userId); 23804 if (callingUid != uid && callingUid != Process.ROOT_UID 23805 && callingUid != Process.SYSTEM_UID) { 23806 throw new SecurityException( 23807 "Caller uid " + callingUid + " does not own package " + packageName); 23808 } 23809 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23810 if (info == null) { 23811 return false; 23812 } 23813 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23814 throw new UnsupportedOperationException( 23815 "Operation only supported on apps targeting Android O or higher"); 23816 } 23817 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23818 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23819 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23820 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23821 } 23822 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23823 return false; 23824 } 23825 if (mExternalSourcesPolicy != null) { 23826 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23827 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23828 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23829 } 23830 } 23831 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23832 } 23833 23834 @Override 23835 public ComponentName getInstantAppResolverSettingsComponent() { 23836 return mInstantAppResolverSettingsComponent; 23837 } 23838 23839 @Override 23840 public ComponentName getInstantAppInstallerComponent() { 23841 return mInstantAppInstallerActivity == null 23842 ? null : mInstantAppInstallerActivity.getComponentName(); 23843 } 23844 23845 @Override 23846 public String getInstantAppAndroidId(String packageName, int userId) { 23847 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23848 "getInstantAppAndroidId"); 23849 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23850 true /* requireFullPermission */, false /* checkShell */, 23851 "getInstantAppAndroidId"); 23852 // Make sure the target is an Instant App. 23853 if (!isInstantApp(packageName, userId)) { 23854 return null; 23855 } 23856 synchronized (mPackages) { 23857 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23858 } 23859 } 23860} 23861 23862interface PackageSender { 23863 void sendPackageBroadcast(final String action, final String pkg, 23864 final Bundle extras, final int flags, final String targetPkg, 23865 final IIntentReceiver finishedReceiver, final int[] userIds); 23866 void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 23867 int appId, int... userIds); 23868} 23869