PackageManagerService.java revision bf297bcf295735d186a627acbefa68f183562070
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppRequest; 132import android.content.pm.AuxiliaryResolveInfo; 133import android.content.pm.FallbackCategoryProvider; 134import android.content.pm.FeatureInfo; 135import android.content.pm.IOnPermissionsChangeListener; 136import android.content.pm.IPackageDataObserver; 137import android.content.pm.IPackageDeleteObserver; 138import android.content.pm.IPackageDeleteObserver2; 139import android.content.pm.IPackageInstallObserver2; 140import android.content.pm.IPackageInstaller; 141import android.content.pm.IPackageManager; 142import android.content.pm.IPackageMoveObserver; 143import android.content.pm.IPackageStatsObserver; 144import android.content.pm.InstantAppInfo; 145import android.content.pm.InstantAppResolveInfo; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.StorageManagerInternal; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.service.pm.PackageServiceDumpProto; 217import android.system.ErrnoException; 218import android.system.Os; 219import android.text.TextUtils; 220import android.text.format.DateUtils; 221import android.util.ArrayMap; 222import android.util.ArraySet; 223import android.util.Base64; 224import android.util.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.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.BackgroundDexOptService; 276import com.android.server.pm.Installer.InstallerException; 277import com.android.server.pm.PermissionsState.PermissionState; 278import com.android.server.pm.Settings.DatabaseVersion; 279import com.android.server.pm.Settings.VersionInfo; 280import com.android.server.pm.dex.DexManager; 281import com.android.server.storage.DeviceStorageMonitorInternal; 282 283import dalvik.system.CloseGuard; 284import dalvik.system.DexFile; 285import dalvik.system.VMRuntime; 286 287import libcore.io.IoUtils; 288import libcore.util.EmptyArray; 289 290import org.xmlpull.v1.XmlPullParser; 291import org.xmlpull.v1.XmlPullParserException; 292import org.xmlpull.v1.XmlSerializer; 293 294import java.io.BufferedOutputStream; 295import java.io.BufferedReader; 296import java.io.ByteArrayInputStream; 297import java.io.ByteArrayOutputStream; 298import java.io.File; 299import java.io.FileDescriptor; 300import java.io.FileInputStream; 301import java.io.FileNotFoundException; 302import java.io.FileOutputStream; 303import java.io.FileReader; 304import java.io.FilenameFilter; 305import java.io.IOException; 306import java.io.PrintWriter; 307import java.nio.charset.StandardCharsets; 308import java.security.DigestInputStream; 309import java.security.MessageDigest; 310import java.security.NoSuchAlgorithmException; 311import java.security.PublicKey; 312import java.security.SecureRandom; 313import java.security.cert.Certificate; 314import java.security.cert.CertificateEncodingException; 315import java.security.cert.CertificateException; 316import java.text.SimpleDateFormat; 317import java.util.ArrayList; 318import java.util.Arrays; 319import java.util.Collection; 320import java.util.Collections; 321import java.util.Comparator; 322import java.util.Date; 323import java.util.HashMap; 324import java.util.HashSet; 325import java.util.Iterator; 326import java.util.List; 327import java.util.Map; 328import java.util.Objects; 329import java.util.Set; 330import java.util.concurrent.CountDownLatch; 331import java.util.concurrent.Future; 332import java.util.concurrent.TimeUnit; 333import java.util.concurrent.atomic.AtomicBoolean; 334import java.util.concurrent.atomic.AtomicInteger; 335 336/** 337 * Keep track of all those APKs everywhere. 338 * <p> 339 * Internally there are two important locks: 340 * <ul> 341 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 342 * and other related state. It is a fine-grained lock that should only be held 343 * momentarily, as it's one of the most contended locks in the system. 344 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 345 * operations typically involve heavy lifting of application data on disk. Since 346 * {@code installd} is single-threaded, and it's operations can often be slow, 347 * this lock should never be acquired while already holding {@link #mPackages}. 348 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 349 * holding {@link #mInstallLock}. 350 * </ul> 351 * Many internal methods rely on the caller to hold the appropriate locks, and 352 * this contract is expressed through method name suffixes: 353 * <ul> 354 * <li>fooLI(): the caller must hold {@link #mInstallLock} 355 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 356 * being modified must be frozen 357 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 358 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 359 * </ul> 360 * <p> 361 * Because this class is very central to the platform's security; please run all 362 * CTS and unit tests whenever making modifications: 363 * 364 * <pre> 365 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 366 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 367 * </pre> 368 */ 369public class PackageManagerService extends IPackageManager.Stub { 370 static final String TAG = "PackageManager"; 371 static final boolean DEBUG_SETTINGS = false; 372 static final boolean DEBUG_PREFERRED = false; 373 static final boolean DEBUG_UPGRADE = false; 374 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 375 private static final boolean DEBUG_BACKUP = false; 376 private static final boolean DEBUG_INSTALL = false; 377 private static final boolean DEBUG_REMOVE = false; 378 private static final boolean DEBUG_BROADCASTS = false; 379 private static final boolean DEBUG_SHOW_INFO = false; 380 private static final boolean DEBUG_PACKAGE_INFO = false; 381 private static final boolean DEBUG_INTENT_MATCHING = false; 382 private static final boolean DEBUG_PACKAGE_SCANNING = false; 383 private static final boolean DEBUG_VERIFY = false; 384 private static final boolean DEBUG_FILTERS = false; 385 386 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 387 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 388 // user, but by default initialize to this. 389 public static final boolean DEBUG_DEXOPT = false; 390 391 private static final boolean DEBUG_ABI_SELECTION = false; 392 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 393 private static final boolean DEBUG_TRIAGED_MISSING = false; 394 private static final boolean DEBUG_APP_DATA = false; 395 396 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 397 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 398 399 private static final boolean DISABLE_EPHEMERAL_APPS = false; 400 private static final boolean HIDE_EPHEMERAL_APIS = false; 401 402 private static final boolean ENABLE_FREE_CACHE_V2 = 403 SystemProperties.getBoolean("fw.free_cache_v2", true); 404 405 private static final int RADIO_UID = Process.PHONE_UID; 406 private static final int LOG_UID = Process.LOG_UID; 407 private static final int NFC_UID = Process.NFC_UID; 408 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 409 private static final int SHELL_UID = Process.SHELL_UID; 410 411 // Cap the size of permission trees that 3rd party apps can define 412 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 413 414 // Suffix used during package installation when copying/moving 415 // package apks to install directory. 416 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 417 418 static final int SCAN_NO_DEX = 1<<1; 419 static final int SCAN_FORCE_DEX = 1<<2; 420 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 421 static final int SCAN_NEW_INSTALL = 1<<4; 422 static final int SCAN_UPDATE_TIME = 1<<5; 423 static final int SCAN_BOOTING = 1<<6; 424 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 425 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 426 static final int SCAN_REPLACING = 1<<9; 427 static final int SCAN_REQUIRE_KNOWN = 1<<10; 428 static final int SCAN_MOVE = 1<<11; 429 static final int SCAN_INITIAL = 1<<12; 430 static final int SCAN_CHECK_ONLY = 1<<13; 431 static final int SCAN_DONT_KILL_APP = 1<<14; 432 static final int SCAN_IGNORE_FROZEN = 1<<15; 433 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 434 static final int SCAN_AS_INSTANT_APP = 1<<17; 435 static final int SCAN_AS_FULL_APP = 1<<18; 436 /** Should not be with the scan flags */ 437 static final int FLAGS_REMOVE_CHATTY = 1<<31; 438 439 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 440 441 private static final int[] EMPTY_INT_ARRAY = new int[0]; 442 443 /** 444 * Timeout (in milliseconds) after which the watchdog should declare that 445 * our handler thread is wedged. The usual default for such things is one 446 * minute but we sometimes do very lengthy I/O operations on this thread, 447 * such as installing multi-gigabyte applications, so ours needs to be longer. 448 */ 449 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 450 451 /** 452 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 453 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 454 * settings entry if available, otherwise we use the hardcoded default. If it's been 455 * more than this long since the last fstrim, we force one during the boot sequence. 456 * 457 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 458 * one gets run at the next available charging+idle time. This final mandatory 459 * no-fstrim check kicks in only of the other scheduling criteria is never met. 460 */ 461 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 462 463 /** 464 * Whether verification is enabled by default. 465 */ 466 private static final boolean DEFAULT_VERIFY_ENABLE = true; 467 468 /** 469 * The default maximum time to wait for the verification agent to return in 470 * milliseconds. 471 */ 472 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 473 474 /** 475 * The default response for package verification timeout. 476 * 477 * This can be either PackageManager.VERIFICATION_ALLOW or 478 * PackageManager.VERIFICATION_REJECT. 479 */ 480 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 481 482 static final String PLATFORM_PACKAGE_NAME = "android"; 483 484 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 485 486 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 487 DEFAULT_CONTAINER_PACKAGE, 488 "com.android.defcontainer.DefaultContainerService"); 489 490 private static final String KILL_APP_REASON_GIDS_CHANGED = 491 "permission grant or revoke changed gids"; 492 493 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 494 "permissions revoked"; 495 496 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 497 498 private static final String PACKAGE_SCHEME = "package"; 499 500 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 501 502 /** Permission grant: not grant the permission. */ 503 private static final int GRANT_DENIED = 1; 504 505 /** Permission grant: grant the permission as an install permission. */ 506 private static final int GRANT_INSTALL = 2; 507 508 /** Permission grant: grant the permission as a runtime one. */ 509 private static final int GRANT_RUNTIME = 3; 510 511 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 512 private static final int GRANT_UPGRADE = 4; 513 514 /** Canonical intent used to identify what counts as a "web browser" app */ 515 private static final Intent sBrowserIntent; 516 static { 517 sBrowserIntent = new Intent(); 518 sBrowserIntent.setAction(Intent.ACTION_VIEW); 519 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 520 sBrowserIntent.setData(Uri.parse("http:")); 521 } 522 523 /** 524 * The set of all protected actions [i.e. those actions for which a high priority 525 * intent filter is disallowed]. 526 */ 527 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 528 static { 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 531 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 532 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 533 } 534 535 // Compilation reasons. 536 public static final int REASON_FIRST_BOOT = 0; 537 public static final int REASON_BOOT = 1; 538 public static final int REASON_INSTALL = 2; 539 public static final int REASON_BACKGROUND_DEXOPT = 3; 540 public static final int REASON_AB_OTA = 4; 541 public static final int REASON_FORCED_DEXOPT = 5; 542 543 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 544 545 /** All dangerous permission names in the same order as the events in MetricsEvent */ 546 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 547 Manifest.permission.READ_CALENDAR, 548 Manifest.permission.WRITE_CALENDAR, 549 Manifest.permission.CAMERA, 550 Manifest.permission.READ_CONTACTS, 551 Manifest.permission.WRITE_CONTACTS, 552 Manifest.permission.GET_ACCOUNTS, 553 Manifest.permission.ACCESS_FINE_LOCATION, 554 Manifest.permission.ACCESS_COARSE_LOCATION, 555 Manifest.permission.RECORD_AUDIO, 556 Manifest.permission.READ_PHONE_STATE, 557 Manifest.permission.CALL_PHONE, 558 Manifest.permission.READ_CALL_LOG, 559 Manifest.permission.WRITE_CALL_LOG, 560 Manifest.permission.ADD_VOICEMAIL, 561 Manifest.permission.USE_SIP, 562 Manifest.permission.PROCESS_OUTGOING_CALLS, 563 Manifest.permission.READ_CELL_BROADCASTS, 564 Manifest.permission.BODY_SENSORS, 565 Manifest.permission.SEND_SMS, 566 Manifest.permission.RECEIVE_SMS, 567 Manifest.permission.READ_SMS, 568 Manifest.permission.RECEIVE_WAP_PUSH, 569 Manifest.permission.RECEIVE_MMS, 570 Manifest.permission.READ_EXTERNAL_STORAGE, 571 Manifest.permission.WRITE_EXTERNAL_STORAGE, 572 Manifest.permission.READ_PHONE_NUMBERS, 573 Manifest.permission.ANSWER_PHONE_CALLS); 574 575 576 /** 577 * Version number for the package parser cache. Increment this whenever the format or 578 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 579 */ 580 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 581 582 /** 583 * Whether the package parser cache is enabled. 584 */ 585 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 586 587 final ServiceThread mHandlerThread; 588 589 final PackageHandler mHandler; 590 591 private final ProcessLoggingHandler mProcessLoggingHandler; 592 593 /** 594 * Messages for {@link #mHandler} that need to wait for system ready before 595 * being dispatched. 596 */ 597 private ArrayList<Message> mPostSystemReadyMessages; 598 599 final int mSdkVersion = Build.VERSION.SDK_INT; 600 601 final Context mContext; 602 final boolean mFactoryTest; 603 final boolean mOnlyCore; 604 final DisplayMetrics mMetrics; 605 final int mDefParseFlags; 606 final String[] mSeparateProcesses; 607 final boolean mIsUpgrade; 608 final boolean mIsPreNUpgrade; 609 final boolean mIsPreNMR1Upgrade; 610 611 // Have we told the Activity Manager to whitelist the default container service by uid yet? 612 @GuardedBy("mPackages") 613 boolean mDefaultContainerWhitelisted = false; 614 615 @GuardedBy("mPackages") 616 private boolean mDexOptDialogShown; 617 618 /** The location for ASEC container files on internal storage. */ 619 final String mAsecInternalPath; 620 621 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 622 // LOCK HELD. Can be called with mInstallLock held. 623 @GuardedBy("mInstallLock") 624 final Installer mInstaller; 625 626 /** Directory where installed third-party apps stored */ 627 final File mAppInstallDir; 628 629 /** 630 * Directory to which applications installed internally have their 631 * 32 bit native libraries copied. 632 */ 633 private File mAppLib32InstallDir; 634 635 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 636 // apps. 637 final File mDrmAppPrivateInstallDir; 638 639 // ---------------------------------------------------------------- 640 641 // Lock for state used when installing and doing other long running 642 // operations. Methods that must be called with this lock held have 643 // the suffix "LI". 644 final Object mInstallLock = new Object(); 645 646 // ---------------------------------------------------------------- 647 648 // Keys are String (package name), values are Package. This also serves 649 // as the lock for the global state. Methods that must be called with 650 // this lock held have the prefix "LP". 651 @GuardedBy("mPackages") 652 final ArrayMap<String, PackageParser.Package> mPackages = 653 new ArrayMap<String, PackageParser.Package>(); 654 655 final ArrayMap<String, Set<String>> mKnownCodebase = 656 new ArrayMap<String, Set<String>>(); 657 658 // Keys are isolated uids and values are the uid of the application 659 // that created the isolated proccess. 660 @GuardedBy("mPackages") 661 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 662 663 // List of APK paths to load for each user and package. This data is never 664 // persisted by the package manager. Instead, the overlay manager will 665 // ensure the data is up-to-date in runtime. 666 @GuardedBy("mPackages") 667 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 668 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 669 670 /** 671 * Tracks new system packages [received in an OTA] that we expect to 672 * find updated user-installed versions. Keys are package name, values 673 * are package location. 674 */ 675 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 676 /** 677 * Tracks high priority intent filters for protected actions. During boot, certain 678 * filter actions are protected and should never be allowed to have a high priority 679 * intent filter for them. However, there is one, and only one exception -- the 680 * setup wizard. It must be able to define a high priority intent filter for these 681 * actions to ensure there are no escapes from the wizard. We need to delay processing 682 * of these during boot as we need to look at all of the system packages in order 683 * to know which component is the setup wizard. 684 */ 685 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 686 /** 687 * Whether or not processing protected filters should be deferred. 688 */ 689 private boolean mDeferProtectedFilters = true; 690 691 /** 692 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 693 */ 694 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 695 /** 696 * Whether or not system app permissions should be promoted from install to runtime. 697 */ 698 boolean mPromoteSystemApps; 699 700 @GuardedBy("mPackages") 701 final Settings mSettings; 702 703 /** 704 * Set of package names that are currently "frozen", which means active 705 * surgery is being done on the code/data for that package. The platform 706 * will refuse to launch frozen packages to avoid race conditions. 707 * 708 * @see PackageFreezer 709 */ 710 @GuardedBy("mPackages") 711 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 712 713 final ProtectedPackages mProtectedPackages; 714 715 boolean mFirstBoot; 716 717 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 718 719 // System configuration read by SystemConfig. 720 final int[] mGlobalGids; 721 final SparseArray<ArraySet<String>> mSystemPermissions; 722 @GuardedBy("mAvailableFeatures") 723 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 724 725 // If mac_permissions.xml was found for seinfo labeling. 726 boolean mFoundPolicyFile; 727 728 private final InstantAppRegistry mInstantAppRegistry; 729 730 @GuardedBy("mPackages") 731 int mChangedPackagesSequenceNumber; 732 /** 733 * List of changed [installed, removed or updated] packages. 734 * mapping from user id -> sequence number -> package name 735 */ 736 @GuardedBy("mPackages") 737 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 738 /** 739 * The sequence number of the last change to a package. 740 * mapping from user id -> package name -> sequence number 741 */ 742 @GuardedBy("mPackages") 743 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 744 745 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 746 @Override public boolean hasFeature(String feature) { 747 return PackageManagerService.this.hasSystemFeature(feature, 0); 748 } 749 }; 750 751 public static final class SharedLibraryEntry { 752 public final String path; 753 public final String apk; 754 public final SharedLibraryInfo info; 755 756 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 757 String declaringPackageName, int declaringPackageVersionCode) { 758 path = _path; 759 apk = _apk; 760 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 761 declaringPackageName, declaringPackageVersionCode), null); 762 } 763 } 764 765 // Currently known shared libraries. 766 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 767 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 768 new ArrayMap<>(); 769 770 // All available activities, for your resolving pleasure. 771 final ActivityIntentResolver mActivities = 772 new ActivityIntentResolver(); 773 774 // All available receivers, for your resolving pleasure. 775 final ActivityIntentResolver mReceivers = 776 new ActivityIntentResolver(); 777 778 // All available services, for your resolving pleasure. 779 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 780 781 // All available providers, for your resolving pleasure. 782 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 783 784 // Mapping from provider base names (first directory in content URI codePath) 785 // to the provider information. 786 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 787 new ArrayMap<String, PackageParser.Provider>(); 788 789 // Mapping from instrumentation class names to info about them. 790 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 791 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 792 793 // Mapping from permission names to info about them. 794 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 795 new ArrayMap<String, PackageParser.PermissionGroup>(); 796 797 // Packages whose data we have transfered into another package, thus 798 // should no longer exist. 799 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 800 801 // Broadcast actions that are only available to the system. 802 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 803 804 /** List of packages waiting for verification. */ 805 final SparseArray<PackageVerificationState> mPendingVerification 806 = new SparseArray<PackageVerificationState>(); 807 808 /** Set of packages associated with each app op permission. */ 809 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 810 811 final PackageInstallerService mInstallerService; 812 813 private final PackageDexOptimizer mPackageDexOptimizer; 814 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 815 // is used by other apps). 816 private final DexManager mDexManager; 817 818 private AtomicInteger mNextMoveId = new AtomicInteger(); 819 private final MoveCallbacks mMoveCallbacks; 820 821 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 822 823 // Cache of users who need badging. 824 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 825 826 /** Token for keys in mPendingVerification. */ 827 private int mPendingVerificationToken = 0; 828 829 volatile boolean mSystemReady; 830 volatile boolean mSafeMode; 831 volatile boolean mHasSystemUidErrors; 832 833 ApplicationInfo mAndroidApplication; 834 final ActivityInfo mResolveActivity = new ActivityInfo(); 835 final ResolveInfo mResolveInfo = new ResolveInfo(); 836 ComponentName mResolveComponentName; 837 PackageParser.Package mPlatformPackage; 838 ComponentName mCustomResolverComponentName; 839 840 boolean mResolverReplaced = false; 841 842 private final @Nullable ComponentName mIntentFilterVerifierComponent; 843 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 844 845 private int mIntentFilterVerificationToken = 0; 846 847 /** The service connection to the ephemeral resolver */ 848 final EphemeralResolverConnection mInstantAppResolverConnection; 849 /** Component used to show resolver settings for Instant Apps */ 850 final ComponentName mInstantAppResolverSettingsComponent; 851 852 /** Activity used to install instant applications */ 853 ActivityInfo mInstantAppInstallerActivity; 854 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 855 856 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 857 = new SparseArray<IntentFilterVerificationState>(); 858 859 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 860 861 // List of packages names to keep cached, even if they are uninstalled for all users 862 private List<String> mKeepUninstalledPackages; 863 864 private UserManagerInternal mUserManagerInternal; 865 866 private DeviceIdleController.LocalService mDeviceIdleController; 867 868 private File mCacheDir; 869 870 private ArraySet<String> mPrivappPermissionsViolations; 871 872 private Future<?> mPrepareAppDataFuture; 873 874 private static class IFVerificationParams { 875 PackageParser.Package pkg; 876 boolean replacing; 877 int userId; 878 int verifierUid; 879 880 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 881 int _userId, int _verifierUid) { 882 pkg = _pkg; 883 replacing = _replacing; 884 userId = _userId; 885 replacing = _replacing; 886 verifierUid = _verifierUid; 887 } 888 } 889 890 private interface IntentFilterVerifier<T extends IntentFilter> { 891 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 892 T filter, String packageName); 893 void startVerifications(int userId); 894 void receiveVerificationResponse(int verificationId); 895 } 896 897 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 898 private Context mContext; 899 private ComponentName mIntentFilterVerifierComponent; 900 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 901 902 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 903 mContext = context; 904 mIntentFilterVerifierComponent = verifierComponent; 905 } 906 907 private String getDefaultScheme() { 908 return IntentFilter.SCHEME_HTTPS; 909 } 910 911 @Override 912 public void startVerifications(int userId) { 913 // Launch verifications requests 914 int count = mCurrentIntentFilterVerifications.size(); 915 for (int n=0; n<count; n++) { 916 int verificationId = mCurrentIntentFilterVerifications.get(n); 917 final IntentFilterVerificationState ivs = 918 mIntentFilterVerificationStates.get(verificationId); 919 920 String packageName = ivs.getPackageName(); 921 922 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 923 final int filterCount = filters.size(); 924 ArraySet<String> domainsSet = new ArraySet<>(); 925 for (int m=0; m<filterCount; m++) { 926 PackageParser.ActivityIntentInfo filter = filters.get(m); 927 domainsSet.addAll(filter.getHostsList()); 928 } 929 synchronized (mPackages) { 930 if (mSettings.createIntentFilterVerificationIfNeededLPw( 931 packageName, domainsSet) != null) { 932 scheduleWriteSettingsLocked(); 933 } 934 } 935 sendVerificationRequest(userId, verificationId, ivs); 936 } 937 mCurrentIntentFilterVerifications.clear(); 938 } 939 940 private void sendVerificationRequest(int userId, int verificationId, 941 IntentFilterVerificationState ivs) { 942 943 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 946 verificationId); 947 verificationIntent.putExtra( 948 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 949 getDefaultScheme()); 950 verificationIntent.putExtra( 951 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 952 ivs.getHostsString()); 953 verificationIntent.putExtra( 954 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 955 ivs.getPackageName()); 956 verificationIntent.setComponent(mIntentFilterVerifierComponent); 957 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 958 959 UserHandle user = new UserHandle(userId); 960 mContext.sendBroadcastAsUser(verificationIntent, user); 961 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 962 "Sending IntentFilter verification broadcast"); 963 } 964 965 public void receiveVerificationResponse(int verificationId) { 966 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 967 968 final boolean verified = ivs.isVerified(); 969 970 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 971 final int count = filters.size(); 972 if (DEBUG_DOMAIN_VERIFICATION) { 973 Slog.i(TAG, "Received verification response " + verificationId 974 + " for " + count + " filters, verified=" + verified); 975 } 976 for (int n=0; n<count; n++) { 977 PackageParser.ActivityIntentInfo filter = filters.get(n); 978 filter.setVerified(verified); 979 980 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 981 + " verified with result:" + verified + " and hosts:" 982 + ivs.getHostsString()); 983 } 984 985 mIntentFilterVerificationStates.remove(verificationId); 986 987 final String packageName = ivs.getPackageName(); 988 IntentFilterVerificationInfo ivi = null; 989 990 synchronized (mPackages) { 991 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 992 } 993 if (ivi == null) { 994 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 995 + verificationId + " packageName:" + packageName); 996 return; 997 } 998 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 999 "Updating IntentFilterVerificationInfo for package " + packageName 1000 +" verificationId:" + verificationId); 1001 1002 synchronized (mPackages) { 1003 if (verified) { 1004 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1005 } else { 1006 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1007 } 1008 scheduleWriteSettingsLocked(); 1009 1010 final int userId = ivs.getUserId(); 1011 if (userId != UserHandle.USER_ALL) { 1012 final int userStatus = 1013 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1014 1015 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1016 boolean needUpdate = false; 1017 1018 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1019 // already been set by the User thru the Disambiguation dialog 1020 switch (userStatus) { 1021 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1022 if (verified) { 1023 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1024 } else { 1025 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1026 } 1027 needUpdate = true; 1028 break; 1029 1030 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1031 if (verified) { 1032 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1033 needUpdate = true; 1034 } 1035 break; 1036 1037 default: 1038 // Nothing to do 1039 } 1040 1041 if (needUpdate) { 1042 mSettings.updateIntentFilterVerificationStatusLPw( 1043 packageName, updatedStatus, userId); 1044 scheduleWritePackageRestrictionsLocked(userId); 1045 } 1046 } 1047 } 1048 } 1049 1050 @Override 1051 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1052 ActivityIntentInfo filter, String packageName) { 1053 if (!hasValidDomains(filter)) { 1054 return false; 1055 } 1056 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1057 if (ivs == null) { 1058 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1059 packageName); 1060 } 1061 if (DEBUG_DOMAIN_VERIFICATION) { 1062 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1063 } 1064 ivs.addFilter(filter); 1065 return true; 1066 } 1067 1068 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1069 int userId, int verificationId, String packageName) { 1070 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1071 verifierUid, userId, packageName); 1072 ivs.setPendingState(); 1073 synchronized (mPackages) { 1074 mIntentFilterVerificationStates.append(verificationId, ivs); 1075 mCurrentIntentFilterVerifications.add(verificationId); 1076 } 1077 return ivs; 1078 } 1079 } 1080 1081 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1082 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1083 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1084 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1085 } 1086 1087 // Set of pending broadcasts for aggregating enable/disable of components. 1088 static class PendingPackageBroadcasts { 1089 // for each user id, a map of <package name -> components within that package> 1090 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1091 1092 public PendingPackageBroadcasts() { 1093 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1094 } 1095 1096 public ArrayList<String> get(int userId, String packageName) { 1097 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1098 return packages.get(packageName); 1099 } 1100 1101 public void put(int userId, String packageName, ArrayList<String> components) { 1102 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1103 packages.put(packageName, components); 1104 } 1105 1106 public void remove(int userId, String packageName) { 1107 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1108 if (packages != null) { 1109 packages.remove(packageName); 1110 } 1111 } 1112 1113 public void remove(int userId) { 1114 mUidMap.remove(userId); 1115 } 1116 1117 public int userIdCount() { 1118 return mUidMap.size(); 1119 } 1120 1121 public int userIdAt(int n) { 1122 return mUidMap.keyAt(n); 1123 } 1124 1125 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1126 return mUidMap.get(userId); 1127 } 1128 1129 public int size() { 1130 // total number of pending broadcast entries across all userIds 1131 int num = 0; 1132 for (int i = 0; i< mUidMap.size(); i++) { 1133 num += mUidMap.valueAt(i).size(); 1134 } 1135 return num; 1136 } 1137 1138 public void clear() { 1139 mUidMap.clear(); 1140 } 1141 1142 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1143 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1144 if (map == null) { 1145 map = new ArrayMap<String, ArrayList<String>>(); 1146 mUidMap.put(userId, map); 1147 } 1148 return map; 1149 } 1150 } 1151 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1152 1153 // Service Connection to remote media container service to copy 1154 // package uri's from external media onto secure containers 1155 // or internal storage. 1156 private IMediaContainerService mContainerService = null; 1157 1158 static final int SEND_PENDING_BROADCAST = 1; 1159 static final int MCS_BOUND = 3; 1160 static final int END_COPY = 4; 1161 static final int INIT_COPY = 5; 1162 static final int MCS_UNBIND = 6; 1163 static final int START_CLEANING_PACKAGE = 7; 1164 static final int FIND_INSTALL_LOC = 8; 1165 static final int POST_INSTALL = 9; 1166 static final int MCS_RECONNECT = 10; 1167 static final int MCS_GIVE_UP = 11; 1168 static final int UPDATED_MEDIA_STATUS = 12; 1169 static final int WRITE_SETTINGS = 13; 1170 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1171 static final int PACKAGE_VERIFIED = 15; 1172 static final int CHECK_PENDING_VERIFICATION = 16; 1173 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1174 static final int INTENT_FILTER_VERIFIED = 18; 1175 static final int WRITE_PACKAGE_LIST = 19; 1176 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1177 1178 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1179 1180 // Delay time in millisecs 1181 static final int BROADCAST_DELAY = 10 * 1000; 1182 1183 static UserManagerService sUserManager; 1184 1185 // Stores a list of users whose package restrictions file needs to be updated 1186 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1187 1188 final private DefaultContainerConnection mDefContainerConn = 1189 new DefaultContainerConnection(); 1190 class DefaultContainerConnection implements ServiceConnection { 1191 public void onServiceConnected(ComponentName name, IBinder service) { 1192 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1193 final IMediaContainerService imcs = IMediaContainerService.Stub 1194 .asInterface(Binder.allowBlocking(service)); 1195 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1196 } 1197 1198 public void onServiceDisconnected(ComponentName name) { 1199 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1200 } 1201 } 1202 1203 // Recordkeeping of restore-after-install operations that are currently in flight 1204 // between the Package Manager and the Backup Manager 1205 static class PostInstallData { 1206 public InstallArgs args; 1207 public PackageInstalledInfo res; 1208 1209 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1210 args = _a; 1211 res = _r; 1212 } 1213 } 1214 1215 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1216 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1217 1218 // XML tags for backup/restore of various bits of state 1219 private static final String TAG_PREFERRED_BACKUP = "pa"; 1220 private static final String TAG_DEFAULT_APPS = "da"; 1221 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1222 1223 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1224 private static final String TAG_ALL_GRANTS = "rt-grants"; 1225 private static final String TAG_GRANT = "grant"; 1226 private static final String ATTR_PACKAGE_NAME = "pkg"; 1227 1228 private static final String TAG_PERMISSION = "perm"; 1229 private static final String ATTR_PERMISSION_NAME = "name"; 1230 private static final String ATTR_IS_GRANTED = "g"; 1231 private static final String ATTR_USER_SET = "set"; 1232 private static final String ATTR_USER_FIXED = "fixed"; 1233 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1234 1235 // System/policy permission grants are not backed up 1236 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1237 FLAG_PERMISSION_POLICY_FIXED 1238 | FLAG_PERMISSION_SYSTEM_FIXED 1239 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1240 1241 // And we back up these user-adjusted states 1242 private static final int USER_RUNTIME_GRANT_MASK = 1243 FLAG_PERMISSION_USER_SET 1244 | FLAG_PERMISSION_USER_FIXED 1245 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1246 1247 final @Nullable String mRequiredVerifierPackage; 1248 final @NonNull String mRequiredInstallerPackage; 1249 final @NonNull String mRequiredUninstallerPackage; 1250 final @Nullable String mSetupWizardPackage; 1251 final @Nullable String mStorageManagerPackage; 1252 final @NonNull String mServicesSystemSharedLibraryPackageName; 1253 final @NonNull String mSharedSystemSharedLibraryPackageName; 1254 1255 final boolean mPermissionReviewRequired; 1256 1257 private final PackageUsage mPackageUsage = new PackageUsage(); 1258 private final CompilerStats mCompilerStats = new CompilerStats(); 1259 1260 class PackageHandler extends Handler { 1261 private boolean mBound = false; 1262 final ArrayList<HandlerParams> mPendingInstalls = 1263 new ArrayList<HandlerParams>(); 1264 1265 private boolean connectToService() { 1266 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1267 " DefaultContainerService"); 1268 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1269 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1270 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1271 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1273 mBound = true; 1274 return true; 1275 } 1276 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1277 return false; 1278 } 1279 1280 private void disconnectService() { 1281 mContainerService = null; 1282 mBound = false; 1283 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1284 mContext.unbindService(mDefContainerConn); 1285 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1286 } 1287 1288 PackageHandler(Looper looper) { 1289 super(looper); 1290 } 1291 1292 public void handleMessage(Message msg) { 1293 try { 1294 doHandleMessage(msg); 1295 } finally { 1296 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1297 } 1298 } 1299 1300 void doHandleMessage(Message msg) { 1301 switch (msg.what) { 1302 case INIT_COPY: { 1303 HandlerParams params = (HandlerParams) msg.obj; 1304 int idx = mPendingInstalls.size(); 1305 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1306 // If a bind was already initiated we dont really 1307 // need to do anything. The pending install 1308 // will be processed later on. 1309 if (!mBound) { 1310 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1311 System.identityHashCode(mHandler)); 1312 // If this is the only one pending we might 1313 // have to bind to the service again. 1314 if (!connectToService()) { 1315 Slog.e(TAG, "Failed to bind to media container service"); 1316 params.serviceError(); 1317 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1318 System.identityHashCode(mHandler)); 1319 if (params.traceMethod != null) { 1320 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1321 params.traceCookie); 1322 } 1323 return; 1324 } else { 1325 // Once we bind to the service, the first 1326 // pending request will be processed. 1327 mPendingInstalls.add(idx, params); 1328 } 1329 } else { 1330 mPendingInstalls.add(idx, params); 1331 // Already bound to the service. Just make 1332 // sure we trigger off processing the first request. 1333 if (idx == 0) { 1334 mHandler.sendEmptyMessage(MCS_BOUND); 1335 } 1336 } 1337 break; 1338 } 1339 case MCS_BOUND: { 1340 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1341 if (msg.obj != null) { 1342 mContainerService = (IMediaContainerService) msg.obj; 1343 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1344 System.identityHashCode(mHandler)); 1345 } 1346 if (mContainerService == null) { 1347 if (!mBound) { 1348 // Something seriously wrong since we are not bound and we are not 1349 // waiting for connection. Bail out. 1350 Slog.e(TAG, "Cannot bind to media container service"); 1351 for (HandlerParams params : mPendingInstalls) { 1352 // Indicate service bind error 1353 params.serviceError(); 1354 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1355 System.identityHashCode(params)); 1356 if (params.traceMethod != null) { 1357 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1358 params.traceMethod, params.traceCookie); 1359 } 1360 return; 1361 } 1362 mPendingInstalls.clear(); 1363 } else { 1364 Slog.w(TAG, "Waiting to connect to media container service"); 1365 } 1366 } else if (mPendingInstalls.size() > 0) { 1367 HandlerParams params = mPendingInstalls.get(0); 1368 if (params != null) { 1369 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1370 System.identityHashCode(params)); 1371 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1372 if (params.startCopy()) { 1373 // We are done... look for more work or to 1374 // go idle. 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, 1376 "Checking for more work or unbind..."); 1377 // Delete pending install 1378 if (mPendingInstalls.size() > 0) { 1379 mPendingInstalls.remove(0); 1380 } 1381 if (mPendingInstalls.size() == 0) { 1382 if (mBound) { 1383 if (DEBUG_SD_INSTALL) Log.i(TAG, 1384 "Posting delayed MCS_UNBIND"); 1385 removeMessages(MCS_UNBIND); 1386 Message ubmsg = obtainMessage(MCS_UNBIND); 1387 // Unbind after a little delay, to avoid 1388 // continual thrashing. 1389 sendMessageDelayed(ubmsg, 10000); 1390 } 1391 } else { 1392 // There are more pending requests in queue. 1393 // Just post MCS_BOUND message to trigger processing 1394 // of next pending install. 1395 if (DEBUG_SD_INSTALL) Log.i(TAG, 1396 "Posting MCS_BOUND for next work"); 1397 mHandler.sendEmptyMessage(MCS_BOUND); 1398 } 1399 } 1400 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1401 } 1402 } else { 1403 // Should never happen ideally. 1404 Slog.w(TAG, "Empty queue"); 1405 } 1406 break; 1407 } 1408 case MCS_RECONNECT: { 1409 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1410 if (mPendingInstalls.size() > 0) { 1411 if (mBound) { 1412 disconnectService(); 1413 } 1414 if (!connectToService()) { 1415 Slog.e(TAG, "Failed to bind to media container service"); 1416 for (HandlerParams params : mPendingInstalls) { 1417 // Indicate service bind error 1418 params.serviceError(); 1419 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1420 System.identityHashCode(params)); 1421 } 1422 mPendingInstalls.clear(); 1423 } 1424 } 1425 break; 1426 } 1427 case MCS_UNBIND: { 1428 // If there is no actual work left, then time to unbind. 1429 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1430 1431 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1432 if (mBound) { 1433 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1434 1435 disconnectService(); 1436 } 1437 } else if (mPendingInstalls.size() > 0) { 1438 // There are more pending requests in queue. 1439 // Just post MCS_BOUND message to trigger processing 1440 // of next pending install. 1441 mHandler.sendEmptyMessage(MCS_BOUND); 1442 } 1443 1444 break; 1445 } 1446 case MCS_GIVE_UP: { 1447 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1448 HandlerParams params = mPendingInstalls.remove(0); 1449 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1450 System.identityHashCode(params)); 1451 break; 1452 } 1453 case SEND_PENDING_BROADCAST: { 1454 String packages[]; 1455 ArrayList<String> components[]; 1456 int size = 0; 1457 int uids[]; 1458 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1459 synchronized (mPackages) { 1460 if (mPendingBroadcasts == null) { 1461 return; 1462 } 1463 size = mPendingBroadcasts.size(); 1464 if (size <= 0) { 1465 // Nothing to be done. Just return 1466 return; 1467 } 1468 packages = new String[size]; 1469 components = new ArrayList[size]; 1470 uids = new int[size]; 1471 int i = 0; // filling out the above arrays 1472 1473 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1474 int packageUserId = mPendingBroadcasts.userIdAt(n); 1475 Iterator<Map.Entry<String, ArrayList<String>>> it 1476 = mPendingBroadcasts.packagesForUserId(packageUserId) 1477 .entrySet().iterator(); 1478 while (it.hasNext() && i < size) { 1479 Map.Entry<String, ArrayList<String>> ent = it.next(); 1480 packages[i] = ent.getKey(); 1481 components[i] = ent.getValue(); 1482 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1483 uids[i] = (ps != null) 1484 ? UserHandle.getUid(packageUserId, ps.appId) 1485 : -1; 1486 i++; 1487 } 1488 } 1489 size = i; 1490 mPendingBroadcasts.clear(); 1491 } 1492 // Send broadcasts 1493 for (int i = 0; i < size; i++) { 1494 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1495 } 1496 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1497 break; 1498 } 1499 case START_CLEANING_PACKAGE: { 1500 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1501 final String packageName = (String)msg.obj; 1502 final int userId = msg.arg1; 1503 final boolean andCode = msg.arg2 != 0; 1504 synchronized (mPackages) { 1505 if (userId == UserHandle.USER_ALL) { 1506 int[] users = sUserManager.getUserIds(); 1507 for (int user : users) { 1508 mSettings.addPackageToCleanLPw( 1509 new PackageCleanItem(user, packageName, andCode)); 1510 } 1511 } else { 1512 mSettings.addPackageToCleanLPw( 1513 new PackageCleanItem(userId, packageName, andCode)); 1514 } 1515 } 1516 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1517 startCleaningPackages(); 1518 } break; 1519 case POST_INSTALL: { 1520 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1521 1522 PostInstallData data = mRunningInstalls.get(msg.arg1); 1523 final boolean didRestore = (msg.arg2 != 0); 1524 mRunningInstalls.delete(msg.arg1); 1525 1526 if (data != null) { 1527 InstallArgs args = data.args; 1528 PackageInstalledInfo parentRes = data.res; 1529 1530 final boolean grantPermissions = (args.installFlags 1531 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1532 final boolean killApp = (args.installFlags 1533 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1534 final String[] grantedPermissions = args.installGrantPermissions; 1535 1536 // Handle the parent package 1537 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1538 grantedPermissions, didRestore, args.installerPackageName, 1539 args.observer); 1540 1541 // Handle the child packages 1542 final int childCount = (parentRes.addedChildPackages != null) 1543 ? parentRes.addedChildPackages.size() : 0; 1544 for (int i = 0; i < childCount; i++) { 1545 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1546 handlePackagePostInstall(childRes, grantPermissions, killApp, 1547 grantedPermissions, false, args.installerPackageName, 1548 args.observer); 1549 } 1550 1551 // Log tracing if needed 1552 if (args.traceMethod != null) { 1553 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1554 args.traceCookie); 1555 } 1556 } else { 1557 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1558 } 1559 1560 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1561 } break; 1562 case UPDATED_MEDIA_STATUS: { 1563 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1564 boolean reportStatus = msg.arg1 == 1; 1565 boolean doGc = msg.arg2 == 1; 1566 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1567 if (doGc) { 1568 // Force a gc to clear up stale containers. 1569 Runtime.getRuntime().gc(); 1570 } 1571 if (msg.obj != null) { 1572 @SuppressWarnings("unchecked") 1573 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1574 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1575 // Unload containers 1576 unloadAllContainers(args); 1577 } 1578 if (reportStatus) { 1579 try { 1580 if (DEBUG_SD_INSTALL) Log.i(TAG, 1581 "Invoking StorageManagerService call back"); 1582 PackageHelper.getStorageManager().finishMediaUpdate(); 1583 } catch (RemoteException e) { 1584 Log.e(TAG, "StorageManagerService not running?"); 1585 } 1586 } 1587 } break; 1588 case WRITE_SETTINGS: { 1589 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1590 synchronized (mPackages) { 1591 removeMessages(WRITE_SETTINGS); 1592 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1593 mSettings.writeLPr(); 1594 mDirtyUsers.clear(); 1595 } 1596 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1597 } break; 1598 case WRITE_PACKAGE_RESTRICTIONS: { 1599 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1600 synchronized (mPackages) { 1601 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1602 for (int userId : mDirtyUsers) { 1603 mSettings.writePackageRestrictionsLPr(userId); 1604 } 1605 mDirtyUsers.clear(); 1606 } 1607 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1608 } break; 1609 case WRITE_PACKAGE_LIST: { 1610 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1611 synchronized (mPackages) { 1612 removeMessages(WRITE_PACKAGE_LIST); 1613 mSettings.writePackageListLPr(msg.arg1); 1614 } 1615 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1616 } break; 1617 case CHECK_PENDING_VERIFICATION: { 1618 final int verificationId = msg.arg1; 1619 final PackageVerificationState state = mPendingVerification.get(verificationId); 1620 1621 if ((state != null) && !state.timeoutExtended()) { 1622 final InstallArgs args = state.getInstallArgs(); 1623 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1624 1625 Slog.i(TAG, "Verification timed out for " + originUri); 1626 mPendingVerification.remove(verificationId); 1627 1628 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1629 1630 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1631 Slog.i(TAG, "Continuing with installation of " + originUri); 1632 state.setVerifierResponse(Binder.getCallingUid(), 1633 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1634 broadcastPackageVerified(verificationId, originUri, 1635 PackageManager.VERIFICATION_ALLOW, 1636 state.getInstallArgs().getUser()); 1637 try { 1638 ret = args.copyApk(mContainerService, true); 1639 } catch (RemoteException e) { 1640 Slog.e(TAG, "Could not contact the ContainerService"); 1641 } 1642 } else { 1643 broadcastPackageVerified(verificationId, originUri, 1644 PackageManager.VERIFICATION_REJECT, 1645 state.getInstallArgs().getUser()); 1646 } 1647 1648 Trace.asyncTraceEnd( 1649 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1650 1651 processPendingInstall(args, ret); 1652 mHandler.sendEmptyMessage(MCS_UNBIND); 1653 } 1654 break; 1655 } 1656 case PACKAGE_VERIFIED: { 1657 final int verificationId = msg.arg1; 1658 1659 final PackageVerificationState state = mPendingVerification.get(verificationId); 1660 if (state == null) { 1661 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1662 break; 1663 } 1664 1665 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1666 1667 state.setVerifierResponse(response.callerUid, response.code); 1668 1669 if (state.isVerificationComplete()) { 1670 mPendingVerification.remove(verificationId); 1671 1672 final InstallArgs args = state.getInstallArgs(); 1673 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1674 1675 int ret; 1676 if (state.isInstallAllowed()) { 1677 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1678 broadcastPackageVerified(verificationId, originUri, 1679 response.code, state.getInstallArgs().getUser()); 1680 try { 1681 ret = args.copyApk(mContainerService, true); 1682 } catch (RemoteException e) { 1683 Slog.e(TAG, "Could not contact the ContainerService"); 1684 } 1685 } else { 1686 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1687 } 1688 1689 Trace.asyncTraceEnd( 1690 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1691 1692 processPendingInstall(args, ret); 1693 mHandler.sendEmptyMessage(MCS_UNBIND); 1694 } 1695 1696 break; 1697 } 1698 case START_INTENT_FILTER_VERIFICATIONS: { 1699 IFVerificationParams params = (IFVerificationParams) msg.obj; 1700 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1701 params.replacing, params.pkg); 1702 break; 1703 } 1704 case INTENT_FILTER_VERIFIED: { 1705 final int verificationId = msg.arg1; 1706 1707 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1708 verificationId); 1709 if (state == null) { 1710 Slog.w(TAG, "Invalid IntentFilter verification token " 1711 + verificationId + " received"); 1712 break; 1713 } 1714 1715 final int userId = state.getUserId(); 1716 1717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1718 "Processing IntentFilter verification with token:" 1719 + verificationId + " and userId:" + userId); 1720 1721 final IntentFilterVerificationResponse response = 1722 (IntentFilterVerificationResponse) msg.obj; 1723 1724 state.setVerifierResponse(response.callerUid, response.code); 1725 1726 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1727 "IntentFilter verification with token:" + verificationId 1728 + " and userId:" + userId 1729 + " is settings verifier response with response code:" 1730 + response.code); 1731 1732 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1733 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1734 + response.getFailedDomainsString()); 1735 } 1736 1737 if (state.isVerificationComplete()) { 1738 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1739 } else { 1740 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1741 "IntentFilter verification with token:" + verificationId 1742 + " was not said to be complete"); 1743 } 1744 1745 break; 1746 } 1747 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1748 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1749 mInstantAppResolverConnection, 1750 (InstantAppRequest) msg.obj, 1751 mInstantAppInstallerActivity, 1752 mHandler); 1753 } 1754 } 1755 } 1756 } 1757 1758 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1759 boolean killApp, String[] grantedPermissions, 1760 boolean launchedForRestore, String installerPackage, 1761 IPackageInstallObserver2 installObserver) { 1762 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1763 // Send the removed broadcasts 1764 if (res.removedInfo != null) { 1765 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1766 } 1767 1768 // Now that we successfully installed the package, grant runtime 1769 // permissions if requested before broadcasting the install. Also 1770 // for legacy apps in permission review mode we clear the permission 1771 // review flag which is used to emulate runtime permissions for 1772 // legacy apps. 1773 if (grantPermissions) { 1774 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1775 } 1776 1777 final boolean update = res.removedInfo != null 1778 && res.removedInfo.removedPackage != null; 1779 1780 // If this is the first time we have child packages for a disabled privileged 1781 // app that had no children, we grant requested runtime permissions to the new 1782 // children if the parent on the system image had them already granted. 1783 if (res.pkg.parentPackage != null) { 1784 synchronized (mPackages) { 1785 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1786 } 1787 } 1788 1789 synchronized (mPackages) { 1790 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1791 } 1792 1793 final String packageName = res.pkg.applicationInfo.packageName; 1794 1795 // Determine the set of users who are adding this package for 1796 // the first time vs. those who are seeing an update. 1797 int[] firstUsers = EMPTY_INT_ARRAY; 1798 int[] updateUsers = EMPTY_INT_ARRAY; 1799 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1800 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1801 for (int newUser : res.newUsers) { 1802 if (ps.getInstantApp(newUser)) { 1803 continue; 1804 } 1805 if (allNewUsers) { 1806 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1807 continue; 1808 } 1809 boolean isNew = true; 1810 for (int origUser : res.origUsers) { 1811 if (origUser == newUser) { 1812 isNew = false; 1813 break; 1814 } 1815 } 1816 if (isNew) { 1817 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1818 } else { 1819 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1820 } 1821 } 1822 1823 // Send installed broadcasts if the package is not a static shared lib. 1824 if (res.pkg.staticSharedLibName == null) { 1825 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1826 1827 // Send added for users that see the package for the first time 1828 // sendPackageAddedForNewUsers also deals with system apps 1829 int appId = UserHandle.getAppId(res.uid); 1830 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1831 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1832 1833 // Send added for users that don't see the package for the first time 1834 Bundle extras = new Bundle(1); 1835 extras.putInt(Intent.EXTRA_UID, res.uid); 1836 if (update) { 1837 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1838 } 1839 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1840 extras, 0 /*flags*/, null /*targetPackage*/, 1841 null /*finishedReceiver*/, updateUsers); 1842 1843 // Send replaced for users that don't see the package for the first time 1844 if (update) { 1845 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1846 packageName, extras, 0 /*flags*/, 1847 null /*targetPackage*/, null /*finishedReceiver*/, 1848 updateUsers); 1849 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1850 null /*package*/, null /*extras*/, 0 /*flags*/, 1851 packageName /*targetPackage*/, 1852 null /*finishedReceiver*/, updateUsers); 1853 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1854 // First-install and we did a restore, so we're responsible for the 1855 // first-launch broadcast. 1856 if (DEBUG_BACKUP) { 1857 Slog.i(TAG, "Post-restore of " + packageName 1858 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1859 } 1860 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1861 } 1862 1863 // Send broadcast package appeared if forward locked/external for all users 1864 // treat asec-hosted packages like removable media on upgrade 1865 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1866 if (DEBUG_INSTALL) { 1867 Slog.i(TAG, "upgrading pkg " + res.pkg 1868 + " is ASEC-hosted -> AVAILABLE"); 1869 } 1870 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1871 ArrayList<String> pkgList = new ArrayList<>(1); 1872 pkgList.add(packageName); 1873 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1874 } 1875 } 1876 1877 // Work that needs to happen on first install within each user 1878 if (firstUsers != null && firstUsers.length > 0) { 1879 synchronized (mPackages) { 1880 for (int userId : firstUsers) { 1881 // If this app is a browser and it's newly-installed for some 1882 // users, clear any default-browser state in those users. The 1883 // app's nature doesn't depend on the user, so we can just check 1884 // its browser nature in any user and generalize. 1885 if (packageIsBrowser(packageName, userId)) { 1886 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1887 } 1888 1889 // We may also need to apply pending (restored) runtime 1890 // permission grants within these users. 1891 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1892 } 1893 } 1894 } 1895 1896 // Log current value of "unknown sources" setting 1897 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1898 getUnknownSourcesSettings()); 1899 1900 // Force a gc to clear up things 1901 Runtime.getRuntime().gc(); 1902 1903 // Remove the replaced package's older resources safely now 1904 // We delete after a gc for applications on sdcard. 1905 if (res.removedInfo != null && res.removedInfo.args != null) { 1906 synchronized (mInstallLock) { 1907 res.removedInfo.args.doPostDeleteLI(true); 1908 } 1909 } 1910 1911 // Notify DexManager that the package was installed for new users. 1912 // The updated users should already be indexed and the package code paths 1913 // should not change. 1914 // Don't notify the manager for ephemeral apps as they are not expected to 1915 // survive long enough to benefit of background optimizations. 1916 for (int userId : firstUsers) { 1917 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1918 // There's a race currently where some install events may interleave with an uninstall. 1919 // This can lead to package info being null (b/36642664). 1920 if (info != null) { 1921 mDexManager.notifyPackageInstalled(info, userId); 1922 } 1923 } 1924 } 1925 1926 // If someone is watching installs - notify them 1927 if (installObserver != null) { 1928 try { 1929 Bundle extras = extrasForInstallResult(res); 1930 installObserver.onPackageInstalled(res.name, res.returnCode, 1931 res.returnMsg, extras); 1932 } catch (RemoteException e) { 1933 Slog.i(TAG, "Observer no longer exists."); 1934 } 1935 } 1936 } 1937 1938 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1939 PackageParser.Package pkg) { 1940 if (pkg.parentPackage == null) { 1941 return; 1942 } 1943 if (pkg.requestedPermissions == null) { 1944 return; 1945 } 1946 final PackageSetting disabledSysParentPs = mSettings 1947 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1948 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1949 || !disabledSysParentPs.isPrivileged() 1950 || (disabledSysParentPs.childPackageNames != null 1951 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1952 return; 1953 } 1954 final int[] allUserIds = sUserManager.getUserIds(); 1955 final int permCount = pkg.requestedPermissions.size(); 1956 for (int i = 0; i < permCount; i++) { 1957 String permission = pkg.requestedPermissions.get(i); 1958 BasePermission bp = mSettings.mPermissions.get(permission); 1959 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1960 continue; 1961 } 1962 for (int userId : allUserIds) { 1963 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1964 permission, userId)) { 1965 grantRuntimePermission(pkg.packageName, permission, userId); 1966 } 1967 } 1968 } 1969 } 1970 1971 private StorageEventListener mStorageListener = new StorageEventListener() { 1972 @Override 1973 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1974 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1975 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1976 final String volumeUuid = vol.getFsUuid(); 1977 1978 // Clean up any users or apps that were removed or recreated 1979 // while this volume was missing 1980 sUserManager.reconcileUsers(volumeUuid); 1981 reconcileApps(volumeUuid); 1982 1983 // Clean up any install sessions that expired or were 1984 // cancelled while this volume was missing 1985 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1986 1987 loadPrivatePackages(vol); 1988 1989 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1990 unloadPrivatePackages(vol); 1991 } 1992 } 1993 1994 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1995 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1996 updateExternalMediaStatus(true, false); 1997 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1998 updateExternalMediaStatus(false, false); 1999 } 2000 } 2001 } 2002 2003 @Override 2004 public void onVolumeForgotten(String fsUuid) { 2005 if (TextUtils.isEmpty(fsUuid)) { 2006 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2007 return; 2008 } 2009 2010 // Remove any apps installed on the forgotten volume 2011 synchronized (mPackages) { 2012 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2013 for (PackageSetting ps : packages) { 2014 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2015 deletePackageVersioned(new VersionedPackage(ps.name, 2016 PackageManager.VERSION_CODE_HIGHEST), 2017 new LegacyPackageDeleteObserver(null).getBinder(), 2018 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2019 // Try very hard to release any references to this package 2020 // so we don't risk the system server being killed due to 2021 // open FDs 2022 AttributeCache.instance().removePackage(ps.name); 2023 } 2024 2025 mSettings.onVolumeForgotten(fsUuid); 2026 mSettings.writeLPr(); 2027 } 2028 } 2029 }; 2030 2031 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2032 String[] grantedPermissions) { 2033 for (int userId : userIds) { 2034 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2035 } 2036 } 2037 2038 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2039 String[] grantedPermissions) { 2040 SettingBase sb = (SettingBase) pkg.mExtras; 2041 if (sb == null) { 2042 return; 2043 } 2044 2045 PermissionsState permissionsState = sb.getPermissionsState(); 2046 2047 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2048 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2049 2050 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2051 >= Build.VERSION_CODES.M; 2052 2053 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2054 2055 for (String permission : pkg.requestedPermissions) { 2056 final BasePermission bp; 2057 synchronized (mPackages) { 2058 bp = mSettings.mPermissions.get(permission); 2059 } 2060 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2061 && (!instantApp || bp.isInstant()) 2062 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2063 && (grantedPermissions == null 2064 || ArrayUtils.contains(grantedPermissions, permission))) { 2065 final int flags = permissionsState.getPermissionFlags(permission, userId); 2066 if (supportsRuntimePermissions) { 2067 // Installer cannot change immutable permissions. 2068 if ((flags & immutableFlags) == 0) { 2069 grantRuntimePermission(pkg.packageName, permission, userId); 2070 } 2071 } else if (mPermissionReviewRequired) { 2072 // In permission review mode we clear the review flag when we 2073 // are asked to install the app with all permissions granted. 2074 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2075 updatePermissionFlags(permission, pkg.packageName, 2076 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2077 } 2078 } 2079 } 2080 } 2081 } 2082 2083 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2084 Bundle extras = null; 2085 switch (res.returnCode) { 2086 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2087 extras = new Bundle(); 2088 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2089 res.origPermission); 2090 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2091 res.origPackage); 2092 break; 2093 } 2094 case PackageManager.INSTALL_SUCCEEDED: { 2095 extras = new Bundle(); 2096 extras.putBoolean(Intent.EXTRA_REPLACING, 2097 res.removedInfo != null && res.removedInfo.removedPackage != null); 2098 break; 2099 } 2100 } 2101 return extras; 2102 } 2103 2104 void scheduleWriteSettingsLocked() { 2105 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2106 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2107 } 2108 } 2109 2110 void scheduleWritePackageListLocked(int userId) { 2111 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2112 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2113 msg.arg1 = userId; 2114 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2115 } 2116 } 2117 2118 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2119 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2120 scheduleWritePackageRestrictionsLocked(userId); 2121 } 2122 2123 void scheduleWritePackageRestrictionsLocked(int userId) { 2124 final int[] userIds = (userId == UserHandle.USER_ALL) 2125 ? sUserManager.getUserIds() : new int[]{userId}; 2126 for (int nextUserId : userIds) { 2127 if (!sUserManager.exists(nextUserId)) return; 2128 mDirtyUsers.add(nextUserId); 2129 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2130 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2131 } 2132 } 2133 } 2134 2135 public static PackageManagerService main(Context context, Installer installer, 2136 boolean factoryTest, boolean onlyCore) { 2137 // Self-check for initial settings. 2138 PackageManagerServiceCompilerMapping.checkProperties(); 2139 2140 PackageManagerService m = new PackageManagerService(context, installer, 2141 factoryTest, onlyCore); 2142 m.enableSystemUserPackages(); 2143 ServiceManager.addService("package", m); 2144 return m; 2145 } 2146 2147 private void enableSystemUserPackages() { 2148 if (!UserManager.isSplitSystemUser()) { 2149 return; 2150 } 2151 // For system user, enable apps based on the following conditions: 2152 // - app is whitelisted or belong to one of these groups: 2153 // -- system app which has no launcher icons 2154 // -- system app which has INTERACT_ACROSS_USERS permission 2155 // -- system IME app 2156 // - app is not in the blacklist 2157 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2158 Set<String> enableApps = new ArraySet<>(); 2159 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2160 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2161 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2162 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2163 enableApps.addAll(wlApps); 2164 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2165 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2166 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2167 enableApps.removeAll(blApps); 2168 Log.i(TAG, "Applications installed for system user: " + enableApps); 2169 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2170 UserHandle.SYSTEM); 2171 final int allAppsSize = allAps.size(); 2172 synchronized (mPackages) { 2173 for (int i = 0; i < allAppsSize; i++) { 2174 String pName = allAps.get(i); 2175 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2176 // Should not happen, but we shouldn't be failing if it does 2177 if (pkgSetting == null) { 2178 continue; 2179 } 2180 boolean install = enableApps.contains(pName); 2181 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2182 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2183 + " for system user"); 2184 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2185 } 2186 } 2187 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2188 } 2189 } 2190 2191 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2192 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2193 Context.DISPLAY_SERVICE); 2194 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2195 } 2196 2197 /** 2198 * Requests that files preopted on a secondary system partition be copied to the data partition 2199 * if possible. Note that the actual copying of the files is accomplished by init for security 2200 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2201 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2202 */ 2203 private static void requestCopyPreoptedFiles() { 2204 final int WAIT_TIME_MS = 100; 2205 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2206 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2207 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2208 // We will wait for up to 100 seconds. 2209 final long timeStart = SystemClock.uptimeMillis(); 2210 final long timeEnd = timeStart + 100 * 1000; 2211 long timeNow = timeStart; 2212 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2213 try { 2214 Thread.sleep(WAIT_TIME_MS); 2215 } catch (InterruptedException e) { 2216 // Do nothing 2217 } 2218 timeNow = SystemClock.uptimeMillis(); 2219 if (timeNow > timeEnd) { 2220 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2221 Slog.wtf(TAG, "cppreopt did not finish!"); 2222 break; 2223 } 2224 } 2225 2226 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2227 } 2228 } 2229 2230 public PackageManagerService(Context context, Installer installer, 2231 boolean factoryTest, boolean onlyCore) { 2232 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2234 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2235 SystemClock.uptimeMillis()); 2236 2237 if (mSdkVersion <= 0) { 2238 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2239 } 2240 2241 mContext = context; 2242 2243 mPermissionReviewRequired = context.getResources().getBoolean( 2244 R.bool.config_permissionReviewRequired); 2245 2246 mFactoryTest = factoryTest; 2247 mOnlyCore = onlyCore; 2248 mMetrics = new DisplayMetrics(); 2249 mSettings = new Settings(mPackages); 2250 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2251 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2252 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2253 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2254 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2255 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2256 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2257 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2258 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2259 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2260 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2261 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2262 2263 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2264 if (separateProcesses != null && separateProcesses.length() > 0) { 2265 if ("*".equals(separateProcesses)) { 2266 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2267 mSeparateProcesses = null; 2268 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2269 } else { 2270 mDefParseFlags = 0; 2271 mSeparateProcesses = separateProcesses.split(","); 2272 Slog.w(TAG, "Running with debug.separate_processes: " 2273 + separateProcesses); 2274 } 2275 } else { 2276 mDefParseFlags = 0; 2277 mSeparateProcesses = null; 2278 } 2279 2280 mInstaller = installer; 2281 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2282 "*dexopt*"); 2283 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2284 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2285 2286 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2287 FgThread.get().getLooper()); 2288 2289 getDefaultDisplayMetrics(context, mMetrics); 2290 2291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2292 SystemConfig systemConfig = SystemConfig.getInstance(); 2293 mGlobalGids = systemConfig.getGlobalGids(); 2294 mSystemPermissions = systemConfig.getSystemPermissions(); 2295 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2297 2298 mProtectedPackages = new ProtectedPackages(mContext); 2299 2300 synchronized (mInstallLock) { 2301 // writer 2302 synchronized (mPackages) { 2303 mHandlerThread = new ServiceThread(TAG, 2304 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2305 mHandlerThread.start(); 2306 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2307 mProcessLoggingHandler = new ProcessLoggingHandler(); 2308 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2309 2310 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2311 mInstantAppRegistry = new InstantAppRegistry(this); 2312 2313 File dataDir = Environment.getDataDirectory(); 2314 mAppInstallDir = new File(dataDir, "app"); 2315 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2316 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2317 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2318 sUserManager = new UserManagerService(context, this, 2319 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2320 2321 // Propagate permission configuration in to package manager. 2322 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2323 = systemConfig.getPermissions(); 2324 for (int i=0; i<permConfig.size(); i++) { 2325 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2326 BasePermission bp = mSettings.mPermissions.get(perm.name); 2327 if (bp == null) { 2328 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2329 mSettings.mPermissions.put(perm.name, bp); 2330 } 2331 if (perm.gids != null) { 2332 bp.setGids(perm.gids, perm.perUser); 2333 } 2334 } 2335 2336 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2337 final int builtInLibCount = libConfig.size(); 2338 for (int i = 0; i < builtInLibCount; i++) { 2339 String name = libConfig.keyAt(i); 2340 String path = libConfig.valueAt(i); 2341 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2342 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2343 } 2344 2345 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2346 2347 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2348 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2349 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2350 2351 // Clean up orphaned packages for which the code path doesn't exist 2352 // and they are an update to a system app - caused by bug/32321269 2353 final int packageSettingCount = mSettings.mPackages.size(); 2354 for (int i = packageSettingCount - 1; i >= 0; i--) { 2355 PackageSetting ps = mSettings.mPackages.valueAt(i); 2356 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2357 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2358 mSettings.mPackages.removeAt(i); 2359 mSettings.enableSystemPackageLPw(ps.name); 2360 } 2361 } 2362 2363 if (mFirstBoot) { 2364 requestCopyPreoptedFiles(); 2365 } 2366 2367 String customResolverActivity = Resources.getSystem().getString( 2368 R.string.config_customResolverActivity); 2369 if (TextUtils.isEmpty(customResolverActivity)) { 2370 customResolverActivity = null; 2371 } else { 2372 mCustomResolverComponentName = ComponentName.unflattenFromString( 2373 customResolverActivity); 2374 } 2375 2376 long startTime = SystemClock.uptimeMillis(); 2377 2378 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2379 startTime); 2380 2381 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2382 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2383 2384 if (bootClassPath == null) { 2385 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2386 } 2387 2388 if (systemServerClassPath == null) { 2389 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2390 } 2391 2392 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2393 2394 final VersionInfo ver = mSettings.getInternalVersion(); 2395 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2396 if (mIsUpgrade) { 2397 logCriticalInfo(Log.INFO, 2398 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2399 } 2400 2401 // when upgrading from pre-M, promote system app permissions from install to runtime 2402 mPromoteSystemApps = 2403 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2404 2405 // When upgrading from pre-N, we need to handle package extraction like first boot, 2406 // as there is no profiling data available. 2407 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2408 2409 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2410 2411 // save off the names of pre-existing system packages prior to scanning; we don't 2412 // want to automatically grant runtime permissions for new system apps 2413 if (mPromoteSystemApps) { 2414 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2415 while (pkgSettingIter.hasNext()) { 2416 PackageSetting ps = pkgSettingIter.next(); 2417 if (isSystemApp(ps)) { 2418 mExistingSystemPackages.add(ps.name); 2419 } 2420 } 2421 } 2422 2423 mCacheDir = preparePackageParserCache(mIsUpgrade); 2424 2425 // Set flag to monitor and not change apk file paths when 2426 // scanning install directories. 2427 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2428 2429 if (mIsUpgrade || mFirstBoot) { 2430 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2431 } 2432 2433 // Collect vendor overlay packages. (Do this before scanning any apps.) 2434 // For security and version matching reason, only consider 2435 // overlay packages if they reside in the right directory. 2436 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR 2439 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2440 2441 // Find base frameworks (resource packages without code). 2442 scanDirTracedLI(frameworkDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR 2445 | PackageParser.PARSE_IS_PRIVILEGED, 2446 scanFlags | SCAN_NO_DEX, 0); 2447 2448 // Collected privileged system packages. 2449 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2450 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2451 | PackageParser.PARSE_IS_SYSTEM 2452 | PackageParser.PARSE_IS_SYSTEM_DIR 2453 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2454 2455 // Collect ordinary system packages. 2456 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2457 scanDirTracedLI(systemAppDir, mDefParseFlags 2458 | PackageParser.PARSE_IS_SYSTEM 2459 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2460 2461 // Collect all vendor packages. 2462 File vendorAppDir = new File("/vendor/app"); 2463 try { 2464 vendorAppDir = vendorAppDir.getCanonicalFile(); 2465 } catch (IOException e) { 2466 // failed to look up canonical path, continue with original one 2467 } 2468 scanDirTracedLI(vendorAppDir, mDefParseFlags 2469 | PackageParser.PARSE_IS_SYSTEM 2470 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2471 2472 // Collect all OEM packages. 2473 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2474 scanDirTracedLI(oemAppDir, mDefParseFlags 2475 | PackageParser.PARSE_IS_SYSTEM 2476 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2477 2478 // Prune any system packages that no longer exist. 2479 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2480 if (!mOnlyCore) { 2481 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2482 while (psit.hasNext()) { 2483 PackageSetting ps = psit.next(); 2484 2485 /* 2486 * If this is not a system app, it can't be a 2487 * disable system app. 2488 */ 2489 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2490 continue; 2491 } 2492 2493 /* 2494 * If the package is scanned, it's not erased. 2495 */ 2496 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2497 if (scannedPkg != null) { 2498 /* 2499 * If the system app is both scanned and in the 2500 * disabled packages list, then it must have been 2501 * added via OTA. Remove it from the currently 2502 * scanned package so the previously user-installed 2503 * application can be scanned. 2504 */ 2505 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2506 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2507 + ps.name + "; removing system app. Last known codePath=" 2508 + ps.codePathString + ", installStatus=" + ps.installStatus 2509 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2510 + scannedPkg.mVersionCode); 2511 removePackageLI(scannedPkg, true); 2512 mExpectingBetter.put(ps.name, ps.codePath); 2513 } 2514 2515 continue; 2516 } 2517 2518 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2519 psit.remove(); 2520 logCriticalInfo(Log.WARN, "System package " + ps.name 2521 + " no longer exists; it's data will be wiped"); 2522 // Actual deletion of code and data will be handled by later 2523 // reconciliation step 2524 } else { 2525 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2526 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2527 possiblyDeletedUpdatedSystemApps.add(ps.name); 2528 } 2529 } 2530 } 2531 } 2532 2533 //look for any incomplete package installations 2534 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2535 for (int i = 0; i < deletePkgsList.size(); i++) { 2536 // Actual deletion of code and data will be handled by later 2537 // reconciliation step 2538 final String packageName = deletePkgsList.get(i).name; 2539 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2540 synchronized (mPackages) { 2541 mSettings.removePackageLPw(packageName); 2542 } 2543 } 2544 2545 //delete tmp files 2546 deleteTempPackageFiles(); 2547 2548 // Remove any shared userIDs that have no associated packages 2549 mSettings.pruneSharedUsersLPw(); 2550 2551 if (!mOnlyCore) { 2552 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2553 SystemClock.uptimeMillis()); 2554 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2555 2556 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2557 | PackageParser.PARSE_FORWARD_LOCK, 2558 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2559 2560 /** 2561 * Remove disable package settings for any updated system 2562 * apps that were removed via an OTA. If they're not a 2563 * previously-updated app, remove them completely. 2564 * Otherwise, just revoke their system-level permissions. 2565 */ 2566 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2567 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2568 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2569 2570 String msg; 2571 if (deletedPkg == null) { 2572 msg = "Updated system package " + deletedAppName 2573 + " no longer exists; it's data will be wiped"; 2574 // Actual deletion of code and data will be handled by later 2575 // reconciliation step 2576 } else { 2577 msg = "Updated system app + " + deletedAppName 2578 + " no longer present; removing system privileges for " 2579 + deletedAppName; 2580 2581 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2582 2583 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2584 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2585 } 2586 logCriticalInfo(Log.WARN, msg); 2587 } 2588 2589 /** 2590 * Make sure all system apps that we expected to appear on 2591 * the userdata partition actually showed up. If they never 2592 * appeared, crawl back and revive the system version. 2593 */ 2594 for (int i = 0; i < mExpectingBetter.size(); i++) { 2595 final String packageName = mExpectingBetter.keyAt(i); 2596 if (!mPackages.containsKey(packageName)) { 2597 final File scanFile = mExpectingBetter.valueAt(i); 2598 2599 logCriticalInfo(Log.WARN, "Expected better " + packageName 2600 + " but never showed up; reverting to system"); 2601 2602 int reparseFlags = mDefParseFlags; 2603 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2604 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR 2606 | PackageParser.PARSE_IS_PRIVILEGED; 2607 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2608 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2609 | PackageParser.PARSE_IS_SYSTEM_DIR; 2610 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2611 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2612 | PackageParser.PARSE_IS_SYSTEM_DIR; 2613 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2614 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2615 | PackageParser.PARSE_IS_SYSTEM_DIR; 2616 } else { 2617 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2618 continue; 2619 } 2620 2621 mSettings.enableSystemPackageLPw(packageName); 2622 2623 try { 2624 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2625 } catch (PackageManagerException e) { 2626 Slog.e(TAG, "Failed to parse original system package: " 2627 + e.getMessage()); 2628 } 2629 } 2630 } 2631 } 2632 mExpectingBetter.clear(); 2633 2634 // Resolve the storage manager. 2635 mStorageManagerPackage = getStorageManagerPackageName(); 2636 2637 // Resolve protected action filters. Only the setup wizard is allowed to 2638 // have a high priority filter for these actions. 2639 mSetupWizardPackage = getSetupWizardPackageName(); 2640 if (mProtectedFilters.size() > 0) { 2641 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2642 Slog.i(TAG, "No setup wizard;" 2643 + " All protected intents capped to priority 0"); 2644 } 2645 for (ActivityIntentInfo filter : mProtectedFilters) { 2646 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2647 if (DEBUG_FILTERS) { 2648 Slog.i(TAG, "Found setup wizard;" 2649 + " allow priority " + filter.getPriority() + ";" 2650 + " package: " + filter.activity.info.packageName 2651 + " activity: " + filter.activity.className 2652 + " priority: " + filter.getPriority()); 2653 } 2654 // skip setup wizard; allow it to keep the high priority filter 2655 continue; 2656 } 2657 Slog.w(TAG, "Protected action; cap priority to 0;" 2658 + " package: " + filter.activity.info.packageName 2659 + " activity: " + filter.activity.className 2660 + " origPrio: " + filter.getPriority()); 2661 filter.setPriority(0); 2662 } 2663 } 2664 mDeferProtectedFilters = false; 2665 mProtectedFilters.clear(); 2666 2667 // Now that we know all of the shared libraries, update all clients to have 2668 // the correct library paths. 2669 updateAllSharedLibrariesLPw(null); 2670 2671 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2672 // NOTE: We ignore potential failures here during a system scan (like 2673 // the rest of the commands above) because there's precious little we 2674 // can do about it. A settings error is reported, though. 2675 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2676 } 2677 2678 // Now that we know all the packages we are keeping, 2679 // read and update their last usage times. 2680 mPackageUsage.read(mPackages); 2681 mCompilerStats.read(); 2682 2683 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2684 SystemClock.uptimeMillis()); 2685 Slog.i(TAG, "Time to scan packages: " 2686 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2687 + " seconds"); 2688 2689 // If the platform SDK has changed since the last time we booted, 2690 // we need to re-grant app permission to catch any new ones that 2691 // appear. This is really a hack, and means that apps can in some 2692 // cases get permissions that the user didn't initially explicitly 2693 // allow... it would be nice to have some better way to handle 2694 // this situation. 2695 int updateFlags = UPDATE_PERMISSIONS_ALL; 2696 if (ver.sdkVersion != mSdkVersion) { 2697 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2698 + mSdkVersion + "; regranting permissions for internal storage"); 2699 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2700 } 2701 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2702 ver.sdkVersion = mSdkVersion; 2703 2704 // If this is the first boot or an update from pre-M, and it is a normal 2705 // boot, then we need to initialize the default preferred apps across 2706 // all defined users. 2707 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2708 for (UserInfo user : sUserManager.getUsers(true)) { 2709 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2710 applyFactoryDefaultBrowserLPw(user.id); 2711 primeDomainVerificationsLPw(user.id); 2712 } 2713 } 2714 2715 // Prepare storage for system user really early during boot, 2716 // since core system apps like SettingsProvider and SystemUI 2717 // can't wait for user to start 2718 final int storageFlags; 2719 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2720 storageFlags = StorageManager.FLAG_STORAGE_DE; 2721 } else { 2722 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2723 } 2724 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2725 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2726 true /* onlyCoreApps */); 2727 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "fixup"); 2729 try { 2730 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2731 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2732 } catch (InstallerException e) { 2733 Slog.w(TAG, "Trouble fixing GIDs", e); 2734 } 2735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2736 2737 if (deferPackages == null || deferPackages.isEmpty()) { 2738 return; 2739 } 2740 int count = 0; 2741 for (String pkgName : deferPackages) { 2742 PackageParser.Package pkg = null; 2743 synchronized (mPackages) { 2744 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2745 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2746 pkg = ps.pkg; 2747 } 2748 } 2749 if (pkg != null) { 2750 synchronized (mInstallLock) { 2751 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2752 true /* maybeMigrateAppData */); 2753 } 2754 count++; 2755 } 2756 } 2757 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2758 }, "prepareAppData"); 2759 2760 // If this is first boot after an OTA, and a normal boot, then 2761 // we need to clear code cache directories. 2762 // Note that we do *not* clear the application profiles. These remain valid 2763 // across OTAs and are used to drive profile verification (post OTA) and 2764 // profile compilation (without waiting to collect a fresh set of profiles). 2765 if (mIsUpgrade && !onlyCore) { 2766 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2767 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2768 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2769 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2770 // No apps are running this early, so no need to freeze 2771 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2772 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2773 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2774 } 2775 } 2776 ver.fingerprint = Build.FINGERPRINT; 2777 } 2778 2779 checkDefaultBrowser(); 2780 2781 // clear only after permissions and other defaults have been updated 2782 mExistingSystemPackages.clear(); 2783 mPromoteSystemApps = false; 2784 2785 // All the changes are done during package scanning. 2786 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2787 2788 // can downgrade to reader 2789 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2790 mSettings.writeLPr(); 2791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2792 2793 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2794 SystemClock.uptimeMillis()); 2795 2796 if (!mOnlyCore) { 2797 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2798 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2799 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2800 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2801 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2802 mIntentFilterVerifierComponent); 2803 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2804 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2805 SharedLibraryInfo.VERSION_UNDEFINED); 2806 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2807 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2808 SharedLibraryInfo.VERSION_UNDEFINED); 2809 } else { 2810 mRequiredVerifierPackage = null; 2811 mRequiredInstallerPackage = null; 2812 mRequiredUninstallerPackage = null; 2813 mIntentFilterVerifierComponent = null; 2814 mIntentFilterVerifier = null; 2815 mServicesSystemSharedLibraryPackageName = null; 2816 mSharedSystemSharedLibraryPackageName = null; 2817 } 2818 2819 mInstallerService = new PackageInstallerService(context, this); 2820 final Pair<ComponentName, String> instantAppResolverComponent = 2821 getInstantAppResolverLPr(); 2822 if (instantAppResolverComponent != null) { 2823 if (DEBUG_EPHEMERAL) { 2824 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2825 } 2826 mInstantAppResolverConnection = new EphemeralResolverConnection( 2827 mContext, instantAppResolverComponent.first, 2828 instantAppResolverComponent.second); 2829 mInstantAppResolverSettingsComponent = 2830 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2831 } else { 2832 mInstantAppResolverConnection = null; 2833 mInstantAppResolverSettingsComponent = null; 2834 } 2835 updateInstantAppInstallerLocked(null); 2836 2837 // Read and update the usage of dex files. 2838 // Do this at the end of PM init so that all the packages have their 2839 // data directory reconciled. 2840 // At this point we know the code paths of the packages, so we can validate 2841 // the disk file and build the internal cache. 2842 // The usage file is expected to be small so loading and verifying it 2843 // should take a fairly small time compare to the other activities (e.g. package 2844 // scanning). 2845 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2846 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2847 for (int userId : currentUserIds) { 2848 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2849 } 2850 mDexManager.load(userPackages); 2851 } // synchronized (mPackages) 2852 } // synchronized (mInstallLock) 2853 2854 // Now after opening every single application zip, make sure they 2855 // are all flushed. Not really needed, but keeps things nice and 2856 // tidy. 2857 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2858 Runtime.getRuntime().gc(); 2859 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2860 2861 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2862 FallbackCategoryProvider.loadFallbacks(); 2863 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2864 2865 // The initial scanning above does many calls into installd while 2866 // holding the mPackages lock, but we're mostly interested in yelling 2867 // once we have a booted system. 2868 mInstaller.setWarnIfHeld(mPackages); 2869 2870 // Expose private service for system components to use. 2871 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2872 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2873 } 2874 2875 private void updateInstantAppInstallerLocked(String modifiedPackage) { 2876 // we're only interested in updating the installer appliction when 1) it's not 2877 // already set or 2) the modified package is the installer 2878 if (mInstantAppInstallerActivity != null 2879 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 2880 .equals(modifiedPackage)) { 2881 return; 2882 } 2883 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 2884 } 2885 2886 private static File preparePackageParserCache(boolean isUpgrade) { 2887 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2888 return null; 2889 } 2890 2891 // Disable package parsing on eng builds to allow for faster incremental development. 2892 if ("eng".equals(Build.TYPE)) { 2893 return null; 2894 } 2895 2896 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2897 Slog.i(TAG, "Disabling package parser cache due to system property."); 2898 return null; 2899 } 2900 2901 // The base directory for the package parser cache lives under /data/system/. 2902 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2903 "package_cache"); 2904 if (cacheBaseDir == null) { 2905 return null; 2906 } 2907 2908 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2909 // This also serves to "GC" unused entries when the package cache version changes (which 2910 // can only happen during upgrades). 2911 if (isUpgrade) { 2912 FileUtils.deleteContents(cacheBaseDir); 2913 } 2914 2915 2916 // Return the versioned package cache directory. This is something like 2917 // "/data/system/package_cache/1" 2918 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2919 2920 // The following is a workaround to aid development on non-numbered userdebug 2921 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2922 // the system partition is newer. 2923 // 2924 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2925 // that starts with "eng." to signify that this is an engineering build and not 2926 // destined for release. 2927 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2928 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2929 2930 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2931 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2932 // in general and should not be used for production changes. In this specific case, 2933 // we know that they will work. 2934 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2935 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2936 FileUtils.deleteContents(cacheBaseDir); 2937 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2938 } 2939 } 2940 2941 return cacheDir; 2942 } 2943 2944 @Override 2945 public boolean isFirstBoot() { 2946 return mFirstBoot; 2947 } 2948 2949 @Override 2950 public boolean isOnlyCoreApps() { 2951 return mOnlyCore; 2952 } 2953 2954 @Override 2955 public boolean isUpgrade() { 2956 return mIsUpgrade; 2957 } 2958 2959 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2960 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2961 2962 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2963 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2964 UserHandle.USER_SYSTEM); 2965 if (matches.size() == 1) { 2966 return matches.get(0).getComponentInfo().packageName; 2967 } else if (matches.size() == 0) { 2968 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2969 return null; 2970 } 2971 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2972 } 2973 2974 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2975 synchronized (mPackages) { 2976 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2977 if (libraryEntry == null) { 2978 throw new IllegalStateException("Missing required shared library:" + name); 2979 } 2980 return libraryEntry.apk; 2981 } 2982 } 2983 2984 private @NonNull String getRequiredInstallerLPr() { 2985 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2986 intent.addCategory(Intent.CATEGORY_DEFAULT); 2987 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2988 2989 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2990 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2991 UserHandle.USER_SYSTEM); 2992 if (matches.size() == 1) { 2993 ResolveInfo resolveInfo = matches.get(0); 2994 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2995 throw new RuntimeException("The installer must be a privileged app"); 2996 } 2997 return matches.get(0).getComponentInfo().packageName; 2998 } else { 2999 throw new RuntimeException("There must be exactly one installer; found " + matches); 3000 } 3001 } 3002 3003 private @NonNull String getRequiredUninstallerLPr() { 3004 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3005 intent.addCategory(Intent.CATEGORY_DEFAULT); 3006 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3007 3008 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3009 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3010 UserHandle.USER_SYSTEM); 3011 if (resolveInfo == null || 3012 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3013 throw new RuntimeException("There must be exactly one uninstaller; found " 3014 + resolveInfo); 3015 } 3016 return resolveInfo.getComponentInfo().packageName; 3017 } 3018 3019 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3020 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3021 3022 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3023 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3024 UserHandle.USER_SYSTEM); 3025 ResolveInfo best = null; 3026 final int N = matches.size(); 3027 for (int i = 0; i < N; i++) { 3028 final ResolveInfo cur = matches.get(i); 3029 final String packageName = cur.getComponentInfo().packageName; 3030 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3031 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3032 continue; 3033 } 3034 3035 if (best == null || cur.priority > best.priority) { 3036 best = cur; 3037 } 3038 } 3039 3040 if (best != null) { 3041 return best.getComponentInfo().getComponentName(); 3042 } else { 3043 throw new RuntimeException("There must be at least one intent filter verifier"); 3044 } 3045 } 3046 3047 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3048 final String[] packageArray = 3049 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3050 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3051 if (DEBUG_EPHEMERAL) { 3052 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3053 } 3054 return null; 3055 } 3056 3057 final int callingUid = Binder.getCallingUid(); 3058 final int resolveFlags = 3059 MATCH_DIRECT_BOOT_AWARE 3060 | MATCH_DIRECT_BOOT_UNAWARE 3061 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3062 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3063 final Intent resolverIntent = new Intent(actionName); 3064 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3065 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3066 // temporarily look for the old action 3067 if (resolvers.size() == 0) { 3068 if (DEBUG_EPHEMERAL) { 3069 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3070 } 3071 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3072 resolverIntent.setAction(actionName); 3073 resolvers = queryIntentServicesInternal(resolverIntent, null, 3074 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3075 } 3076 final int N = resolvers.size(); 3077 if (N == 0) { 3078 if (DEBUG_EPHEMERAL) { 3079 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3080 } 3081 return null; 3082 } 3083 3084 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3085 for (int i = 0; i < N; i++) { 3086 final ResolveInfo info = resolvers.get(i); 3087 3088 if (info.serviceInfo == null) { 3089 continue; 3090 } 3091 3092 final String packageName = info.serviceInfo.packageName; 3093 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3094 if (DEBUG_EPHEMERAL) { 3095 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3096 + " pkg: " + packageName + ", info:" + info); 3097 } 3098 continue; 3099 } 3100 3101 if (DEBUG_EPHEMERAL) { 3102 Slog.v(TAG, "Ephemeral resolver found;" 3103 + " pkg: " + packageName + ", info:" + info); 3104 } 3105 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3106 } 3107 if (DEBUG_EPHEMERAL) { 3108 Slog.v(TAG, "Ephemeral resolver NOT found"); 3109 } 3110 return null; 3111 } 3112 3113 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3114 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3115 intent.addCategory(Intent.CATEGORY_DEFAULT); 3116 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3117 3118 final int resolveFlags = 3119 MATCH_DIRECT_BOOT_AWARE 3120 | MATCH_DIRECT_BOOT_UNAWARE 3121 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3122 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3123 resolveFlags, UserHandle.USER_SYSTEM); 3124 // temporarily look for the old action 3125 if (matches.isEmpty()) { 3126 if (DEBUG_EPHEMERAL) { 3127 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3128 } 3129 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3130 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3131 resolveFlags, UserHandle.USER_SYSTEM); 3132 } 3133 Iterator<ResolveInfo> iter = matches.iterator(); 3134 while (iter.hasNext()) { 3135 final ResolveInfo rInfo = iter.next(); 3136 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3137 if (ps != null) { 3138 final PermissionsState permissionsState = ps.getPermissionsState(); 3139 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3140 continue; 3141 } 3142 } 3143 iter.remove(); 3144 } 3145 if (matches.size() == 0) { 3146 return null; 3147 } else if (matches.size() == 1) { 3148 return (ActivityInfo) matches.get(0).getComponentInfo(); 3149 } else { 3150 throw new RuntimeException( 3151 "There must be at most one ephemeral installer; found " + matches); 3152 } 3153 } 3154 3155 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3156 @NonNull ComponentName resolver) { 3157 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3158 .addCategory(Intent.CATEGORY_DEFAULT) 3159 .setPackage(resolver.getPackageName()); 3160 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3161 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3162 UserHandle.USER_SYSTEM); 3163 // temporarily look for the old action 3164 if (matches.isEmpty()) { 3165 if (DEBUG_EPHEMERAL) { 3166 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3167 } 3168 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3169 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3170 UserHandle.USER_SYSTEM); 3171 } 3172 if (matches.isEmpty()) { 3173 return null; 3174 } 3175 return matches.get(0).getComponentInfo().getComponentName(); 3176 } 3177 3178 private void primeDomainVerificationsLPw(int userId) { 3179 if (DEBUG_DOMAIN_VERIFICATION) { 3180 Slog.d(TAG, "Priming domain verifications in user " + userId); 3181 } 3182 3183 SystemConfig systemConfig = SystemConfig.getInstance(); 3184 ArraySet<String> packages = systemConfig.getLinkedApps(); 3185 3186 for (String packageName : packages) { 3187 PackageParser.Package pkg = mPackages.get(packageName); 3188 if (pkg != null) { 3189 if (!pkg.isSystemApp()) { 3190 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3191 continue; 3192 } 3193 3194 ArraySet<String> domains = null; 3195 for (PackageParser.Activity a : pkg.activities) { 3196 for (ActivityIntentInfo filter : a.intents) { 3197 if (hasValidDomains(filter)) { 3198 if (domains == null) { 3199 domains = new ArraySet<String>(); 3200 } 3201 domains.addAll(filter.getHostsList()); 3202 } 3203 } 3204 } 3205 3206 if (domains != null && domains.size() > 0) { 3207 if (DEBUG_DOMAIN_VERIFICATION) { 3208 Slog.v(TAG, " + " + packageName); 3209 } 3210 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3211 // state w.r.t. the formal app-linkage "no verification attempted" state; 3212 // and then 'always' in the per-user state actually used for intent resolution. 3213 final IntentFilterVerificationInfo ivi; 3214 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3215 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3216 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3217 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3218 } else { 3219 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3220 + "' does not handle web links"); 3221 } 3222 } else { 3223 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3224 } 3225 } 3226 3227 scheduleWritePackageRestrictionsLocked(userId); 3228 scheduleWriteSettingsLocked(); 3229 } 3230 3231 private void applyFactoryDefaultBrowserLPw(int userId) { 3232 // The default browser app's package name is stored in a string resource, 3233 // with a product-specific overlay used for vendor customization. 3234 String browserPkg = mContext.getResources().getString( 3235 com.android.internal.R.string.default_browser); 3236 if (!TextUtils.isEmpty(browserPkg)) { 3237 // non-empty string => required to be a known package 3238 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3239 if (ps == null) { 3240 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3241 browserPkg = null; 3242 } else { 3243 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3244 } 3245 } 3246 3247 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3248 // default. If there's more than one, just leave everything alone. 3249 if (browserPkg == null) { 3250 calculateDefaultBrowserLPw(userId); 3251 } 3252 } 3253 3254 private void calculateDefaultBrowserLPw(int userId) { 3255 List<String> allBrowsers = resolveAllBrowserApps(userId); 3256 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3257 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3258 } 3259 3260 private List<String> resolveAllBrowserApps(int userId) { 3261 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3262 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3263 PackageManager.MATCH_ALL, userId); 3264 3265 final int count = list.size(); 3266 List<String> result = new ArrayList<String>(count); 3267 for (int i=0; i<count; i++) { 3268 ResolveInfo info = list.get(i); 3269 if (info.activityInfo == null 3270 || !info.handleAllWebDataURI 3271 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3272 || result.contains(info.activityInfo.packageName)) { 3273 continue; 3274 } 3275 result.add(info.activityInfo.packageName); 3276 } 3277 3278 return result; 3279 } 3280 3281 private boolean packageIsBrowser(String packageName, int userId) { 3282 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3283 PackageManager.MATCH_ALL, userId); 3284 final int N = list.size(); 3285 for (int i = 0; i < N; i++) { 3286 ResolveInfo info = list.get(i); 3287 if (packageName.equals(info.activityInfo.packageName)) { 3288 return true; 3289 } 3290 } 3291 return false; 3292 } 3293 3294 private void checkDefaultBrowser() { 3295 final int myUserId = UserHandle.myUserId(); 3296 final String packageName = getDefaultBrowserPackageName(myUserId); 3297 if (packageName != null) { 3298 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3299 if (info == null) { 3300 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3301 synchronized (mPackages) { 3302 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3303 } 3304 } 3305 } 3306 } 3307 3308 @Override 3309 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3310 throws RemoteException { 3311 try { 3312 return super.onTransact(code, data, reply, flags); 3313 } catch (RuntimeException e) { 3314 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3315 Slog.wtf(TAG, "Package Manager Crash", e); 3316 } 3317 throw e; 3318 } 3319 } 3320 3321 static int[] appendInts(int[] cur, int[] add) { 3322 if (add == null) return cur; 3323 if (cur == null) return add; 3324 final int N = add.length; 3325 for (int i=0; i<N; i++) { 3326 cur = appendInt(cur, add[i]); 3327 } 3328 return cur; 3329 } 3330 3331 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3332 if (!sUserManager.exists(userId)) return null; 3333 if (ps == null) { 3334 return null; 3335 } 3336 final PackageParser.Package p = ps.pkg; 3337 if (p == null) { 3338 return null; 3339 } 3340 // Filter out ephemeral app metadata: 3341 // * The system/shell/root can see metadata for any app 3342 // * An installed app can see metadata for 1) other installed apps 3343 // and 2) ephemeral apps that have explicitly interacted with it 3344 // * Ephemeral apps can only see their own data and exposed installed apps 3345 // * Holding a signature permission allows seeing instant apps 3346 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3347 if (callingAppId != Process.SYSTEM_UID 3348 && callingAppId != Process.SHELL_UID 3349 && callingAppId != Process.ROOT_UID 3350 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3351 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3352 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3353 if (instantAppPackageName != null) { 3354 // ephemeral apps can only get information on themselves or 3355 // installed apps that are exposed. 3356 if (!instantAppPackageName.equals(p.packageName) 3357 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3358 return null; 3359 } 3360 } else { 3361 if (ps.getInstantApp(userId)) { 3362 // only get access to the ephemeral app if we've been granted access 3363 if (!mInstantAppRegistry.isInstantAccessGranted( 3364 userId, callingAppId, ps.appId)) { 3365 return null; 3366 } 3367 } 3368 } 3369 } 3370 3371 final PermissionsState permissionsState = ps.getPermissionsState(); 3372 3373 // Compute GIDs only if requested 3374 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3375 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3376 // Compute granted permissions only if package has requested permissions 3377 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3378 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3379 final PackageUserState state = ps.readUserState(userId); 3380 3381 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3382 && ps.isSystem()) { 3383 flags |= MATCH_ANY_USER; 3384 } 3385 3386 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3387 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3388 3389 if (packageInfo == null) { 3390 return null; 3391 } 3392 3393 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3394 3395 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3396 resolveExternalPackageNameLPr(p); 3397 3398 return packageInfo; 3399 } 3400 3401 @Override 3402 public void checkPackageStartable(String packageName, int userId) { 3403 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3404 3405 synchronized (mPackages) { 3406 final PackageSetting ps = mSettings.mPackages.get(packageName); 3407 if (ps == null) { 3408 throw new SecurityException("Package " + packageName + " was not found!"); 3409 } 3410 3411 if (!ps.getInstalled(userId)) { 3412 throw new SecurityException( 3413 "Package " + packageName + " was not installed for user " + userId + "!"); 3414 } 3415 3416 if (mSafeMode && !ps.isSystem()) { 3417 throw new SecurityException("Package " + packageName + " not a system app!"); 3418 } 3419 3420 if (mFrozenPackages.contains(packageName)) { 3421 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3422 } 3423 3424 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3425 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3426 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3427 } 3428 } 3429 } 3430 3431 @Override 3432 public boolean isPackageAvailable(String packageName, int userId) { 3433 if (!sUserManager.exists(userId)) return false; 3434 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3435 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3436 synchronized (mPackages) { 3437 PackageParser.Package p = mPackages.get(packageName); 3438 if (p != null) { 3439 final PackageSetting ps = (PackageSetting) p.mExtras; 3440 if (ps != null) { 3441 final PackageUserState state = ps.readUserState(userId); 3442 if (state != null) { 3443 return PackageParser.isAvailable(state); 3444 } 3445 } 3446 } 3447 } 3448 return false; 3449 } 3450 3451 @Override 3452 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3453 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3454 flags, userId); 3455 } 3456 3457 @Override 3458 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3459 int flags, int userId) { 3460 return getPackageInfoInternal(versionedPackage.getPackageName(), 3461 // TODO: We will change version code to long, so in the new API it is long 3462 (int) versionedPackage.getVersionCode(), flags, userId); 3463 } 3464 3465 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3466 int flags, int userId) { 3467 if (!sUserManager.exists(userId)) return null; 3468 flags = updateFlagsForPackage(flags, userId, packageName); 3469 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3470 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3471 3472 // reader 3473 synchronized (mPackages) { 3474 // Normalize package name to handle renamed packages and static libs 3475 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3476 3477 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3478 if (matchFactoryOnly) { 3479 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3480 if (ps != null) { 3481 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3482 return null; 3483 } 3484 return generatePackageInfo(ps, flags, userId); 3485 } 3486 } 3487 3488 PackageParser.Package p = mPackages.get(packageName); 3489 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3490 return null; 3491 } 3492 if (DEBUG_PACKAGE_INFO) 3493 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3494 if (p != null) { 3495 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3496 Binder.getCallingUid(), userId)) { 3497 return null; 3498 } 3499 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3500 } 3501 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3502 final PackageSetting ps = mSettings.mPackages.get(packageName); 3503 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3504 return null; 3505 } 3506 return generatePackageInfo(ps, flags, userId); 3507 } 3508 } 3509 return null; 3510 } 3511 3512 3513 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3514 // System/shell/root get to see all static libs 3515 final int appId = UserHandle.getAppId(uid); 3516 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3517 || appId == Process.ROOT_UID) { 3518 return false; 3519 } 3520 3521 // No package means no static lib as it is always on internal storage 3522 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3523 return false; 3524 } 3525 3526 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3527 ps.pkg.staticSharedLibVersion); 3528 if (libEntry == null) { 3529 return false; 3530 } 3531 3532 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3533 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3534 if (uidPackageNames == null) { 3535 return true; 3536 } 3537 3538 for (String uidPackageName : uidPackageNames) { 3539 if (ps.name.equals(uidPackageName)) { 3540 return false; 3541 } 3542 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3543 if (uidPs != null) { 3544 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3545 libEntry.info.getName()); 3546 if (index < 0) { 3547 continue; 3548 } 3549 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3550 return false; 3551 } 3552 } 3553 } 3554 return true; 3555 } 3556 3557 @Override 3558 public String[] currentToCanonicalPackageNames(String[] names) { 3559 String[] out = new String[names.length]; 3560 // reader 3561 synchronized (mPackages) { 3562 for (int i=names.length-1; i>=0; i--) { 3563 PackageSetting ps = mSettings.mPackages.get(names[i]); 3564 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3565 } 3566 } 3567 return out; 3568 } 3569 3570 @Override 3571 public String[] canonicalToCurrentPackageNames(String[] names) { 3572 String[] out = new String[names.length]; 3573 // reader 3574 synchronized (mPackages) { 3575 for (int i=names.length-1; i>=0; i--) { 3576 String cur = mSettings.getRenamedPackageLPr(names[i]); 3577 out[i] = cur != null ? cur : names[i]; 3578 } 3579 } 3580 return out; 3581 } 3582 3583 @Override 3584 public int getPackageUid(String packageName, int flags, int userId) { 3585 if (!sUserManager.exists(userId)) return -1; 3586 flags = updateFlagsForPackage(flags, userId, packageName); 3587 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3588 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3589 3590 // reader 3591 synchronized (mPackages) { 3592 final PackageParser.Package p = mPackages.get(packageName); 3593 if (p != null && p.isMatch(flags)) { 3594 return UserHandle.getUid(userId, p.applicationInfo.uid); 3595 } 3596 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3597 final PackageSetting ps = mSettings.mPackages.get(packageName); 3598 if (ps != null && ps.isMatch(flags)) { 3599 return UserHandle.getUid(userId, ps.appId); 3600 } 3601 } 3602 } 3603 3604 return -1; 3605 } 3606 3607 @Override 3608 public int[] getPackageGids(String packageName, int flags, int userId) { 3609 if (!sUserManager.exists(userId)) return null; 3610 flags = updateFlagsForPackage(flags, userId, packageName); 3611 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3612 false /* requireFullPermission */, false /* checkShell */, 3613 "getPackageGids"); 3614 3615 // reader 3616 synchronized (mPackages) { 3617 final PackageParser.Package p = mPackages.get(packageName); 3618 if (p != null && p.isMatch(flags)) { 3619 PackageSetting ps = (PackageSetting) p.mExtras; 3620 // TODO: Shouldn't this be checking for package installed state for userId and 3621 // return null? 3622 return ps.getPermissionsState().computeGids(userId); 3623 } 3624 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3625 final PackageSetting ps = mSettings.mPackages.get(packageName); 3626 if (ps != null && ps.isMatch(flags)) { 3627 return ps.getPermissionsState().computeGids(userId); 3628 } 3629 } 3630 } 3631 3632 return null; 3633 } 3634 3635 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3636 if (bp.perm != null) { 3637 return PackageParser.generatePermissionInfo(bp.perm, flags); 3638 } 3639 PermissionInfo pi = new PermissionInfo(); 3640 pi.name = bp.name; 3641 pi.packageName = bp.sourcePackage; 3642 pi.nonLocalizedLabel = bp.name; 3643 pi.protectionLevel = bp.protectionLevel; 3644 return pi; 3645 } 3646 3647 @Override 3648 public PermissionInfo getPermissionInfo(String name, int flags) { 3649 // reader 3650 synchronized (mPackages) { 3651 final BasePermission p = mSettings.mPermissions.get(name); 3652 if (p != null) { 3653 return generatePermissionInfo(p, flags); 3654 } 3655 return null; 3656 } 3657 } 3658 3659 @Override 3660 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3661 int flags) { 3662 // reader 3663 synchronized (mPackages) { 3664 if (group != null && !mPermissionGroups.containsKey(group)) { 3665 // This is thrown as NameNotFoundException 3666 return null; 3667 } 3668 3669 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3670 for (BasePermission p : mSettings.mPermissions.values()) { 3671 if (group == null) { 3672 if (p.perm == null || p.perm.info.group == null) { 3673 out.add(generatePermissionInfo(p, flags)); 3674 } 3675 } else { 3676 if (p.perm != null && group.equals(p.perm.info.group)) { 3677 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3678 } 3679 } 3680 } 3681 return new ParceledListSlice<>(out); 3682 } 3683 } 3684 3685 @Override 3686 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3687 // reader 3688 synchronized (mPackages) { 3689 return PackageParser.generatePermissionGroupInfo( 3690 mPermissionGroups.get(name), flags); 3691 } 3692 } 3693 3694 @Override 3695 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3696 // reader 3697 synchronized (mPackages) { 3698 final int N = mPermissionGroups.size(); 3699 ArrayList<PermissionGroupInfo> out 3700 = new ArrayList<PermissionGroupInfo>(N); 3701 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3702 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3703 } 3704 return new ParceledListSlice<>(out); 3705 } 3706 } 3707 3708 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3709 int uid, int userId) { 3710 if (!sUserManager.exists(userId)) return null; 3711 PackageSetting ps = mSettings.mPackages.get(packageName); 3712 if (ps != null) { 3713 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3714 return null; 3715 } 3716 if (ps.pkg == null) { 3717 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3718 if (pInfo != null) { 3719 return pInfo.applicationInfo; 3720 } 3721 return null; 3722 } 3723 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3724 ps.readUserState(userId), userId); 3725 if (ai != null) { 3726 rebaseEnabledOverlays(ai, userId); 3727 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3728 } 3729 return ai; 3730 } 3731 return null; 3732 } 3733 3734 @Override 3735 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3736 if (!sUserManager.exists(userId)) return null; 3737 flags = updateFlagsForApplication(flags, userId, packageName); 3738 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3739 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3740 3741 // writer 3742 synchronized (mPackages) { 3743 // Normalize package name to handle renamed packages and static libs 3744 packageName = resolveInternalPackageNameLPr(packageName, 3745 PackageManager.VERSION_CODE_HIGHEST); 3746 3747 PackageParser.Package p = mPackages.get(packageName); 3748 if (DEBUG_PACKAGE_INFO) Log.v( 3749 TAG, "getApplicationInfo " + packageName 3750 + ": " + p); 3751 if (p != null) { 3752 PackageSetting ps = mSettings.mPackages.get(packageName); 3753 if (ps == null) return null; 3754 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3755 return null; 3756 } 3757 // Note: isEnabledLP() does not apply here - always return info 3758 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3759 p, flags, ps.readUserState(userId), userId); 3760 if (ai != null) { 3761 rebaseEnabledOverlays(ai, userId); 3762 ai.packageName = resolveExternalPackageNameLPr(p); 3763 } 3764 return ai; 3765 } 3766 if ("android".equals(packageName)||"system".equals(packageName)) { 3767 return mAndroidApplication; 3768 } 3769 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3770 // Already generates the external package name 3771 return generateApplicationInfoFromSettingsLPw(packageName, 3772 Binder.getCallingUid(), flags, userId); 3773 } 3774 } 3775 return null; 3776 } 3777 3778 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3779 List<String> paths = new ArrayList<>(); 3780 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3781 mEnabledOverlayPaths.get(userId); 3782 if (userSpecificOverlays != null) { 3783 if (!"android".equals(ai.packageName)) { 3784 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3785 if (frameworkOverlays != null) { 3786 paths.addAll(frameworkOverlays); 3787 } 3788 } 3789 3790 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3791 if (appOverlays != null) { 3792 paths.addAll(appOverlays); 3793 } 3794 } 3795 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3796 } 3797 3798 private String normalizePackageNameLPr(String packageName) { 3799 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3800 return normalizedPackageName != null ? normalizedPackageName : packageName; 3801 } 3802 3803 @Override 3804 public void deletePreloadsFileCache() { 3805 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3806 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3807 } 3808 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3809 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3810 FileUtils.deleteContents(dir); 3811 } 3812 3813 @Override 3814 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3815 final IPackageDataObserver observer) { 3816 mContext.enforceCallingOrSelfPermission( 3817 android.Manifest.permission.CLEAR_APP_CACHE, null); 3818 mHandler.post(() -> { 3819 boolean success = false; 3820 try { 3821 freeStorage(volumeUuid, freeStorageSize, 0); 3822 success = true; 3823 } catch (IOException e) { 3824 Slog.w(TAG, e); 3825 } 3826 if (observer != null) { 3827 try { 3828 observer.onRemoveCompleted(null, success); 3829 } catch (RemoteException e) { 3830 Slog.w(TAG, e); 3831 } 3832 } 3833 }); 3834 } 3835 3836 @Override 3837 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3838 final IntentSender pi) { 3839 mContext.enforceCallingOrSelfPermission( 3840 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3841 mHandler.post(() -> { 3842 boolean success = false; 3843 try { 3844 freeStorage(volumeUuid, freeStorageSize, 0); 3845 success = true; 3846 } catch (IOException e) { 3847 Slog.w(TAG, e); 3848 } 3849 if (pi != null) { 3850 try { 3851 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3852 } catch (SendIntentException e) { 3853 Slog.w(TAG, e); 3854 } 3855 } 3856 }); 3857 } 3858 3859 /** 3860 * Blocking call to clear various types of cached data across the system 3861 * until the requested bytes are available. 3862 */ 3863 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3864 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3865 final File file = storage.findPathForUuid(volumeUuid); 3866 if (file.getUsableSpace() >= bytes) return; 3867 3868 if (ENABLE_FREE_CACHE_V2) { 3869 final boolean aggressive = (storageFlags 3870 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3871 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3872 volumeUuid); 3873 3874 // 1. Pre-flight to determine if we have any chance to succeed 3875 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3876 if (internalVolume && (aggressive || SystemProperties 3877 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3878 deletePreloadsFileCache(); 3879 if (file.getUsableSpace() >= bytes) return; 3880 } 3881 3882 // 3. Consider parsed APK data (aggressive only) 3883 if (internalVolume && aggressive) { 3884 FileUtils.deleteContents(mCacheDir); 3885 if (file.getUsableSpace() >= bytes) return; 3886 } 3887 3888 // 4. Consider cached app data (above quotas) 3889 try { 3890 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3891 } catch (InstallerException ignored) { 3892 } 3893 if (file.getUsableSpace() >= bytes) return; 3894 3895 // 5. Consider shared libraries with refcount=0 and age>2h 3896 // 6. Consider dexopt output (aggressive only) 3897 // 7. Consider ephemeral apps not used in last week 3898 3899 // 8. Consider cached app data (below quotas) 3900 try { 3901 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3902 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3903 } catch (InstallerException ignored) { 3904 } 3905 if (file.getUsableSpace() >= bytes) return; 3906 3907 // 9. Consider DropBox entries 3908 // 10. Consider ephemeral cookies 3909 3910 } else { 3911 try { 3912 mInstaller.freeCache(volumeUuid, bytes, 0); 3913 } catch (InstallerException ignored) { 3914 } 3915 if (file.getUsableSpace() >= bytes) return; 3916 } 3917 3918 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3919 } 3920 3921 /** 3922 * Update given flags based on encryption status of current user. 3923 */ 3924 private int updateFlags(int flags, int userId) { 3925 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3926 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3927 // Caller expressed an explicit opinion about what encryption 3928 // aware/unaware components they want to see, so fall through and 3929 // give them what they want 3930 } else { 3931 // Caller expressed no opinion, so match based on user state 3932 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3933 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3934 } else { 3935 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3936 } 3937 } 3938 return flags; 3939 } 3940 3941 private UserManagerInternal getUserManagerInternal() { 3942 if (mUserManagerInternal == null) { 3943 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3944 } 3945 return mUserManagerInternal; 3946 } 3947 3948 private DeviceIdleController.LocalService getDeviceIdleController() { 3949 if (mDeviceIdleController == null) { 3950 mDeviceIdleController = 3951 LocalServices.getService(DeviceIdleController.LocalService.class); 3952 } 3953 return mDeviceIdleController; 3954 } 3955 3956 /** 3957 * Update given flags when being used to request {@link PackageInfo}. 3958 */ 3959 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3960 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3961 boolean triaged = true; 3962 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3963 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3964 // Caller is asking for component details, so they'd better be 3965 // asking for specific encryption matching behavior, or be triaged 3966 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3967 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3968 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3969 triaged = false; 3970 } 3971 } 3972 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3973 | PackageManager.MATCH_SYSTEM_ONLY 3974 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3975 triaged = false; 3976 } 3977 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3978 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3979 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3980 + Debug.getCallers(5)); 3981 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3982 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3983 // If the caller wants all packages and has a restricted profile associated with it, 3984 // then match all users. This is to make sure that launchers that need to access work 3985 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3986 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3987 flags |= PackageManager.MATCH_ANY_USER; 3988 } 3989 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3990 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3991 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3992 } 3993 return updateFlags(flags, userId); 3994 } 3995 3996 /** 3997 * Update given flags when being used to request {@link ApplicationInfo}. 3998 */ 3999 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4000 return updateFlagsForPackage(flags, userId, cookie); 4001 } 4002 4003 /** 4004 * Update given flags when being used to request {@link ComponentInfo}. 4005 */ 4006 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4007 if (cookie instanceof Intent) { 4008 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4009 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4010 } 4011 } 4012 4013 boolean triaged = true; 4014 // Caller is asking for component details, so they'd better be 4015 // asking for specific encryption matching behavior, or be triaged 4016 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4017 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4018 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4019 triaged = false; 4020 } 4021 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4022 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4023 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4024 } 4025 4026 return updateFlags(flags, userId); 4027 } 4028 4029 /** 4030 * Update given intent when being used to request {@link ResolveInfo}. 4031 */ 4032 private Intent updateIntentForResolve(Intent intent) { 4033 if (intent.getSelector() != null) { 4034 intent = intent.getSelector(); 4035 } 4036 if (DEBUG_PREFERRED) { 4037 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4038 } 4039 return intent; 4040 } 4041 4042 /** 4043 * Update given flags when being used to request {@link ResolveInfo}. 4044 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4045 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4046 * flag set. However, this flag is only honoured in three circumstances: 4047 * <ul> 4048 * <li>when called from a system process</li> 4049 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4050 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4051 * action and a {@code android.intent.category.BROWSABLE} category</li> 4052 * </ul> 4053 */ 4054 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4055 boolean includeInstantApps) { 4056 // Safe mode means we shouldn't match any third-party components 4057 if (mSafeMode) { 4058 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4059 } 4060 if (getInstantAppPackageName(callingUid) != null) { 4061 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4062 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4063 flags |= PackageManager.MATCH_INSTANT; 4064 } else { 4065 // Otherwise, prevent leaking ephemeral components 4066 final boolean isSpecialProcess = 4067 callingUid == Process.SYSTEM_UID 4068 || callingUid == Process.SHELL_UID 4069 || callingUid == 0; 4070 final boolean allowMatchInstant = 4071 (includeInstantApps 4072 && Intent.ACTION_VIEW.equals(intent.getAction()) 4073 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4074 && hasWebURI(intent)) 4075 || isSpecialProcess 4076 || mContext.checkCallingOrSelfPermission( 4077 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4078 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4079 if (!allowMatchInstant) { 4080 flags &= ~PackageManager.MATCH_INSTANT; 4081 } 4082 } 4083 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4084 } 4085 4086 @Override 4087 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4088 if (!sUserManager.exists(userId)) return null; 4089 flags = updateFlagsForComponent(flags, userId, component); 4090 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4091 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4092 synchronized (mPackages) { 4093 PackageParser.Activity a = mActivities.mActivities.get(component); 4094 4095 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4096 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4097 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4098 if (ps == null) return null; 4099 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4100 userId); 4101 } 4102 if (mResolveComponentName.equals(component)) { 4103 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4104 new PackageUserState(), userId); 4105 } 4106 } 4107 return null; 4108 } 4109 4110 @Override 4111 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4112 String resolvedType) { 4113 synchronized (mPackages) { 4114 if (component.equals(mResolveComponentName)) { 4115 // The resolver supports EVERYTHING! 4116 return true; 4117 } 4118 PackageParser.Activity a = mActivities.mActivities.get(component); 4119 if (a == null) { 4120 return false; 4121 } 4122 for (int i=0; i<a.intents.size(); i++) { 4123 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4124 intent.getData(), intent.getCategories(), TAG) >= 0) { 4125 return true; 4126 } 4127 } 4128 return false; 4129 } 4130 } 4131 4132 @Override 4133 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4134 if (!sUserManager.exists(userId)) return null; 4135 flags = updateFlagsForComponent(flags, userId, component); 4136 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4137 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4138 synchronized (mPackages) { 4139 PackageParser.Activity a = mReceivers.mActivities.get(component); 4140 if (DEBUG_PACKAGE_INFO) Log.v( 4141 TAG, "getReceiverInfo " + component + ": " + a); 4142 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4143 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4144 if (ps == null) return null; 4145 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4146 ps.readUserState(userId), userId); 4147 if (ri != null) { 4148 rebaseEnabledOverlays(ri.applicationInfo, userId); 4149 } 4150 return ri; 4151 } 4152 } 4153 return null; 4154 } 4155 4156 @Override 4157 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4158 if (!sUserManager.exists(userId)) return null; 4159 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4160 4161 flags = updateFlagsForPackage(flags, userId, null); 4162 4163 final boolean canSeeStaticLibraries = 4164 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4165 == PERMISSION_GRANTED 4166 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4167 == PERMISSION_GRANTED 4168 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4169 == PERMISSION_GRANTED 4170 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4171 == PERMISSION_GRANTED; 4172 4173 synchronized (mPackages) { 4174 List<SharedLibraryInfo> result = null; 4175 4176 final int libCount = mSharedLibraries.size(); 4177 for (int i = 0; i < libCount; i++) { 4178 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4179 if (versionedLib == null) { 4180 continue; 4181 } 4182 4183 final int versionCount = versionedLib.size(); 4184 for (int j = 0; j < versionCount; j++) { 4185 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4186 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4187 break; 4188 } 4189 final long identity = Binder.clearCallingIdentity(); 4190 try { 4191 // TODO: We will change version code to long, so in the new API it is long 4192 PackageInfo packageInfo = getPackageInfoVersioned( 4193 libInfo.getDeclaringPackage(), flags, userId); 4194 if (packageInfo == null) { 4195 continue; 4196 } 4197 } finally { 4198 Binder.restoreCallingIdentity(identity); 4199 } 4200 4201 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4202 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4203 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4204 4205 if (result == null) { 4206 result = new ArrayList<>(); 4207 } 4208 result.add(resLibInfo); 4209 } 4210 } 4211 4212 return result != null ? new ParceledListSlice<>(result) : null; 4213 } 4214 } 4215 4216 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4217 SharedLibraryInfo libInfo, int flags, int userId) { 4218 List<VersionedPackage> versionedPackages = null; 4219 final int packageCount = mSettings.mPackages.size(); 4220 for (int i = 0; i < packageCount; i++) { 4221 PackageSetting ps = mSettings.mPackages.valueAt(i); 4222 4223 if (ps == null) { 4224 continue; 4225 } 4226 4227 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4228 continue; 4229 } 4230 4231 final String libName = libInfo.getName(); 4232 if (libInfo.isStatic()) { 4233 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4234 if (libIdx < 0) { 4235 continue; 4236 } 4237 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4238 continue; 4239 } 4240 if (versionedPackages == null) { 4241 versionedPackages = new ArrayList<>(); 4242 } 4243 // If the dependent is a static shared lib, use the public package name 4244 String dependentPackageName = ps.name; 4245 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4246 dependentPackageName = ps.pkg.manifestPackageName; 4247 } 4248 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4249 } else if (ps.pkg != null) { 4250 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4251 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4252 if (versionedPackages == null) { 4253 versionedPackages = new ArrayList<>(); 4254 } 4255 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4256 } 4257 } 4258 } 4259 4260 return versionedPackages; 4261 } 4262 4263 @Override 4264 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4265 if (!sUserManager.exists(userId)) return null; 4266 flags = updateFlagsForComponent(flags, userId, component); 4267 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4268 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4269 synchronized (mPackages) { 4270 PackageParser.Service s = mServices.mServices.get(component); 4271 if (DEBUG_PACKAGE_INFO) Log.v( 4272 TAG, "getServiceInfo " + component + ": " + s); 4273 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4274 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4275 if (ps == null) return null; 4276 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4277 ps.readUserState(userId), userId); 4278 if (si != null) { 4279 rebaseEnabledOverlays(si.applicationInfo, userId); 4280 } 4281 return si; 4282 } 4283 } 4284 return null; 4285 } 4286 4287 @Override 4288 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4289 if (!sUserManager.exists(userId)) return null; 4290 flags = updateFlagsForComponent(flags, userId, component); 4291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4292 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4293 synchronized (mPackages) { 4294 PackageParser.Provider p = mProviders.mProviders.get(component); 4295 if (DEBUG_PACKAGE_INFO) Log.v( 4296 TAG, "getProviderInfo " + component + ": " + p); 4297 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4298 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4299 if (ps == null) return null; 4300 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4301 ps.readUserState(userId), userId); 4302 if (pi != null) { 4303 rebaseEnabledOverlays(pi.applicationInfo, userId); 4304 } 4305 return pi; 4306 } 4307 } 4308 return null; 4309 } 4310 4311 @Override 4312 public String[] getSystemSharedLibraryNames() { 4313 synchronized (mPackages) { 4314 Set<String> libs = null; 4315 final int libCount = mSharedLibraries.size(); 4316 for (int i = 0; i < libCount; i++) { 4317 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4318 if (versionedLib == null) { 4319 continue; 4320 } 4321 final int versionCount = versionedLib.size(); 4322 for (int j = 0; j < versionCount; j++) { 4323 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4324 if (!libEntry.info.isStatic()) { 4325 if (libs == null) { 4326 libs = new ArraySet<>(); 4327 } 4328 libs.add(libEntry.info.getName()); 4329 break; 4330 } 4331 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4332 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4333 UserHandle.getUserId(Binder.getCallingUid()))) { 4334 if (libs == null) { 4335 libs = new ArraySet<>(); 4336 } 4337 libs.add(libEntry.info.getName()); 4338 break; 4339 } 4340 } 4341 } 4342 4343 if (libs != null) { 4344 String[] libsArray = new String[libs.size()]; 4345 libs.toArray(libsArray); 4346 return libsArray; 4347 } 4348 4349 return null; 4350 } 4351 } 4352 4353 @Override 4354 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4355 synchronized (mPackages) { 4356 return mServicesSystemSharedLibraryPackageName; 4357 } 4358 } 4359 4360 @Override 4361 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4362 synchronized (mPackages) { 4363 return mSharedSystemSharedLibraryPackageName; 4364 } 4365 } 4366 4367 private void updateSequenceNumberLP(String packageName, int[] userList) { 4368 for (int i = userList.length - 1; i >= 0; --i) { 4369 final int userId = userList[i]; 4370 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4371 if (changedPackages == null) { 4372 changedPackages = new SparseArray<>(); 4373 mChangedPackages.put(userId, changedPackages); 4374 } 4375 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4376 if (sequenceNumbers == null) { 4377 sequenceNumbers = new HashMap<>(); 4378 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4379 } 4380 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4381 if (sequenceNumber != null) { 4382 changedPackages.remove(sequenceNumber); 4383 } 4384 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4385 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4386 } 4387 mChangedPackagesSequenceNumber++; 4388 } 4389 4390 @Override 4391 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4392 synchronized (mPackages) { 4393 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4394 return null; 4395 } 4396 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4397 if (changedPackages == null) { 4398 return null; 4399 } 4400 final List<String> packageNames = 4401 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4402 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4403 final String packageName = changedPackages.get(i); 4404 if (packageName != null) { 4405 packageNames.add(packageName); 4406 } 4407 } 4408 return packageNames.isEmpty() 4409 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4410 } 4411 } 4412 4413 @Override 4414 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4415 ArrayList<FeatureInfo> res; 4416 synchronized (mAvailableFeatures) { 4417 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4418 res.addAll(mAvailableFeatures.values()); 4419 } 4420 final FeatureInfo fi = new FeatureInfo(); 4421 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4422 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4423 res.add(fi); 4424 4425 return new ParceledListSlice<>(res); 4426 } 4427 4428 @Override 4429 public boolean hasSystemFeature(String name, int version) { 4430 synchronized (mAvailableFeatures) { 4431 final FeatureInfo feat = mAvailableFeatures.get(name); 4432 if (feat == null) { 4433 return false; 4434 } else { 4435 return feat.version >= version; 4436 } 4437 } 4438 } 4439 4440 @Override 4441 public int checkPermission(String permName, String pkgName, int userId) { 4442 if (!sUserManager.exists(userId)) { 4443 return PackageManager.PERMISSION_DENIED; 4444 } 4445 4446 synchronized (mPackages) { 4447 final PackageParser.Package p = mPackages.get(pkgName); 4448 if (p != null && p.mExtras != null) { 4449 final PackageSetting ps = (PackageSetting) p.mExtras; 4450 final PermissionsState permissionsState = ps.getPermissionsState(); 4451 if (permissionsState.hasPermission(permName, userId)) { 4452 return PackageManager.PERMISSION_GRANTED; 4453 } 4454 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4455 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4456 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4457 return PackageManager.PERMISSION_GRANTED; 4458 } 4459 } 4460 } 4461 4462 return PackageManager.PERMISSION_DENIED; 4463 } 4464 4465 @Override 4466 public int checkUidPermission(String permName, int uid) { 4467 final int userId = UserHandle.getUserId(uid); 4468 4469 if (!sUserManager.exists(userId)) { 4470 return PackageManager.PERMISSION_DENIED; 4471 } 4472 4473 synchronized (mPackages) { 4474 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4475 if (obj != null) { 4476 final SettingBase ps = (SettingBase) obj; 4477 final PermissionsState permissionsState = ps.getPermissionsState(); 4478 if (permissionsState.hasPermission(permName, userId)) { 4479 return PackageManager.PERMISSION_GRANTED; 4480 } 4481 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4482 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4483 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4484 return PackageManager.PERMISSION_GRANTED; 4485 } 4486 } else { 4487 ArraySet<String> perms = mSystemPermissions.get(uid); 4488 if (perms != null) { 4489 if (perms.contains(permName)) { 4490 return PackageManager.PERMISSION_GRANTED; 4491 } 4492 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4493 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4494 return PackageManager.PERMISSION_GRANTED; 4495 } 4496 } 4497 } 4498 } 4499 4500 return PackageManager.PERMISSION_DENIED; 4501 } 4502 4503 @Override 4504 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4505 if (UserHandle.getCallingUserId() != userId) { 4506 mContext.enforceCallingPermission( 4507 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4508 "isPermissionRevokedByPolicy for user " + userId); 4509 } 4510 4511 if (checkPermission(permission, packageName, userId) 4512 == PackageManager.PERMISSION_GRANTED) { 4513 return false; 4514 } 4515 4516 final long identity = Binder.clearCallingIdentity(); 4517 try { 4518 final int flags = getPermissionFlags(permission, packageName, userId); 4519 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4520 } finally { 4521 Binder.restoreCallingIdentity(identity); 4522 } 4523 } 4524 4525 @Override 4526 public String getPermissionControllerPackageName() { 4527 synchronized (mPackages) { 4528 return mRequiredInstallerPackage; 4529 } 4530 } 4531 4532 /** 4533 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4534 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4535 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4536 * @param message the message to log on security exception 4537 */ 4538 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4539 boolean checkShell, String message) { 4540 if (userId < 0) { 4541 throw new IllegalArgumentException("Invalid userId " + userId); 4542 } 4543 if (checkShell) { 4544 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4545 } 4546 if (userId == UserHandle.getUserId(callingUid)) return; 4547 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4548 if (requireFullPermission) { 4549 mContext.enforceCallingOrSelfPermission( 4550 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4551 } else { 4552 try { 4553 mContext.enforceCallingOrSelfPermission( 4554 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4555 } catch (SecurityException se) { 4556 mContext.enforceCallingOrSelfPermission( 4557 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4558 } 4559 } 4560 } 4561 } 4562 4563 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4564 if (callingUid == Process.SHELL_UID) { 4565 if (userHandle >= 0 4566 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4567 throw new SecurityException("Shell does not have permission to access user " 4568 + userHandle); 4569 } else if (userHandle < 0) { 4570 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4571 + Debug.getCallers(3)); 4572 } 4573 } 4574 } 4575 4576 private BasePermission findPermissionTreeLP(String permName) { 4577 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4578 if (permName.startsWith(bp.name) && 4579 permName.length() > bp.name.length() && 4580 permName.charAt(bp.name.length()) == '.') { 4581 return bp; 4582 } 4583 } 4584 return null; 4585 } 4586 4587 private BasePermission checkPermissionTreeLP(String permName) { 4588 if (permName != null) { 4589 BasePermission bp = findPermissionTreeLP(permName); 4590 if (bp != null) { 4591 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4592 return bp; 4593 } 4594 throw new SecurityException("Calling uid " 4595 + Binder.getCallingUid() 4596 + " is not allowed to add to permission tree " 4597 + bp.name + " owned by uid " + bp.uid); 4598 } 4599 } 4600 throw new SecurityException("No permission tree found for " + permName); 4601 } 4602 4603 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4604 if (s1 == null) { 4605 return s2 == null; 4606 } 4607 if (s2 == null) { 4608 return false; 4609 } 4610 if (s1.getClass() != s2.getClass()) { 4611 return false; 4612 } 4613 return s1.equals(s2); 4614 } 4615 4616 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4617 if (pi1.icon != pi2.icon) return false; 4618 if (pi1.logo != pi2.logo) return false; 4619 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4620 if (!compareStrings(pi1.name, pi2.name)) return false; 4621 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4622 // We'll take care of setting this one. 4623 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4624 // These are not currently stored in settings. 4625 //if (!compareStrings(pi1.group, pi2.group)) return false; 4626 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4627 //if (pi1.labelRes != pi2.labelRes) return false; 4628 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4629 return true; 4630 } 4631 4632 int permissionInfoFootprint(PermissionInfo info) { 4633 int size = info.name.length(); 4634 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4635 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4636 return size; 4637 } 4638 4639 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4640 int size = 0; 4641 for (BasePermission perm : mSettings.mPermissions.values()) { 4642 if (perm.uid == tree.uid) { 4643 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4644 } 4645 } 4646 return size; 4647 } 4648 4649 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4650 // We calculate the max size of permissions defined by this uid and throw 4651 // if that plus the size of 'info' would exceed our stated maximum. 4652 if (tree.uid != Process.SYSTEM_UID) { 4653 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4654 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4655 throw new SecurityException("Permission tree size cap exceeded"); 4656 } 4657 } 4658 } 4659 4660 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4661 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4662 throw new SecurityException("Label must be specified in permission"); 4663 } 4664 BasePermission tree = checkPermissionTreeLP(info.name); 4665 BasePermission bp = mSettings.mPermissions.get(info.name); 4666 boolean added = bp == null; 4667 boolean changed = true; 4668 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4669 if (added) { 4670 enforcePermissionCapLocked(info, tree); 4671 bp = new BasePermission(info.name, tree.sourcePackage, 4672 BasePermission.TYPE_DYNAMIC); 4673 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4674 throw new SecurityException( 4675 "Not allowed to modify non-dynamic permission " 4676 + info.name); 4677 } else { 4678 if (bp.protectionLevel == fixedLevel 4679 && bp.perm.owner.equals(tree.perm.owner) 4680 && bp.uid == tree.uid 4681 && comparePermissionInfos(bp.perm.info, info)) { 4682 changed = false; 4683 } 4684 } 4685 bp.protectionLevel = fixedLevel; 4686 info = new PermissionInfo(info); 4687 info.protectionLevel = fixedLevel; 4688 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4689 bp.perm.info.packageName = tree.perm.info.packageName; 4690 bp.uid = tree.uid; 4691 if (added) { 4692 mSettings.mPermissions.put(info.name, bp); 4693 } 4694 if (changed) { 4695 if (!async) { 4696 mSettings.writeLPr(); 4697 } else { 4698 scheduleWriteSettingsLocked(); 4699 } 4700 } 4701 return added; 4702 } 4703 4704 @Override 4705 public boolean addPermission(PermissionInfo info) { 4706 synchronized (mPackages) { 4707 return addPermissionLocked(info, false); 4708 } 4709 } 4710 4711 @Override 4712 public boolean addPermissionAsync(PermissionInfo info) { 4713 synchronized (mPackages) { 4714 return addPermissionLocked(info, true); 4715 } 4716 } 4717 4718 @Override 4719 public void removePermission(String name) { 4720 synchronized (mPackages) { 4721 checkPermissionTreeLP(name); 4722 BasePermission bp = mSettings.mPermissions.get(name); 4723 if (bp != null) { 4724 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4725 throw new SecurityException( 4726 "Not allowed to modify non-dynamic permission " 4727 + name); 4728 } 4729 mSettings.mPermissions.remove(name); 4730 mSettings.writeLPr(); 4731 } 4732 } 4733 } 4734 4735 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4736 BasePermission bp) { 4737 int index = pkg.requestedPermissions.indexOf(bp.name); 4738 if (index == -1) { 4739 throw new SecurityException("Package " + pkg.packageName 4740 + " has not requested permission " + bp.name); 4741 } 4742 if (!bp.isRuntime() && !bp.isDevelopment()) { 4743 throw new SecurityException("Permission " + bp.name 4744 + " is not a changeable permission type"); 4745 } 4746 } 4747 4748 @Override 4749 public void grantRuntimePermission(String packageName, String name, final int userId) { 4750 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4751 } 4752 4753 private void grantRuntimePermission(String packageName, String name, final int userId, 4754 boolean overridePolicy) { 4755 if (!sUserManager.exists(userId)) { 4756 Log.e(TAG, "No such user:" + userId); 4757 return; 4758 } 4759 4760 mContext.enforceCallingOrSelfPermission( 4761 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4762 "grantRuntimePermission"); 4763 4764 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4765 true /* requireFullPermission */, true /* checkShell */, 4766 "grantRuntimePermission"); 4767 4768 final int uid; 4769 final SettingBase sb; 4770 4771 synchronized (mPackages) { 4772 final PackageParser.Package pkg = mPackages.get(packageName); 4773 if (pkg == null) { 4774 throw new IllegalArgumentException("Unknown package: " + packageName); 4775 } 4776 4777 final BasePermission bp = mSettings.mPermissions.get(name); 4778 if (bp == null) { 4779 throw new IllegalArgumentException("Unknown permission: " + name); 4780 } 4781 4782 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4783 4784 // If a permission review is required for legacy apps we represent 4785 // their permissions as always granted runtime ones since we need 4786 // to keep the review required permission flag per user while an 4787 // install permission's state is shared across all users. 4788 if (mPermissionReviewRequired 4789 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4790 && bp.isRuntime()) { 4791 return; 4792 } 4793 4794 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4795 sb = (SettingBase) pkg.mExtras; 4796 if (sb == null) { 4797 throw new IllegalArgumentException("Unknown package: " + packageName); 4798 } 4799 4800 final PermissionsState permissionsState = sb.getPermissionsState(); 4801 4802 final int flags = permissionsState.getPermissionFlags(name, userId); 4803 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4804 throw new SecurityException("Cannot grant system fixed permission " 4805 + name + " for package " + packageName); 4806 } 4807 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4808 throw new SecurityException("Cannot grant policy fixed permission " 4809 + name + " for package " + packageName); 4810 } 4811 4812 if (bp.isDevelopment()) { 4813 // Development permissions must be handled specially, since they are not 4814 // normal runtime permissions. For now they apply to all users. 4815 if (permissionsState.grantInstallPermission(bp) != 4816 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4817 scheduleWriteSettingsLocked(); 4818 } 4819 return; 4820 } 4821 4822 final PackageSetting ps = mSettings.mPackages.get(packageName); 4823 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4824 throw new SecurityException("Cannot grant non-ephemeral permission" 4825 + name + " for package " + packageName); 4826 } 4827 4828 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4829 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4830 return; 4831 } 4832 4833 final int result = permissionsState.grantRuntimePermission(bp, userId); 4834 switch (result) { 4835 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4836 return; 4837 } 4838 4839 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4840 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4841 mHandler.post(new Runnable() { 4842 @Override 4843 public void run() { 4844 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4845 } 4846 }); 4847 } 4848 break; 4849 } 4850 4851 if (bp.isRuntime()) { 4852 logPermissionGranted(mContext, name, packageName); 4853 } 4854 4855 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4856 4857 // Not critical if that is lost - app has to request again. 4858 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4859 } 4860 4861 // Only need to do this if user is initialized. Otherwise it's a new user 4862 // and there are no processes running as the user yet and there's no need 4863 // to make an expensive call to remount processes for the changed permissions. 4864 if (READ_EXTERNAL_STORAGE.equals(name) 4865 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4866 final long token = Binder.clearCallingIdentity(); 4867 try { 4868 if (sUserManager.isInitialized(userId)) { 4869 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4870 StorageManagerInternal.class); 4871 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4872 } 4873 } finally { 4874 Binder.restoreCallingIdentity(token); 4875 } 4876 } 4877 } 4878 4879 @Override 4880 public void revokeRuntimePermission(String packageName, String name, int userId) { 4881 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4882 } 4883 4884 private void revokeRuntimePermission(String packageName, String name, int userId, 4885 boolean overridePolicy) { 4886 if (!sUserManager.exists(userId)) { 4887 Log.e(TAG, "No such user:" + userId); 4888 return; 4889 } 4890 4891 mContext.enforceCallingOrSelfPermission( 4892 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4893 "revokeRuntimePermission"); 4894 4895 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4896 true /* requireFullPermission */, true /* checkShell */, 4897 "revokeRuntimePermission"); 4898 4899 final int appId; 4900 4901 synchronized (mPackages) { 4902 final PackageParser.Package pkg = mPackages.get(packageName); 4903 if (pkg == null) { 4904 throw new IllegalArgumentException("Unknown package: " + packageName); 4905 } 4906 4907 final BasePermission bp = mSettings.mPermissions.get(name); 4908 if (bp == null) { 4909 throw new IllegalArgumentException("Unknown permission: " + name); 4910 } 4911 4912 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4913 4914 // If a permission review is required for legacy apps we represent 4915 // their permissions as always granted runtime ones since we need 4916 // to keep the review required permission flag per user while an 4917 // install permission's state is shared across all users. 4918 if (mPermissionReviewRequired 4919 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4920 && bp.isRuntime()) { 4921 return; 4922 } 4923 4924 SettingBase sb = (SettingBase) pkg.mExtras; 4925 if (sb == null) { 4926 throw new IllegalArgumentException("Unknown package: " + packageName); 4927 } 4928 4929 final PermissionsState permissionsState = sb.getPermissionsState(); 4930 4931 final int flags = permissionsState.getPermissionFlags(name, userId); 4932 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4933 throw new SecurityException("Cannot revoke system fixed permission " 4934 + name + " for package " + packageName); 4935 } 4936 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4937 throw new SecurityException("Cannot revoke policy fixed permission " 4938 + name + " for package " + packageName); 4939 } 4940 4941 if (bp.isDevelopment()) { 4942 // Development permissions must be handled specially, since they are not 4943 // normal runtime permissions. For now they apply to all users. 4944 if (permissionsState.revokeInstallPermission(bp) != 4945 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4946 scheduleWriteSettingsLocked(); 4947 } 4948 return; 4949 } 4950 4951 if (permissionsState.revokeRuntimePermission(bp, userId) == 4952 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4953 return; 4954 } 4955 4956 if (bp.isRuntime()) { 4957 logPermissionRevoked(mContext, name, packageName); 4958 } 4959 4960 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4961 4962 // Critical, after this call app should never have the permission. 4963 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4964 4965 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4966 } 4967 4968 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4969 } 4970 4971 /** 4972 * Get the first event id for the permission. 4973 * 4974 * <p>There are four events for each permission: <ul> 4975 * <li>Request permission: first id + 0</li> 4976 * <li>Grant permission: first id + 1</li> 4977 * <li>Request for permission denied: first id + 2</li> 4978 * <li>Revoke permission: first id + 3</li> 4979 * </ul></p> 4980 * 4981 * @param name name of the permission 4982 * 4983 * @return The first event id for the permission 4984 */ 4985 private static int getBaseEventId(@NonNull String name) { 4986 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4987 4988 if (eventIdIndex == -1) { 4989 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4990 || "user".equals(Build.TYPE)) { 4991 Log.i(TAG, "Unknown permission " + name); 4992 4993 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4994 } else { 4995 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4996 // 4997 // Also update 4998 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4999 // - metrics_constants.proto 5000 throw new IllegalStateException("Unknown permission " + name); 5001 } 5002 } 5003 5004 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5005 } 5006 5007 /** 5008 * Log that a permission was revoked. 5009 * 5010 * @param context Context of the caller 5011 * @param name name of the permission 5012 * @param packageName package permission if for 5013 */ 5014 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5015 @NonNull String packageName) { 5016 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5017 } 5018 5019 /** 5020 * Log that a permission request was granted. 5021 * 5022 * @param context Context of the caller 5023 * @param name name of the permission 5024 * @param packageName package permission if for 5025 */ 5026 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5027 @NonNull String packageName) { 5028 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5029 } 5030 5031 @Override 5032 public void resetRuntimePermissions() { 5033 mContext.enforceCallingOrSelfPermission( 5034 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5035 "revokeRuntimePermission"); 5036 5037 int callingUid = Binder.getCallingUid(); 5038 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5039 mContext.enforceCallingOrSelfPermission( 5040 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5041 "resetRuntimePermissions"); 5042 } 5043 5044 synchronized (mPackages) { 5045 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5046 for (int userId : UserManagerService.getInstance().getUserIds()) { 5047 final int packageCount = mPackages.size(); 5048 for (int i = 0; i < packageCount; i++) { 5049 PackageParser.Package pkg = mPackages.valueAt(i); 5050 if (!(pkg.mExtras instanceof PackageSetting)) { 5051 continue; 5052 } 5053 PackageSetting ps = (PackageSetting) pkg.mExtras; 5054 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5055 } 5056 } 5057 } 5058 } 5059 5060 @Override 5061 public int getPermissionFlags(String name, String packageName, int userId) { 5062 if (!sUserManager.exists(userId)) { 5063 return 0; 5064 } 5065 5066 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5067 5068 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5069 true /* requireFullPermission */, false /* checkShell */, 5070 "getPermissionFlags"); 5071 5072 synchronized (mPackages) { 5073 final PackageParser.Package pkg = mPackages.get(packageName); 5074 if (pkg == null) { 5075 return 0; 5076 } 5077 5078 final BasePermission bp = mSettings.mPermissions.get(name); 5079 if (bp == null) { 5080 return 0; 5081 } 5082 5083 SettingBase sb = (SettingBase) pkg.mExtras; 5084 if (sb == null) { 5085 return 0; 5086 } 5087 5088 PermissionsState permissionsState = sb.getPermissionsState(); 5089 return permissionsState.getPermissionFlags(name, userId); 5090 } 5091 } 5092 5093 @Override 5094 public void updatePermissionFlags(String name, String packageName, int flagMask, 5095 int flagValues, int userId) { 5096 if (!sUserManager.exists(userId)) { 5097 return; 5098 } 5099 5100 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5101 5102 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5103 true /* requireFullPermission */, true /* checkShell */, 5104 "updatePermissionFlags"); 5105 5106 // Only the system can change these flags and nothing else. 5107 if (getCallingUid() != Process.SYSTEM_UID) { 5108 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5109 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5110 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5111 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5112 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5113 } 5114 5115 synchronized (mPackages) { 5116 final PackageParser.Package pkg = mPackages.get(packageName); 5117 if (pkg == null) { 5118 throw new IllegalArgumentException("Unknown package: " + packageName); 5119 } 5120 5121 final BasePermission bp = mSettings.mPermissions.get(name); 5122 if (bp == null) { 5123 throw new IllegalArgumentException("Unknown permission: " + name); 5124 } 5125 5126 SettingBase sb = (SettingBase) pkg.mExtras; 5127 if (sb == null) { 5128 throw new IllegalArgumentException("Unknown package: " + packageName); 5129 } 5130 5131 PermissionsState permissionsState = sb.getPermissionsState(); 5132 5133 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5134 5135 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5136 // Install and runtime permissions are stored in different places, 5137 // so figure out what permission changed and persist the change. 5138 if (permissionsState.getInstallPermissionState(name) != null) { 5139 scheduleWriteSettingsLocked(); 5140 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5141 || hadState) { 5142 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5143 } 5144 } 5145 } 5146 } 5147 5148 /** 5149 * Update the permission flags for all packages and runtime permissions of a user in order 5150 * to allow device or profile owner to remove POLICY_FIXED. 5151 */ 5152 @Override 5153 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5154 if (!sUserManager.exists(userId)) { 5155 return; 5156 } 5157 5158 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5159 5160 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5161 true /* requireFullPermission */, true /* checkShell */, 5162 "updatePermissionFlagsForAllApps"); 5163 5164 // Only the system can change system fixed flags. 5165 if (getCallingUid() != Process.SYSTEM_UID) { 5166 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5167 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5168 } 5169 5170 synchronized (mPackages) { 5171 boolean changed = false; 5172 final int packageCount = mPackages.size(); 5173 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5174 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5175 SettingBase sb = (SettingBase) pkg.mExtras; 5176 if (sb == null) { 5177 continue; 5178 } 5179 PermissionsState permissionsState = sb.getPermissionsState(); 5180 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5181 userId, flagMask, flagValues); 5182 } 5183 if (changed) { 5184 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5185 } 5186 } 5187 } 5188 5189 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5190 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5191 != PackageManager.PERMISSION_GRANTED 5192 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5193 != PackageManager.PERMISSION_GRANTED) { 5194 throw new SecurityException(message + " requires " 5195 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5196 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5197 } 5198 } 5199 5200 @Override 5201 public boolean shouldShowRequestPermissionRationale(String permissionName, 5202 String packageName, int userId) { 5203 if (UserHandle.getCallingUserId() != userId) { 5204 mContext.enforceCallingPermission( 5205 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5206 "canShowRequestPermissionRationale for user " + userId); 5207 } 5208 5209 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5210 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5211 return false; 5212 } 5213 5214 if (checkPermission(permissionName, packageName, userId) 5215 == PackageManager.PERMISSION_GRANTED) { 5216 return false; 5217 } 5218 5219 final int flags; 5220 5221 final long identity = Binder.clearCallingIdentity(); 5222 try { 5223 flags = getPermissionFlags(permissionName, 5224 packageName, userId); 5225 } finally { 5226 Binder.restoreCallingIdentity(identity); 5227 } 5228 5229 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5230 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5231 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5232 5233 if ((flags & fixedFlags) != 0) { 5234 return false; 5235 } 5236 5237 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5238 } 5239 5240 @Override 5241 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5242 mContext.enforceCallingOrSelfPermission( 5243 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5244 "addOnPermissionsChangeListener"); 5245 5246 synchronized (mPackages) { 5247 mOnPermissionChangeListeners.addListenerLocked(listener); 5248 } 5249 } 5250 5251 @Override 5252 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5253 synchronized (mPackages) { 5254 mOnPermissionChangeListeners.removeListenerLocked(listener); 5255 } 5256 } 5257 5258 @Override 5259 public boolean isProtectedBroadcast(String actionName) { 5260 synchronized (mPackages) { 5261 if (mProtectedBroadcasts.contains(actionName)) { 5262 return true; 5263 } else if (actionName != null) { 5264 // TODO: remove these terrible hacks 5265 if (actionName.startsWith("android.net.netmon.lingerExpired") 5266 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5267 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5268 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5269 return true; 5270 } 5271 } 5272 } 5273 return false; 5274 } 5275 5276 @Override 5277 public int checkSignatures(String pkg1, String pkg2) { 5278 synchronized (mPackages) { 5279 final PackageParser.Package p1 = mPackages.get(pkg1); 5280 final PackageParser.Package p2 = mPackages.get(pkg2); 5281 if (p1 == null || p1.mExtras == null 5282 || p2 == null || p2.mExtras == null) { 5283 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5284 } 5285 return compareSignatures(p1.mSignatures, p2.mSignatures); 5286 } 5287 } 5288 5289 @Override 5290 public int checkUidSignatures(int uid1, int uid2) { 5291 // Map to base uids. 5292 uid1 = UserHandle.getAppId(uid1); 5293 uid2 = UserHandle.getAppId(uid2); 5294 // reader 5295 synchronized (mPackages) { 5296 Signature[] s1; 5297 Signature[] s2; 5298 Object obj = mSettings.getUserIdLPr(uid1); 5299 if (obj != null) { 5300 if (obj instanceof SharedUserSetting) { 5301 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5302 } else if (obj instanceof PackageSetting) { 5303 s1 = ((PackageSetting)obj).signatures.mSignatures; 5304 } else { 5305 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5306 } 5307 } else { 5308 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5309 } 5310 obj = mSettings.getUserIdLPr(uid2); 5311 if (obj != null) { 5312 if (obj instanceof SharedUserSetting) { 5313 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5314 } else if (obj instanceof PackageSetting) { 5315 s2 = ((PackageSetting)obj).signatures.mSignatures; 5316 } else { 5317 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5318 } 5319 } else { 5320 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5321 } 5322 return compareSignatures(s1, s2); 5323 } 5324 } 5325 5326 /** 5327 * This method should typically only be used when granting or revoking 5328 * permissions, since the app may immediately restart after this call. 5329 * <p> 5330 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5331 * guard your work against the app being relaunched. 5332 */ 5333 private void killUid(int appId, int userId, String reason) { 5334 final long identity = Binder.clearCallingIdentity(); 5335 try { 5336 IActivityManager am = ActivityManager.getService(); 5337 if (am != null) { 5338 try { 5339 am.killUid(appId, userId, reason); 5340 } catch (RemoteException e) { 5341 /* ignore - same process */ 5342 } 5343 } 5344 } finally { 5345 Binder.restoreCallingIdentity(identity); 5346 } 5347 } 5348 5349 /** 5350 * Compares two sets of signatures. Returns: 5351 * <br /> 5352 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5353 * <br /> 5354 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5355 * <br /> 5356 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5357 * <br /> 5358 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5359 * <br /> 5360 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5361 */ 5362 static int compareSignatures(Signature[] s1, Signature[] s2) { 5363 if (s1 == null) { 5364 return s2 == null 5365 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5366 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5367 } 5368 5369 if (s2 == null) { 5370 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5371 } 5372 5373 if (s1.length != s2.length) { 5374 return PackageManager.SIGNATURE_NO_MATCH; 5375 } 5376 5377 // Since both signature sets are of size 1, we can compare without HashSets. 5378 if (s1.length == 1) { 5379 return s1[0].equals(s2[0]) ? 5380 PackageManager.SIGNATURE_MATCH : 5381 PackageManager.SIGNATURE_NO_MATCH; 5382 } 5383 5384 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5385 for (Signature sig : s1) { 5386 set1.add(sig); 5387 } 5388 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5389 for (Signature sig : s2) { 5390 set2.add(sig); 5391 } 5392 // Make sure s2 contains all signatures in s1. 5393 if (set1.equals(set2)) { 5394 return PackageManager.SIGNATURE_MATCH; 5395 } 5396 return PackageManager.SIGNATURE_NO_MATCH; 5397 } 5398 5399 /** 5400 * If the database version for this type of package (internal storage or 5401 * external storage) is less than the version where package signatures 5402 * were updated, return true. 5403 */ 5404 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5405 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5406 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5407 } 5408 5409 /** 5410 * Used for backward compatibility to make sure any packages with 5411 * certificate chains get upgraded to the new style. {@code existingSigs} 5412 * will be in the old format (since they were stored on disk from before the 5413 * system upgrade) and {@code scannedSigs} will be in the newer format. 5414 */ 5415 private int compareSignaturesCompat(PackageSignatures existingSigs, 5416 PackageParser.Package scannedPkg) { 5417 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5418 return PackageManager.SIGNATURE_NO_MATCH; 5419 } 5420 5421 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5422 for (Signature sig : existingSigs.mSignatures) { 5423 existingSet.add(sig); 5424 } 5425 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5426 for (Signature sig : scannedPkg.mSignatures) { 5427 try { 5428 Signature[] chainSignatures = sig.getChainSignatures(); 5429 for (Signature chainSig : chainSignatures) { 5430 scannedCompatSet.add(chainSig); 5431 } 5432 } catch (CertificateEncodingException e) { 5433 scannedCompatSet.add(sig); 5434 } 5435 } 5436 /* 5437 * Make sure the expanded scanned set contains all signatures in the 5438 * existing one. 5439 */ 5440 if (scannedCompatSet.equals(existingSet)) { 5441 // Migrate the old signatures to the new scheme. 5442 existingSigs.assignSignatures(scannedPkg.mSignatures); 5443 // The new KeySets will be re-added later in the scanning process. 5444 synchronized (mPackages) { 5445 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5446 } 5447 return PackageManager.SIGNATURE_MATCH; 5448 } 5449 return PackageManager.SIGNATURE_NO_MATCH; 5450 } 5451 5452 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5453 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5454 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5455 } 5456 5457 private int compareSignaturesRecover(PackageSignatures existingSigs, 5458 PackageParser.Package scannedPkg) { 5459 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5460 return PackageManager.SIGNATURE_NO_MATCH; 5461 } 5462 5463 String msg = null; 5464 try { 5465 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5466 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5467 + scannedPkg.packageName); 5468 return PackageManager.SIGNATURE_MATCH; 5469 } 5470 } catch (CertificateException e) { 5471 msg = e.getMessage(); 5472 } 5473 5474 logCriticalInfo(Log.INFO, 5475 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5476 return PackageManager.SIGNATURE_NO_MATCH; 5477 } 5478 5479 @Override 5480 public List<String> getAllPackages() { 5481 synchronized (mPackages) { 5482 return new ArrayList<String>(mPackages.keySet()); 5483 } 5484 } 5485 5486 @Override 5487 public String[] getPackagesForUid(int uid) { 5488 final int userId = UserHandle.getUserId(uid); 5489 uid = UserHandle.getAppId(uid); 5490 // reader 5491 synchronized (mPackages) { 5492 Object obj = mSettings.getUserIdLPr(uid); 5493 if (obj instanceof SharedUserSetting) { 5494 final SharedUserSetting sus = (SharedUserSetting) obj; 5495 final int N = sus.packages.size(); 5496 String[] res = new String[N]; 5497 final Iterator<PackageSetting> it = sus.packages.iterator(); 5498 int i = 0; 5499 while (it.hasNext()) { 5500 PackageSetting ps = it.next(); 5501 if (ps.getInstalled(userId)) { 5502 res[i++] = ps.name; 5503 } else { 5504 res = ArrayUtils.removeElement(String.class, res, res[i]); 5505 } 5506 } 5507 return res; 5508 } else if (obj instanceof PackageSetting) { 5509 final PackageSetting ps = (PackageSetting) obj; 5510 if (ps.getInstalled(userId)) { 5511 return new String[]{ps.name}; 5512 } 5513 } 5514 } 5515 return null; 5516 } 5517 5518 @Override 5519 public String getNameForUid(int uid) { 5520 // reader 5521 synchronized (mPackages) { 5522 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5523 if (obj instanceof SharedUserSetting) { 5524 final SharedUserSetting sus = (SharedUserSetting) obj; 5525 return sus.name + ":" + sus.userId; 5526 } else if (obj instanceof PackageSetting) { 5527 final PackageSetting ps = (PackageSetting) obj; 5528 return ps.name; 5529 } 5530 } 5531 return null; 5532 } 5533 5534 @Override 5535 public int getUidForSharedUser(String sharedUserName) { 5536 if(sharedUserName == null) { 5537 return -1; 5538 } 5539 // reader 5540 synchronized (mPackages) { 5541 SharedUserSetting suid; 5542 try { 5543 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5544 if (suid != null) { 5545 return suid.userId; 5546 } 5547 } catch (PackageManagerException ignore) { 5548 // can't happen, but, still need to catch it 5549 } 5550 return -1; 5551 } 5552 } 5553 5554 @Override 5555 public int getFlagsForUid(int uid) { 5556 synchronized (mPackages) { 5557 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5558 if (obj instanceof SharedUserSetting) { 5559 final SharedUserSetting sus = (SharedUserSetting) obj; 5560 return sus.pkgFlags; 5561 } else if (obj instanceof PackageSetting) { 5562 final PackageSetting ps = (PackageSetting) obj; 5563 return ps.pkgFlags; 5564 } 5565 } 5566 return 0; 5567 } 5568 5569 @Override 5570 public int getPrivateFlagsForUid(int uid) { 5571 synchronized (mPackages) { 5572 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5573 if (obj instanceof SharedUserSetting) { 5574 final SharedUserSetting sus = (SharedUserSetting) obj; 5575 return sus.pkgPrivateFlags; 5576 } else if (obj instanceof PackageSetting) { 5577 final PackageSetting ps = (PackageSetting) obj; 5578 return ps.pkgPrivateFlags; 5579 } 5580 } 5581 return 0; 5582 } 5583 5584 @Override 5585 public boolean isUidPrivileged(int uid) { 5586 uid = UserHandle.getAppId(uid); 5587 // reader 5588 synchronized (mPackages) { 5589 Object obj = mSettings.getUserIdLPr(uid); 5590 if (obj instanceof SharedUserSetting) { 5591 final SharedUserSetting sus = (SharedUserSetting) obj; 5592 final Iterator<PackageSetting> it = sus.packages.iterator(); 5593 while (it.hasNext()) { 5594 if (it.next().isPrivileged()) { 5595 return true; 5596 } 5597 } 5598 } else if (obj instanceof PackageSetting) { 5599 final PackageSetting ps = (PackageSetting) obj; 5600 return ps.isPrivileged(); 5601 } 5602 } 5603 return false; 5604 } 5605 5606 @Override 5607 public String[] getAppOpPermissionPackages(String permissionName) { 5608 synchronized (mPackages) { 5609 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5610 if (pkgs == null) { 5611 return null; 5612 } 5613 return pkgs.toArray(new String[pkgs.size()]); 5614 } 5615 } 5616 5617 @Override 5618 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5619 int flags, int userId) { 5620 return resolveIntentInternal( 5621 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5622 } 5623 5624 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5625 int flags, int userId, boolean includeInstantApps) { 5626 try { 5627 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5628 5629 if (!sUserManager.exists(userId)) return null; 5630 final int callingUid = Binder.getCallingUid(); 5631 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 5632 enforceCrossUserPermission(callingUid, userId, 5633 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5634 5635 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5636 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5637 flags, userId, includeInstantApps); 5638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5639 5640 final ResolveInfo bestChoice = 5641 chooseBestActivity(intent, resolvedType, flags, query, userId); 5642 return bestChoice; 5643 } finally { 5644 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5645 } 5646 } 5647 5648 @Override 5649 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5650 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5651 throw new SecurityException( 5652 "findPersistentPreferredActivity can only be run by the system"); 5653 } 5654 if (!sUserManager.exists(userId)) { 5655 return null; 5656 } 5657 final int callingUid = Binder.getCallingUid(); 5658 intent = updateIntentForResolve(intent); 5659 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5660 final int flags = updateFlagsForResolve( 5661 0, userId, intent, callingUid, false /*includeInstantApps*/); 5662 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5663 userId); 5664 synchronized (mPackages) { 5665 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5666 userId); 5667 } 5668 } 5669 5670 @Override 5671 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5672 IntentFilter filter, int match, ComponentName activity) { 5673 final int userId = UserHandle.getCallingUserId(); 5674 if (DEBUG_PREFERRED) { 5675 Log.v(TAG, "setLastChosenActivity intent=" + intent 5676 + " resolvedType=" + resolvedType 5677 + " flags=" + flags 5678 + " filter=" + filter 5679 + " match=" + match 5680 + " activity=" + activity); 5681 filter.dump(new PrintStreamPrinter(System.out), " "); 5682 } 5683 intent.setComponent(null); 5684 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5685 userId); 5686 // Find any earlier preferred or last chosen entries and nuke them 5687 findPreferredActivity(intent, resolvedType, 5688 flags, query, 0, false, true, false, userId); 5689 // Add the new activity as the last chosen for this filter 5690 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5691 "Setting last chosen"); 5692 } 5693 5694 @Override 5695 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5696 final int userId = UserHandle.getCallingUserId(); 5697 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5698 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5699 userId); 5700 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5701 false, false, false, userId); 5702 } 5703 5704 /** 5705 * Returns whether or not instant apps have been disabled remotely. 5706 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5707 * held. Otherwise we run the risk of deadlock. 5708 */ 5709 private boolean isEphemeralDisabled() { 5710 // ephemeral apps have been disabled across the board 5711 if (DISABLE_EPHEMERAL_APPS) { 5712 return true; 5713 } 5714 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5715 if (!mSystemReady) { 5716 return true; 5717 } 5718 // we can't get a content resolver until the system is ready; these checks must happen last 5719 final ContentResolver resolver = mContext.getContentResolver(); 5720 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5721 return true; 5722 } 5723 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5724 } 5725 5726 private boolean isEphemeralAllowed( 5727 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5728 boolean skipPackageCheck) { 5729 final int callingUser = UserHandle.getCallingUserId(); 5730 if (mInstantAppResolverConnection == null) { 5731 return false; 5732 } 5733 if (mInstantAppInstallerActivity == null) { 5734 return false; 5735 } 5736 if (intent.getComponent() != null) { 5737 return false; 5738 } 5739 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5740 return false; 5741 } 5742 if (!skipPackageCheck && intent.getPackage() != null) { 5743 return false; 5744 } 5745 final boolean isWebUri = hasWebURI(intent); 5746 if (!isWebUri || intent.getData().getHost() == null) { 5747 return false; 5748 } 5749 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5750 // Or if there's already an ephemeral app installed that handles the action 5751 synchronized (mPackages) { 5752 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5753 for (int n = 0; n < count; n++) { 5754 final ResolveInfo info = resolvedActivities.get(n); 5755 final String packageName = info.activityInfo.packageName; 5756 final PackageSetting ps = mSettings.mPackages.get(packageName); 5757 if (ps != null) { 5758 // only check domain verification status if the app is not a browser 5759 if (!info.handleAllWebDataURI) { 5760 // Try to get the status from User settings first 5761 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5762 final int status = (int) (packedStatus >> 32); 5763 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5764 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5765 if (DEBUG_EPHEMERAL) { 5766 Slog.v(TAG, "DENY instant app;" 5767 + " pkg: " + packageName + ", status: " + status); 5768 } 5769 return false; 5770 } 5771 } 5772 if (ps.getInstantApp(userId)) { 5773 if (DEBUG_EPHEMERAL) { 5774 Slog.v(TAG, "DENY instant app installed;" 5775 + " pkg: " + packageName); 5776 } 5777 return false; 5778 } 5779 } 5780 } 5781 } 5782 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5783 return true; 5784 } 5785 5786 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5787 Intent origIntent, String resolvedType, String callingPackage, 5788 int userId) { 5789 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5790 new InstantAppRequest(responseObj, origIntent, resolvedType, 5791 callingPackage, userId)); 5792 mHandler.sendMessage(msg); 5793 } 5794 5795 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5796 int flags, List<ResolveInfo> query, int userId) { 5797 if (query != null) { 5798 final int N = query.size(); 5799 if (N == 1) { 5800 return query.get(0); 5801 } else if (N > 1) { 5802 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5803 // If there is more than one activity with the same priority, 5804 // then let the user decide between them. 5805 ResolveInfo r0 = query.get(0); 5806 ResolveInfo r1 = query.get(1); 5807 if (DEBUG_INTENT_MATCHING || debug) { 5808 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5809 + r1.activityInfo.name + "=" + r1.priority); 5810 } 5811 // If the first activity has a higher priority, or a different 5812 // default, then it is always desirable to pick it. 5813 if (r0.priority != r1.priority 5814 || r0.preferredOrder != r1.preferredOrder 5815 || r0.isDefault != r1.isDefault) { 5816 return query.get(0); 5817 } 5818 // If we have saved a preference for a preferred activity for 5819 // this Intent, use that. 5820 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5821 flags, query, r0.priority, true, false, debug, userId); 5822 if (ri != null) { 5823 return ri; 5824 } 5825 // If we have an ephemeral app, use it 5826 for (int i = 0; i < N; i++) { 5827 ri = query.get(i); 5828 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5829 return ri; 5830 } 5831 } 5832 ri = new ResolveInfo(mResolveInfo); 5833 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5834 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5835 // If all of the options come from the same package, show the application's 5836 // label and icon instead of the generic resolver's. 5837 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5838 // and then throw away the ResolveInfo itself, meaning that the caller loses 5839 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5840 // a fallback for this case; we only set the target package's resources on 5841 // the ResolveInfo, not the ActivityInfo. 5842 final String intentPackage = intent.getPackage(); 5843 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5844 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5845 ri.resolvePackageName = intentPackage; 5846 if (userNeedsBadging(userId)) { 5847 ri.noResourceId = true; 5848 } else { 5849 ri.icon = appi.icon; 5850 } 5851 ri.iconResourceId = appi.icon; 5852 ri.labelRes = appi.labelRes; 5853 } 5854 ri.activityInfo.applicationInfo = new ApplicationInfo( 5855 ri.activityInfo.applicationInfo); 5856 if (userId != 0) { 5857 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5858 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5859 } 5860 // Make sure that the resolver is displayable in car mode 5861 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5862 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5863 return ri; 5864 } 5865 } 5866 return null; 5867 } 5868 5869 /** 5870 * Return true if the given list is not empty and all of its contents have 5871 * an activityInfo with the given package name. 5872 */ 5873 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5874 if (ArrayUtils.isEmpty(list)) { 5875 return false; 5876 } 5877 for (int i = 0, N = list.size(); i < N; i++) { 5878 final ResolveInfo ri = list.get(i); 5879 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5880 if (ai == null || !packageName.equals(ai.packageName)) { 5881 return false; 5882 } 5883 } 5884 return true; 5885 } 5886 5887 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5888 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5889 final int N = query.size(); 5890 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5891 .get(userId); 5892 // Get the list of persistent preferred activities that handle the intent 5893 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5894 List<PersistentPreferredActivity> pprefs = ppir != null 5895 ? ppir.queryIntent(intent, resolvedType, 5896 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5897 userId) 5898 : null; 5899 if (pprefs != null && pprefs.size() > 0) { 5900 final int M = pprefs.size(); 5901 for (int i=0; i<M; i++) { 5902 final PersistentPreferredActivity ppa = pprefs.get(i); 5903 if (DEBUG_PREFERRED || debug) { 5904 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5905 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5906 + "\n component=" + ppa.mComponent); 5907 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5908 } 5909 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5910 flags | MATCH_DISABLED_COMPONENTS, userId); 5911 if (DEBUG_PREFERRED || debug) { 5912 Slog.v(TAG, "Found persistent preferred activity:"); 5913 if (ai != null) { 5914 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5915 } else { 5916 Slog.v(TAG, " null"); 5917 } 5918 } 5919 if (ai == null) { 5920 // This previously registered persistent preferred activity 5921 // component is no longer known. Ignore it and do NOT remove it. 5922 continue; 5923 } 5924 for (int j=0; j<N; j++) { 5925 final ResolveInfo ri = query.get(j); 5926 if (!ri.activityInfo.applicationInfo.packageName 5927 .equals(ai.applicationInfo.packageName)) { 5928 continue; 5929 } 5930 if (!ri.activityInfo.name.equals(ai.name)) { 5931 continue; 5932 } 5933 // Found a persistent preference that can handle the intent. 5934 if (DEBUG_PREFERRED || debug) { 5935 Slog.v(TAG, "Returning persistent preferred activity: " + 5936 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5937 } 5938 return ri; 5939 } 5940 } 5941 } 5942 return null; 5943 } 5944 5945 // TODO: handle preferred activities missing while user has amnesia 5946 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5947 List<ResolveInfo> query, int priority, boolean always, 5948 boolean removeMatches, boolean debug, int userId) { 5949 if (!sUserManager.exists(userId)) return null; 5950 final int callingUid = Binder.getCallingUid(); 5951 flags = updateFlagsForResolve( 5952 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5953 intent = updateIntentForResolve(intent); 5954 // writer 5955 synchronized (mPackages) { 5956 // Try to find a matching persistent preferred activity. 5957 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5958 debug, userId); 5959 5960 // If a persistent preferred activity matched, use it. 5961 if (pri != null) { 5962 return pri; 5963 } 5964 5965 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5966 // Get the list of preferred activities that handle the intent 5967 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5968 List<PreferredActivity> prefs = pir != null 5969 ? pir.queryIntent(intent, resolvedType, 5970 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5971 userId) 5972 : null; 5973 if (prefs != null && prefs.size() > 0) { 5974 boolean changed = false; 5975 try { 5976 // First figure out how good the original match set is. 5977 // We will only allow preferred activities that came 5978 // from the same match quality. 5979 int match = 0; 5980 5981 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5982 5983 final int N = query.size(); 5984 for (int j=0; j<N; j++) { 5985 final ResolveInfo ri = query.get(j); 5986 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5987 + ": 0x" + Integer.toHexString(match)); 5988 if (ri.match > match) { 5989 match = ri.match; 5990 } 5991 } 5992 5993 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5994 + Integer.toHexString(match)); 5995 5996 match &= IntentFilter.MATCH_CATEGORY_MASK; 5997 final int M = prefs.size(); 5998 for (int i=0; i<M; i++) { 5999 final PreferredActivity pa = prefs.get(i); 6000 if (DEBUG_PREFERRED || debug) { 6001 Slog.v(TAG, "Checking PreferredActivity ds=" 6002 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6003 + "\n component=" + pa.mPref.mComponent); 6004 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6005 } 6006 if (pa.mPref.mMatch != match) { 6007 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6008 + Integer.toHexString(pa.mPref.mMatch)); 6009 continue; 6010 } 6011 // If it's not an "always" type preferred activity and that's what we're 6012 // looking for, skip it. 6013 if (always && !pa.mPref.mAlways) { 6014 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6015 continue; 6016 } 6017 final ActivityInfo ai = getActivityInfo( 6018 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6019 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6020 userId); 6021 if (DEBUG_PREFERRED || debug) { 6022 Slog.v(TAG, "Found preferred activity:"); 6023 if (ai != null) { 6024 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6025 } else { 6026 Slog.v(TAG, " null"); 6027 } 6028 } 6029 if (ai == null) { 6030 // This previously registered preferred activity 6031 // component is no longer known. Most likely an update 6032 // to the app was installed and in the new version this 6033 // component no longer exists. Clean it up by removing 6034 // it from the preferred activities list, and skip it. 6035 Slog.w(TAG, "Removing dangling preferred activity: " 6036 + pa.mPref.mComponent); 6037 pir.removeFilter(pa); 6038 changed = true; 6039 continue; 6040 } 6041 for (int j=0; j<N; j++) { 6042 final ResolveInfo ri = query.get(j); 6043 if (!ri.activityInfo.applicationInfo.packageName 6044 .equals(ai.applicationInfo.packageName)) { 6045 continue; 6046 } 6047 if (!ri.activityInfo.name.equals(ai.name)) { 6048 continue; 6049 } 6050 6051 if (removeMatches) { 6052 pir.removeFilter(pa); 6053 changed = true; 6054 if (DEBUG_PREFERRED) { 6055 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6056 } 6057 break; 6058 } 6059 6060 // Okay we found a previously set preferred or last chosen app. 6061 // If the result set is different from when this 6062 // was created, we need to clear it and re-ask the 6063 // user their preference, if we're looking for an "always" type entry. 6064 if (always && !pa.mPref.sameSet(query)) { 6065 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6066 + intent + " type " + resolvedType); 6067 if (DEBUG_PREFERRED) { 6068 Slog.v(TAG, "Removing preferred activity since set changed " 6069 + pa.mPref.mComponent); 6070 } 6071 pir.removeFilter(pa); 6072 // Re-add the filter as a "last chosen" entry (!always) 6073 PreferredActivity lastChosen = new PreferredActivity( 6074 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6075 pir.addFilter(lastChosen); 6076 changed = true; 6077 return null; 6078 } 6079 6080 // Yay! Either the set matched or we're looking for the last chosen 6081 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6082 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6083 return ri; 6084 } 6085 } 6086 } finally { 6087 if (changed) { 6088 if (DEBUG_PREFERRED) { 6089 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6090 } 6091 scheduleWritePackageRestrictionsLocked(userId); 6092 } 6093 } 6094 } 6095 } 6096 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6097 return null; 6098 } 6099 6100 /* 6101 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6102 */ 6103 @Override 6104 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6105 int targetUserId) { 6106 mContext.enforceCallingOrSelfPermission( 6107 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6108 List<CrossProfileIntentFilter> matches = 6109 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6110 if (matches != null) { 6111 int size = matches.size(); 6112 for (int i = 0; i < size; i++) { 6113 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6114 } 6115 } 6116 if (hasWebURI(intent)) { 6117 // cross-profile app linking works only towards the parent. 6118 final int callingUid = Binder.getCallingUid(); 6119 final UserInfo parent = getProfileParent(sourceUserId); 6120 synchronized(mPackages) { 6121 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6122 false /*includeInstantApps*/); 6123 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6124 intent, resolvedType, flags, sourceUserId, parent.id); 6125 return xpDomainInfo != null; 6126 } 6127 } 6128 return false; 6129 } 6130 6131 private UserInfo getProfileParent(int userId) { 6132 final long identity = Binder.clearCallingIdentity(); 6133 try { 6134 return sUserManager.getProfileParent(userId); 6135 } finally { 6136 Binder.restoreCallingIdentity(identity); 6137 } 6138 } 6139 6140 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6141 String resolvedType, int userId) { 6142 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6143 if (resolver != null) { 6144 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6145 } 6146 return null; 6147 } 6148 6149 @Override 6150 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6151 String resolvedType, int flags, int userId) { 6152 try { 6153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6154 6155 return new ParceledListSlice<>( 6156 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6157 } finally { 6158 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6159 } 6160 } 6161 6162 /** 6163 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6164 * instant, returns {@code null}. 6165 */ 6166 private String getInstantAppPackageName(int callingUid) { 6167 // If the caller is an isolated app use the owner's uid for the lookup. 6168 if (Process.isIsolated(callingUid)) { 6169 callingUid = mIsolatedOwners.get(callingUid); 6170 } 6171 final int appId = UserHandle.getAppId(callingUid); 6172 synchronized (mPackages) { 6173 final Object obj = mSettings.getUserIdLPr(appId); 6174 if (obj instanceof PackageSetting) { 6175 final PackageSetting ps = (PackageSetting) obj; 6176 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6177 return isInstantApp ? ps.pkg.packageName : null; 6178 } 6179 } 6180 return null; 6181 } 6182 6183 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6184 String resolvedType, int flags, int userId) { 6185 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6186 } 6187 6188 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6189 String resolvedType, int flags, int userId, boolean includeInstantApps) { 6190 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6191 final int callingUid = Binder.getCallingUid(); 6192 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6193 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 6194 enforceCrossUserPermission(callingUid, userId, 6195 false /* requireFullPermission */, false /* checkShell */, 6196 "query intent activities"); 6197 ComponentName comp = intent.getComponent(); 6198 if (comp == null) { 6199 if (intent.getSelector() != null) { 6200 intent = intent.getSelector(); 6201 comp = intent.getComponent(); 6202 } 6203 } 6204 6205 if (comp != null) { 6206 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6207 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6208 if (ai != null) { 6209 // When specifying an explicit component, we prevent the activity from being 6210 // used when either 1) the calling package is normal and the activity is within 6211 // an ephemeral application or 2) the calling package is ephemeral and the 6212 // activity is not visible to ephemeral applications. 6213 final boolean matchInstantApp = 6214 (flags & PackageManager.MATCH_INSTANT) != 0; 6215 final boolean matchVisibleToInstantAppOnly = 6216 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6217 final boolean isCallerInstantApp = 6218 instantAppPkgName != null; 6219 final boolean isTargetSameInstantApp = 6220 comp.getPackageName().equals(instantAppPkgName); 6221 final boolean isTargetInstantApp = 6222 (ai.applicationInfo.privateFlags 6223 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6224 final boolean isTargetHiddenFromInstantApp = 6225 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6226 final boolean blockResolution = 6227 !isTargetSameInstantApp 6228 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6229 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6230 && isTargetHiddenFromInstantApp)); 6231 if (!blockResolution) { 6232 final ResolveInfo ri = new ResolveInfo(); 6233 ri.activityInfo = ai; 6234 list.add(ri); 6235 } 6236 } 6237 return applyPostResolutionFilter(list, instantAppPkgName); 6238 } 6239 6240 // reader 6241 boolean sortResult = false; 6242 boolean addEphemeral = false; 6243 List<ResolveInfo> result; 6244 final String pkgName = intent.getPackage(); 6245 final boolean ephemeralDisabled = isEphemeralDisabled(); 6246 synchronized (mPackages) { 6247 if (pkgName == null) { 6248 List<CrossProfileIntentFilter> matchingFilters = 6249 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6250 // Check for results that need to skip the current profile. 6251 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6252 resolvedType, flags, userId); 6253 if (xpResolveInfo != null) { 6254 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6255 xpResult.add(xpResolveInfo); 6256 return applyPostResolutionFilter( 6257 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6258 } 6259 6260 // Check for results in the current profile. 6261 result = filterIfNotSystemUser(mActivities.queryIntent( 6262 intent, resolvedType, flags, userId), userId); 6263 addEphemeral = !ephemeralDisabled 6264 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6265 // Check for cross profile results. 6266 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6267 xpResolveInfo = queryCrossProfileIntents( 6268 matchingFilters, intent, resolvedType, flags, userId, 6269 hasNonNegativePriorityResult); 6270 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6271 boolean isVisibleToUser = filterIfNotSystemUser( 6272 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6273 if (isVisibleToUser) { 6274 result.add(xpResolveInfo); 6275 sortResult = true; 6276 } 6277 } 6278 if (hasWebURI(intent)) { 6279 CrossProfileDomainInfo xpDomainInfo = null; 6280 final UserInfo parent = getProfileParent(userId); 6281 if (parent != null) { 6282 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6283 flags, userId, parent.id); 6284 } 6285 if (xpDomainInfo != null) { 6286 if (xpResolveInfo != null) { 6287 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6288 // in the result. 6289 result.remove(xpResolveInfo); 6290 } 6291 if (result.size() == 0 && !addEphemeral) { 6292 // No result in current profile, but found candidate in parent user. 6293 // And we are not going to add emphemeral app, so we can return the 6294 // result straight away. 6295 result.add(xpDomainInfo.resolveInfo); 6296 return applyPostResolutionFilter(result, instantAppPkgName); 6297 } 6298 } else if (result.size() <= 1 && !addEphemeral) { 6299 // No result in parent user and <= 1 result in current profile, and we 6300 // are not going to add emphemeral app, so we can return the result without 6301 // further processing. 6302 return applyPostResolutionFilter(result, instantAppPkgName); 6303 } 6304 // We have more than one candidate (combining results from current and parent 6305 // profile), so we need filtering and sorting. 6306 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6307 intent, flags, result, xpDomainInfo, userId); 6308 sortResult = true; 6309 } 6310 } else { 6311 final PackageParser.Package pkg = mPackages.get(pkgName); 6312 if (pkg != null) { 6313 return applyPostResolutionFilter(filterIfNotSystemUser( 6314 mActivities.queryIntentForPackage( 6315 intent, resolvedType, flags, pkg.activities, userId), 6316 userId), instantAppPkgName); 6317 } else { 6318 // the caller wants to resolve for a particular package; however, there 6319 // were no installed results, so, try to find an ephemeral result 6320 addEphemeral = !ephemeralDisabled 6321 && isEphemeralAllowed( 6322 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6323 result = new ArrayList<ResolveInfo>(); 6324 } 6325 } 6326 } 6327 if (addEphemeral) { 6328 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6329 final InstantAppRequest requestObject = new InstantAppRequest( 6330 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6331 null /*callingPackage*/, userId); 6332 final AuxiliaryResolveInfo auxiliaryResponse = 6333 InstantAppResolver.doInstantAppResolutionPhaseOne( 6334 mContext, mInstantAppResolverConnection, requestObject); 6335 if (auxiliaryResponse != null) { 6336 if (DEBUG_EPHEMERAL) { 6337 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6338 } 6339 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6340 final PackageSetting ps = 6341 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6342 if (ps != null) { 6343 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6344 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6345 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6346 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6347 // make sure this resolver is the default 6348 ephemeralInstaller.isDefault = true; 6349 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6350 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6351 // add a non-generic filter 6352 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6353 ephemeralInstaller.filter.addDataPath( 6354 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6355 ephemeralInstaller.instantAppAvailable = true; 6356 result.add(ephemeralInstaller); 6357 } 6358 } 6359 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6360 } 6361 if (sortResult) { 6362 Collections.sort(result, mResolvePrioritySorter); 6363 } 6364 return applyPostResolutionFilter(result, instantAppPkgName); 6365 } 6366 6367 private static class CrossProfileDomainInfo { 6368 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6369 ResolveInfo resolveInfo; 6370 /* Best domain verification status of the activities found in the other profile */ 6371 int bestDomainVerificationStatus; 6372 } 6373 6374 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6375 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6376 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6377 sourceUserId)) { 6378 return null; 6379 } 6380 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6381 resolvedType, flags, parentUserId); 6382 6383 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6384 return null; 6385 } 6386 CrossProfileDomainInfo result = null; 6387 int size = resultTargetUser.size(); 6388 for (int i = 0; i < size; i++) { 6389 ResolveInfo riTargetUser = resultTargetUser.get(i); 6390 // Intent filter verification is only for filters that specify a host. So don't return 6391 // those that handle all web uris. 6392 if (riTargetUser.handleAllWebDataURI) { 6393 continue; 6394 } 6395 String packageName = riTargetUser.activityInfo.packageName; 6396 PackageSetting ps = mSettings.mPackages.get(packageName); 6397 if (ps == null) { 6398 continue; 6399 } 6400 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6401 int status = (int)(verificationState >> 32); 6402 if (result == null) { 6403 result = new CrossProfileDomainInfo(); 6404 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6405 sourceUserId, parentUserId); 6406 result.bestDomainVerificationStatus = status; 6407 } else { 6408 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6409 result.bestDomainVerificationStatus); 6410 } 6411 } 6412 // Don't consider matches with status NEVER across profiles. 6413 if (result != null && result.bestDomainVerificationStatus 6414 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6415 return null; 6416 } 6417 return result; 6418 } 6419 6420 /** 6421 * Verification statuses are ordered from the worse to the best, except for 6422 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6423 */ 6424 private int bestDomainVerificationStatus(int status1, int status2) { 6425 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6426 return status2; 6427 } 6428 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6429 return status1; 6430 } 6431 return (int) MathUtils.max(status1, status2); 6432 } 6433 6434 private boolean isUserEnabled(int userId) { 6435 long callingId = Binder.clearCallingIdentity(); 6436 try { 6437 UserInfo userInfo = sUserManager.getUserInfo(userId); 6438 return userInfo != null && userInfo.isEnabled(); 6439 } finally { 6440 Binder.restoreCallingIdentity(callingId); 6441 } 6442 } 6443 6444 /** 6445 * Filter out activities with systemUserOnly flag set, when current user is not System. 6446 * 6447 * @return filtered list 6448 */ 6449 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6450 if (userId == UserHandle.USER_SYSTEM) { 6451 return resolveInfos; 6452 } 6453 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6454 ResolveInfo info = resolveInfos.get(i); 6455 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6456 resolveInfos.remove(i); 6457 } 6458 } 6459 return resolveInfos; 6460 } 6461 6462 /** 6463 * Filters out ephemeral activities. 6464 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6465 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6466 * 6467 * @param resolveInfos The pre-filtered list of resolved activities 6468 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6469 * is performed. 6470 * @return A filtered list of resolved activities. 6471 */ 6472 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6473 String ephemeralPkgName) { 6474 // TODO: When adding on-demand split support for non-instant apps, remove this check 6475 // and always apply post filtering 6476 if (ephemeralPkgName == null) { 6477 return resolveInfos; 6478 } 6479 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6480 final ResolveInfo info = resolveInfos.get(i); 6481 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6482 // allow activities that are defined in the provided package 6483 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6484 if (info.activityInfo.splitName != null 6485 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6486 info.activityInfo.splitName)) { 6487 // requested activity is defined in a split that hasn't been installed yet. 6488 // add the installer to the resolve list 6489 if (DEBUG_EPHEMERAL) { 6490 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6491 } 6492 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6493 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6494 info.activityInfo.packageName, info.activityInfo.splitName, 6495 info.activityInfo.applicationInfo.versionCode); 6496 // make sure this resolver is the default 6497 installerInfo.isDefault = true; 6498 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6499 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6500 // add a non-generic filter 6501 installerInfo.filter = new IntentFilter(); 6502 // load resources from the correct package 6503 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6504 resolveInfos.set(i, installerInfo); 6505 } 6506 continue; 6507 } 6508 // allow activities that have been explicitly exposed to ephemeral apps 6509 if (!isEphemeralApp 6510 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6511 continue; 6512 } 6513 resolveInfos.remove(i); 6514 } 6515 return resolveInfos; 6516 } 6517 6518 /** 6519 * @param resolveInfos list of resolve infos in descending priority order 6520 * @return if the list contains a resolve info with non-negative priority 6521 */ 6522 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6523 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6524 } 6525 6526 private static boolean hasWebURI(Intent intent) { 6527 if (intent.getData() == null) { 6528 return false; 6529 } 6530 final String scheme = intent.getScheme(); 6531 if (TextUtils.isEmpty(scheme)) { 6532 return false; 6533 } 6534 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6535 } 6536 6537 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6538 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6539 int userId) { 6540 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6541 6542 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6543 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6544 candidates.size()); 6545 } 6546 6547 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6548 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6549 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6550 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6551 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6552 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6553 6554 synchronized (mPackages) { 6555 final int count = candidates.size(); 6556 // First, try to use linked apps. Partition the candidates into four lists: 6557 // one for the final results, one for the "do not use ever", one for "undefined status" 6558 // and finally one for "browser app type". 6559 for (int n=0; n<count; n++) { 6560 ResolveInfo info = candidates.get(n); 6561 String packageName = info.activityInfo.packageName; 6562 PackageSetting ps = mSettings.mPackages.get(packageName); 6563 if (ps != null) { 6564 // Add to the special match all list (Browser use case) 6565 if (info.handleAllWebDataURI) { 6566 matchAllList.add(info); 6567 continue; 6568 } 6569 // Try to get the status from User settings first 6570 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6571 int status = (int)(packedStatus >> 32); 6572 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6573 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6574 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6575 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6576 + " : linkgen=" + linkGeneration); 6577 } 6578 // Use link-enabled generation as preferredOrder, i.e. 6579 // prefer newly-enabled over earlier-enabled. 6580 info.preferredOrder = linkGeneration; 6581 alwaysList.add(info); 6582 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6583 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6584 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6585 } 6586 neverList.add(info); 6587 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6588 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6589 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6590 } 6591 alwaysAskList.add(info); 6592 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6593 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6594 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6595 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6596 } 6597 undefinedList.add(info); 6598 } 6599 } 6600 } 6601 6602 // We'll want to include browser possibilities in a few cases 6603 boolean includeBrowser = false; 6604 6605 // First try to add the "always" resolution(s) for the current user, if any 6606 if (alwaysList.size() > 0) { 6607 result.addAll(alwaysList); 6608 } else { 6609 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6610 result.addAll(undefinedList); 6611 // Maybe add one for the other profile. 6612 if (xpDomainInfo != null && ( 6613 xpDomainInfo.bestDomainVerificationStatus 6614 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6615 result.add(xpDomainInfo.resolveInfo); 6616 } 6617 includeBrowser = true; 6618 } 6619 6620 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6621 // If there were 'always' entries their preferred order has been set, so we also 6622 // back that off to make the alternatives equivalent 6623 if (alwaysAskList.size() > 0) { 6624 for (ResolveInfo i : result) { 6625 i.preferredOrder = 0; 6626 } 6627 result.addAll(alwaysAskList); 6628 includeBrowser = true; 6629 } 6630 6631 if (includeBrowser) { 6632 // Also add browsers (all of them or only the default one) 6633 if (DEBUG_DOMAIN_VERIFICATION) { 6634 Slog.v(TAG, " ...including browsers in candidate set"); 6635 } 6636 if ((matchFlags & MATCH_ALL) != 0) { 6637 result.addAll(matchAllList); 6638 } else { 6639 // Browser/generic handling case. If there's a default browser, go straight 6640 // to that (but only if there is no other higher-priority match). 6641 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6642 int maxMatchPrio = 0; 6643 ResolveInfo defaultBrowserMatch = null; 6644 final int numCandidates = matchAllList.size(); 6645 for (int n = 0; n < numCandidates; n++) { 6646 ResolveInfo info = matchAllList.get(n); 6647 // track the highest overall match priority... 6648 if (info.priority > maxMatchPrio) { 6649 maxMatchPrio = info.priority; 6650 } 6651 // ...and the highest-priority default browser match 6652 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6653 if (defaultBrowserMatch == null 6654 || (defaultBrowserMatch.priority < info.priority)) { 6655 if (debug) { 6656 Slog.v(TAG, "Considering default browser match " + info); 6657 } 6658 defaultBrowserMatch = info; 6659 } 6660 } 6661 } 6662 if (defaultBrowserMatch != null 6663 && defaultBrowserMatch.priority >= maxMatchPrio 6664 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6665 { 6666 if (debug) { 6667 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6668 } 6669 result.add(defaultBrowserMatch); 6670 } else { 6671 result.addAll(matchAllList); 6672 } 6673 } 6674 6675 // If there is nothing selected, add all candidates and remove the ones that the user 6676 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6677 if (result.size() == 0) { 6678 result.addAll(candidates); 6679 result.removeAll(neverList); 6680 } 6681 } 6682 } 6683 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6684 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6685 result.size()); 6686 for (ResolveInfo info : result) { 6687 Slog.v(TAG, " + " + info.activityInfo); 6688 } 6689 } 6690 return result; 6691 } 6692 6693 // Returns a packed value as a long: 6694 // 6695 // high 'int'-sized word: link status: undefined/ask/never/always. 6696 // low 'int'-sized word: relative priority among 'always' results. 6697 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6698 long result = ps.getDomainVerificationStatusForUser(userId); 6699 // if none available, get the master status 6700 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6701 if (ps.getIntentFilterVerificationInfo() != null) { 6702 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6703 } 6704 } 6705 return result; 6706 } 6707 6708 private ResolveInfo querySkipCurrentProfileIntents( 6709 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6710 int flags, int sourceUserId) { 6711 if (matchingFilters != null) { 6712 int size = matchingFilters.size(); 6713 for (int i = 0; i < size; i ++) { 6714 CrossProfileIntentFilter filter = matchingFilters.get(i); 6715 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6716 // Checking if there are activities in the target user that can handle the 6717 // intent. 6718 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6719 resolvedType, flags, sourceUserId); 6720 if (resolveInfo != null) { 6721 return resolveInfo; 6722 } 6723 } 6724 } 6725 } 6726 return null; 6727 } 6728 6729 // Return matching ResolveInfo in target user if any. 6730 private ResolveInfo queryCrossProfileIntents( 6731 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6732 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6733 if (matchingFilters != null) { 6734 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6735 // match the same intent. For performance reasons, it is better not to 6736 // run queryIntent twice for the same userId 6737 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6738 int size = matchingFilters.size(); 6739 for (int i = 0; i < size; i++) { 6740 CrossProfileIntentFilter filter = matchingFilters.get(i); 6741 int targetUserId = filter.getTargetUserId(); 6742 boolean skipCurrentProfile = 6743 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6744 boolean skipCurrentProfileIfNoMatchFound = 6745 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6746 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6747 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6748 // Checking if there are activities in the target user that can handle the 6749 // intent. 6750 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6751 resolvedType, flags, sourceUserId); 6752 if (resolveInfo != null) return resolveInfo; 6753 alreadyTriedUserIds.put(targetUserId, true); 6754 } 6755 } 6756 } 6757 return null; 6758 } 6759 6760 /** 6761 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6762 * will forward the intent to the filter's target user. 6763 * Otherwise, returns null. 6764 */ 6765 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6766 String resolvedType, int flags, int sourceUserId) { 6767 int targetUserId = filter.getTargetUserId(); 6768 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6769 resolvedType, flags, targetUserId); 6770 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6771 // If all the matches in the target profile are suspended, return null. 6772 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6773 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6774 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6775 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6776 targetUserId); 6777 } 6778 } 6779 } 6780 return null; 6781 } 6782 6783 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6784 int sourceUserId, int targetUserId) { 6785 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6786 long ident = Binder.clearCallingIdentity(); 6787 boolean targetIsProfile; 6788 try { 6789 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6790 } finally { 6791 Binder.restoreCallingIdentity(ident); 6792 } 6793 String className; 6794 if (targetIsProfile) { 6795 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6796 } else { 6797 className = FORWARD_INTENT_TO_PARENT; 6798 } 6799 ComponentName forwardingActivityComponentName = new ComponentName( 6800 mAndroidApplication.packageName, className); 6801 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6802 sourceUserId); 6803 if (!targetIsProfile) { 6804 forwardingActivityInfo.showUserIcon = targetUserId; 6805 forwardingResolveInfo.noResourceId = true; 6806 } 6807 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6808 forwardingResolveInfo.priority = 0; 6809 forwardingResolveInfo.preferredOrder = 0; 6810 forwardingResolveInfo.match = 0; 6811 forwardingResolveInfo.isDefault = true; 6812 forwardingResolveInfo.filter = filter; 6813 forwardingResolveInfo.targetUserId = targetUserId; 6814 return forwardingResolveInfo; 6815 } 6816 6817 @Override 6818 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6819 Intent[] specifics, String[] specificTypes, Intent intent, 6820 String resolvedType, int flags, int userId) { 6821 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6822 specificTypes, intent, resolvedType, flags, userId)); 6823 } 6824 6825 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6826 Intent[] specifics, String[] specificTypes, Intent intent, 6827 String resolvedType, int flags, int userId) { 6828 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6829 final int callingUid = Binder.getCallingUid(); 6830 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6831 false /*includeInstantApps*/); 6832 enforceCrossUserPermission(callingUid, userId, 6833 false /*requireFullPermission*/, false /*checkShell*/, 6834 "query intent activity options"); 6835 final String resultsAction = intent.getAction(); 6836 6837 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6838 | PackageManager.GET_RESOLVED_FILTER, userId); 6839 6840 if (DEBUG_INTENT_MATCHING) { 6841 Log.v(TAG, "Query " + intent + ": " + results); 6842 } 6843 6844 int specificsPos = 0; 6845 int N; 6846 6847 // todo: note that the algorithm used here is O(N^2). This 6848 // isn't a problem in our current environment, but if we start running 6849 // into situations where we have more than 5 or 10 matches then this 6850 // should probably be changed to something smarter... 6851 6852 // First we go through and resolve each of the specific items 6853 // that were supplied, taking care of removing any corresponding 6854 // duplicate items in the generic resolve list. 6855 if (specifics != null) { 6856 for (int i=0; i<specifics.length; i++) { 6857 final Intent sintent = specifics[i]; 6858 if (sintent == null) { 6859 continue; 6860 } 6861 6862 if (DEBUG_INTENT_MATCHING) { 6863 Log.v(TAG, "Specific #" + i + ": " + sintent); 6864 } 6865 6866 String action = sintent.getAction(); 6867 if (resultsAction != null && resultsAction.equals(action)) { 6868 // If this action was explicitly requested, then don't 6869 // remove things that have it. 6870 action = null; 6871 } 6872 6873 ResolveInfo ri = null; 6874 ActivityInfo ai = null; 6875 6876 ComponentName comp = sintent.getComponent(); 6877 if (comp == null) { 6878 ri = resolveIntent( 6879 sintent, 6880 specificTypes != null ? specificTypes[i] : null, 6881 flags, userId); 6882 if (ri == null) { 6883 continue; 6884 } 6885 if (ri == mResolveInfo) { 6886 // ACK! Must do something better with this. 6887 } 6888 ai = ri.activityInfo; 6889 comp = new ComponentName(ai.applicationInfo.packageName, 6890 ai.name); 6891 } else { 6892 ai = getActivityInfo(comp, flags, userId); 6893 if (ai == null) { 6894 continue; 6895 } 6896 } 6897 6898 // Look for any generic query activities that are duplicates 6899 // of this specific one, and remove them from the results. 6900 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6901 N = results.size(); 6902 int j; 6903 for (j=specificsPos; j<N; j++) { 6904 ResolveInfo sri = results.get(j); 6905 if ((sri.activityInfo.name.equals(comp.getClassName()) 6906 && sri.activityInfo.applicationInfo.packageName.equals( 6907 comp.getPackageName())) 6908 || (action != null && sri.filter.matchAction(action))) { 6909 results.remove(j); 6910 if (DEBUG_INTENT_MATCHING) Log.v( 6911 TAG, "Removing duplicate item from " + j 6912 + " due to specific " + specificsPos); 6913 if (ri == null) { 6914 ri = sri; 6915 } 6916 j--; 6917 N--; 6918 } 6919 } 6920 6921 // Add this specific item to its proper place. 6922 if (ri == null) { 6923 ri = new ResolveInfo(); 6924 ri.activityInfo = ai; 6925 } 6926 results.add(specificsPos, ri); 6927 ri.specificIndex = i; 6928 specificsPos++; 6929 } 6930 } 6931 6932 // Now we go through the remaining generic results and remove any 6933 // duplicate actions that are found here. 6934 N = results.size(); 6935 for (int i=specificsPos; i<N-1; i++) { 6936 final ResolveInfo rii = results.get(i); 6937 if (rii.filter == null) { 6938 continue; 6939 } 6940 6941 // Iterate over all of the actions of this result's intent 6942 // filter... typically this should be just one. 6943 final Iterator<String> it = rii.filter.actionsIterator(); 6944 if (it == null) { 6945 continue; 6946 } 6947 while (it.hasNext()) { 6948 final String action = it.next(); 6949 if (resultsAction != null && resultsAction.equals(action)) { 6950 // If this action was explicitly requested, then don't 6951 // remove things that have it. 6952 continue; 6953 } 6954 for (int j=i+1; j<N; j++) { 6955 final ResolveInfo rij = results.get(j); 6956 if (rij.filter != null && rij.filter.hasAction(action)) { 6957 results.remove(j); 6958 if (DEBUG_INTENT_MATCHING) Log.v( 6959 TAG, "Removing duplicate item from " + j 6960 + " due to action " + action + " at " + i); 6961 j--; 6962 N--; 6963 } 6964 } 6965 } 6966 6967 // If the caller didn't request filter information, drop it now 6968 // so we don't have to marshall/unmarshall it. 6969 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6970 rii.filter = null; 6971 } 6972 } 6973 6974 // Filter out the caller activity if so requested. 6975 if (caller != null) { 6976 N = results.size(); 6977 for (int i=0; i<N; i++) { 6978 ActivityInfo ainfo = results.get(i).activityInfo; 6979 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6980 && caller.getClassName().equals(ainfo.name)) { 6981 results.remove(i); 6982 break; 6983 } 6984 } 6985 } 6986 6987 // If the caller didn't request filter information, 6988 // drop them now so we don't have to 6989 // marshall/unmarshall it. 6990 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6991 N = results.size(); 6992 for (int i=0; i<N; i++) { 6993 results.get(i).filter = null; 6994 } 6995 } 6996 6997 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6998 return results; 6999 } 7000 7001 @Override 7002 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7003 String resolvedType, int flags, int userId) { 7004 return new ParceledListSlice<>( 7005 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 7006 } 7007 7008 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7009 String resolvedType, int flags, int userId) { 7010 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7011 final int callingUid = Binder.getCallingUid(); 7012 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7013 false /*includeInstantApps*/); 7014 ComponentName comp = intent.getComponent(); 7015 if (comp == null) { 7016 if (intent.getSelector() != null) { 7017 intent = intent.getSelector(); 7018 comp = intent.getComponent(); 7019 } 7020 } 7021 if (comp != null) { 7022 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7023 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7024 if (ai != null) { 7025 ResolveInfo ri = new ResolveInfo(); 7026 ri.activityInfo = ai; 7027 list.add(ri); 7028 } 7029 return list; 7030 } 7031 7032 // reader 7033 synchronized (mPackages) { 7034 String pkgName = intent.getPackage(); 7035 if (pkgName == null) { 7036 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7037 } 7038 final PackageParser.Package pkg = mPackages.get(pkgName); 7039 if (pkg != null) { 7040 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7041 userId); 7042 } 7043 return Collections.emptyList(); 7044 } 7045 } 7046 7047 @Override 7048 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7049 final int callingUid = Binder.getCallingUid(); 7050 return resolveServiceInternal( 7051 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7052 } 7053 7054 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7055 int userId, int callingUid, boolean includeInstantApps) { 7056 if (!sUserManager.exists(userId)) return null; 7057 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7058 List<ResolveInfo> query = queryIntentServicesInternal( 7059 intent, resolvedType, flags, userId, callingUid, includeInstantApps); 7060 if (query != null) { 7061 if (query.size() >= 1) { 7062 // If there is more than one service with the same priority, 7063 // just arbitrarily pick the first one. 7064 return query.get(0); 7065 } 7066 } 7067 return null; 7068 } 7069 7070 @Override 7071 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7072 String resolvedType, int flags, int userId) { 7073 final int callingUid = Binder.getCallingUid(); 7074 return new ParceledListSlice<>(queryIntentServicesInternal( 7075 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7076 } 7077 7078 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7079 String resolvedType, int flags, int userId, int callingUid, 7080 boolean includeInstantApps) { 7081 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7082 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7083 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7084 ComponentName comp = intent.getComponent(); 7085 if (comp == null) { 7086 if (intent.getSelector() != null) { 7087 intent = intent.getSelector(); 7088 comp = intent.getComponent(); 7089 } 7090 } 7091 if (comp != null) { 7092 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7093 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7094 if (si != null) { 7095 // When specifying an explicit component, we prevent the service from being 7096 // used when either 1) the service is in an instant application and the 7097 // caller is not the same instant application or 2) the calling package is 7098 // ephemeral and the activity is not visible to ephemeral applications. 7099 final boolean matchVisibleToInstantAppOnly = 7100 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7101 final boolean isCallerInstantApp = 7102 instantAppPkgName != null; 7103 final boolean isTargetSameInstantApp = 7104 comp.getPackageName().equals(instantAppPkgName); 7105 final boolean isTargetHiddenFromInstantApp = 7106 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 7107 final boolean blockResolution = 7108 !isTargetSameInstantApp 7109 && ((matchVisibleToInstantAppOnly && isCallerInstantApp 7110 && isTargetHiddenFromInstantApp)); 7111 if (!blockResolution) { 7112 final ResolveInfo ri = new ResolveInfo(); 7113 ri.serviceInfo = si; 7114 list.add(ri); 7115 } 7116 } 7117 return list; 7118 } 7119 7120 // reader 7121 synchronized (mPackages) { 7122 String pkgName = intent.getPackage(); 7123 if (pkgName == null) { 7124 return applyPostServiceResolutionFilter( 7125 mServices.queryIntent(intent, resolvedType, flags, userId), 7126 instantAppPkgName); 7127 } 7128 final PackageParser.Package pkg = mPackages.get(pkgName); 7129 if (pkg != null) { 7130 return applyPostServiceResolutionFilter( 7131 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7132 userId), 7133 instantAppPkgName); 7134 } 7135 return Collections.emptyList(); 7136 } 7137 } 7138 7139 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7140 String instantAppPkgName) { 7141 // TODO: When adding on-demand split support for non-instant apps, remove this check 7142 // and always apply post filtering 7143 if (instantAppPkgName == null) { 7144 return resolveInfos; 7145 } 7146 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7147 final ResolveInfo info = resolveInfos.get(i); 7148 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7149 // allow services that are defined in the provided package 7150 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7151 if (info.serviceInfo.splitName != null 7152 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7153 info.serviceInfo.splitName)) { 7154 // requested service is defined in a split that hasn't been installed yet. 7155 // add the installer to the resolve list 7156 if (DEBUG_EPHEMERAL) { 7157 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7158 } 7159 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7160 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7161 info.serviceInfo.packageName, info.serviceInfo.splitName, 7162 info.serviceInfo.applicationInfo.versionCode); 7163 // make sure this resolver is the default 7164 installerInfo.isDefault = true; 7165 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7166 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7167 // add a non-generic filter 7168 installerInfo.filter = new IntentFilter(); 7169 // load resources from the correct package 7170 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7171 resolveInfos.set(i, installerInfo); 7172 } 7173 continue; 7174 } 7175 // allow services that have been explicitly exposed to ephemeral apps 7176 if (!isEphemeralApp 7177 && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 7178 continue; 7179 } 7180 resolveInfos.remove(i); 7181 } 7182 return resolveInfos; 7183 } 7184 7185 @Override 7186 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7187 String resolvedType, int flags, int userId) { 7188 return new ParceledListSlice<>( 7189 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7190 } 7191 7192 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7193 Intent intent, String resolvedType, int flags, int userId) { 7194 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7195 final int callingUid = Binder.getCallingUid(); 7196 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7197 false /*includeInstantApps*/); 7198 ComponentName comp = intent.getComponent(); 7199 if (comp == null) { 7200 if (intent.getSelector() != null) { 7201 intent = intent.getSelector(); 7202 comp = intent.getComponent(); 7203 } 7204 } 7205 if (comp != null) { 7206 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7207 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7208 if (pi != null) { 7209 final ResolveInfo ri = new ResolveInfo(); 7210 ri.providerInfo = pi; 7211 list.add(ri); 7212 } 7213 return list; 7214 } 7215 7216 // reader 7217 synchronized (mPackages) { 7218 String pkgName = intent.getPackage(); 7219 if (pkgName == null) { 7220 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7221 } 7222 final PackageParser.Package pkg = mPackages.get(pkgName); 7223 if (pkg != null) { 7224 return mProviders.queryIntentForPackage( 7225 intent, resolvedType, flags, pkg.providers, userId); 7226 } 7227 return Collections.emptyList(); 7228 } 7229 } 7230 7231 @Override 7232 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7233 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7234 flags = updateFlagsForPackage(flags, userId, null); 7235 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7237 true /* requireFullPermission */, false /* checkShell */, 7238 "get installed packages"); 7239 7240 // writer 7241 synchronized (mPackages) { 7242 ArrayList<PackageInfo> list; 7243 if (listUninstalled) { 7244 list = new ArrayList<>(mSettings.mPackages.size()); 7245 for (PackageSetting ps : mSettings.mPackages.values()) { 7246 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7247 continue; 7248 } 7249 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7250 if (pi != null) { 7251 list.add(pi); 7252 } 7253 } 7254 } else { 7255 list = new ArrayList<>(mPackages.size()); 7256 for (PackageParser.Package p : mPackages.values()) { 7257 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7258 Binder.getCallingUid(), userId)) { 7259 continue; 7260 } 7261 final PackageInfo pi = generatePackageInfo((PackageSetting) 7262 p.mExtras, flags, userId); 7263 if (pi != null) { 7264 list.add(pi); 7265 } 7266 } 7267 } 7268 7269 return new ParceledListSlice<>(list); 7270 } 7271 } 7272 7273 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7274 String[] permissions, boolean[] tmp, int flags, int userId) { 7275 int numMatch = 0; 7276 final PermissionsState permissionsState = ps.getPermissionsState(); 7277 for (int i=0; i<permissions.length; i++) { 7278 final String permission = permissions[i]; 7279 if (permissionsState.hasPermission(permission, userId)) { 7280 tmp[i] = true; 7281 numMatch++; 7282 } else { 7283 tmp[i] = false; 7284 } 7285 } 7286 if (numMatch == 0) { 7287 return; 7288 } 7289 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7290 7291 // The above might return null in cases of uninstalled apps or install-state 7292 // skew across users/profiles. 7293 if (pi != null) { 7294 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7295 if (numMatch == permissions.length) { 7296 pi.requestedPermissions = permissions; 7297 } else { 7298 pi.requestedPermissions = new String[numMatch]; 7299 numMatch = 0; 7300 for (int i=0; i<permissions.length; i++) { 7301 if (tmp[i]) { 7302 pi.requestedPermissions[numMatch] = permissions[i]; 7303 numMatch++; 7304 } 7305 } 7306 } 7307 } 7308 list.add(pi); 7309 } 7310 } 7311 7312 @Override 7313 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7314 String[] permissions, int flags, int userId) { 7315 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7316 flags = updateFlagsForPackage(flags, userId, permissions); 7317 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7318 true /* requireFullPermission */, false /* checkShell */, 7319 "get packages holding permissions"); 7320 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7321 7322 // writer 7323 synchronized (mPackages) { 7324 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7325 boolean[] tmpBools = new boolean[permissions.length]; 7326 if (listUninstalled) { 7327 for (PackageSetting ps : mSettings.mPackages.values()) { 7328 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7329 userId); 7330 } 7331 } else { 7332 for (PackageParser.Package pkg : mPackages.values()) { 7333 PackageSetting ps = (PackageSetting)pkg.mExtras; 7334 if (ps != null) { 7335 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7336 userId); 7337 } 7338 } 7339 } 7340 7341 return new ParceledListSlice<PackageInfo>(list); 7342 } 7343 } 7344 7345 @Override 7346 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7347 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7348 flags = updateFlagsForApplication(flags, userId, null); 7349 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7350 7351 // writer 7352 synchronized (mPackages) { 7353 ArrayList<ApplicationInfo> list; 7354 if (listUninstalled) { 7355 list = new ArrayList<>(mSettings.mPackages.size()); 7356 for (PackageSetting ps : mSettings.mPackages.values()) { 7357 ApplicationInfo ai; 7358 int effectiveFlags = flags; 7359 if (ps.isSystem()) { 7360 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7361 } 7362 if (ps.pkg != null) { 7363 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7364 continue; 7365 } 7366 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7367 ps.readUserState(userId), userId); 7368 if (ai != null) { 7369 rebaseEnabledOverlays(ai, userId); 7370 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7371 } 7372 } else { 7373 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7374 // and already converts to externally visible package name 7375 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7376 Binder.getCallingUid(), effectiveFlags, userId); 7377 } 7378 if (ai != null) { 7379 list.add(ai); 7380 } 7381 } 7382 } else { 7383 list = new ArrayList<>(mPackages.size()); 7384 for (PackageParser.Package p : mPackages.values()) { 7385 if (p.mExtras != null) { 7386 PackageSetting ps = (PackageSetting) p.mExtras; 7387 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7388 continue; 7389 } 7390 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7391 ps.readUserState(userId), userId); 7392 if (ai != null) { 7393 rebaseEnabledOverlays(ai, userId); 7394 ai.packageName = resolveExternalPackageNameLPr(p); 7395 list.add(ai); 7396 } 7397 } 7398 } 7399 } 7400 7401 return new ParceledListSlice<>(list); 7402 } 7403 } 7404 7405 @Override 7406 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7407 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7408 return null; 7409 } 7410 7411 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7412 "getEphemeralApplications"); 7413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7414 true /* requireFullPermission */, false /* checkShell */, 7415 "getEphemeralApplications"); 7416 synchronized (mPackages) { 7417 List<InstantAppInfo> instantApps = mInstantAppRegistry 7418 .getInstantAppsLPr(userId); 7419 if (instantApps != null) { 7420 return new ParceledListSlice<>(instantApps); 7421 } 7422 } 7423 return null; 7424 } 7425 7426 @Override 7427 public boolean isInstantApp(String packageName, int userId) { 7428 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7429 true /* requireFullPermission */, false /* checkShell */, 7430 "isInstantApp"); 7431 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7432 return false; 7433 } 7434 int uid = Binder.getCallingUid(); 7435 if (Process.isIsolated(uid)) { 7436 uid = mIsolatedOwners.get(uid); 7437 } 7438 7439 synchronized (mPackages) { 7440 final PackageSetting ps = mSettings.mPackages.get(packageName); 7441 PackageParser.Package pkg = mPackages.get(packageName); 7442 final boolean returnAllowed = 7443 ps != null 7444 && (isCallerSameApp(packageName, uid) 7445 || mContext.checkCallingOrSelfPermission( 7446 android.Manifest.permission.ACCESS_INSTANT_APPS) 7447 == PERMISSION_GRANTED 7448 || mInstantAppRegistry.isInstantAccessGranted( 7449 userId, UserHandle.getAppId(uid), ps.appId)); 7450 if (returnAllowed) { 7451 return ps.getInstantApp(userId); 7452 } 7453 } 7454 return false; 7455 } 7456 7457 @Override 7458 public byte[] getInstantAppCookie(String packageName, int userId) { 7459 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7460 return null; 7461 } 7462 7463 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7464 true /* requireFullPermission */, false /* checkShell */, 7465 "getInstantAppCookie"); 7466 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7467 return null; 7468 } 7469 synchronized (mPackages) { 7470 return mInstantAppRegistry.getInstantAppCookieLPw( 7471 packageName, userId); 7472 } 7473 } 7474 7475 @Override 7476 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7477 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7478 return true; 7479 } 7480 7481 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7482 true /* requireFullPermission */, true /* checkShell */, 7483 "setInstantAppCookie"); 7484 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7485 return false; 7486 } 7487 synchronized (mPackages) { 7488 return mInstantAppRegistry.setInstantAppCookieLPw( 7489 packageName, cookie, userId); 7490 } 7491 } 7492 7493 @Override 7494 public Bitmap getInstantAppIcon(String packageName, int userId) { 7495 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7496 return null; 7497 } 7498 7499 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7500 "getInstantAppIcon"); 7501 7502 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7503 true /* requireFullPermission */, false /* checkShell */, 7504 "getInstantAppIcon"); 7505 7506 synchronized (mPackages) { 7507 return mInstantAppRegistry.getInstantAppIconLPw( 7508 packageName, userId); 7509 } 7510 } 7511 7512 private boolean isCallerSameApp(String packageName, int uid) { 7513 PackageParser.Package pkg = mPackages.get(packageName); 7514 return pkg != null 7515 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7516 } 7517 7518 @Override 7519 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7520 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7521 } 7522 7523 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7524 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7525 7526 // reader 7527 synchronized (mPackages) { 7528 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7529 final int userId = UserHandle.getCallingUserId(); 7530 while (i.hasNext()) { 7531 final PackageParser.Package p = i.next(); 7532 if (p.applicationInfo == null) continue; 7533 7534 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7535 && !p.applicationInfo.isDirectBootAware(); 7536 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7537 && p.applicationInfo.isDirectBootAware(); 7538 7539 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7540 && (!mSafeMode || isSystemApp(p)) 7541 && (matchesUnaware || matchesAware)) { 7542 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7543 if (ps != null) { 7544 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7545 ps.readUserState(userId), userId); 7546 if (ai != null) { 7547 rebaseEnabledOverlays(ai, userId); 7548 finalList.add(ai); 7549 } 7550 } 7551 } 7552 } 7553 } 7554 7555 return finalList; 7556 } 7557 7558 @Override 7559 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7560 if (!sUserManager.exists(userId)) return null; 7561 flags = updateFlagsForComponent(flags, userId, name); 7562 // reader 7563 synchronized (mPackages) { 7564 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7565 PackageSetting ps = provider != null 7566 ? mSettings.mPackages.get(provider.owner.packageName) 7567 : null; 7568 return ps != null 7569 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7570 ? PackageParser.generateProviderInfo(provider, flags, 7571 ps.readUserState(userId), userId) 7572 : null; 7573 } 7574 } 7575 7576 /** 7577 * @deprecated 7578 */ 7579 @Deprecated 7580 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7581 // reader 7582 synchronized (mPackages) { 7583 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7584 .entrySet().iterator(); 7585 final int userId = UserHandle.getCallingUserId(); 7586 while (i.hasNext()) { 7587 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7588 PackageParser.Provider p = entry.getValue(); 7589 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7590 7591 if (ps != null && p.syncable 7592 && (!mSafeMode || (p.info.applicationInfo.flags 7593 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7594 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7595 ps.readUserState(userId), userId); 7596 if (info != null) { 7597 outNames.add(entry.getKey()); 7598 outInfo.add(info); 7599 } 7600 } 7601 } 7602 } 7603 } 7604 7605 @Override 7606 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7607 int uid, int flags, String metaDataKey) { 7608 final int userId = processName != null ? UserHandle.getUserId(uid) 7609 : UserHandle.getCallingUserId(); 7610 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7611 flags = updateFlagsForComponent(flags, userId, processName); 7612 7613 ArrayList<ProviderInfo> finalList = null; 7614 // reader 7615 synchronized (mPackages) { 7616 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7617 while (i.hasNext()) { 7618 final PackageParser.Provider p = i.next(); 7619 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7620 if (ps != null && p.info.authority != null 7621 && (processName == null 7622 || (p.info.processName.equals(processName) 7623 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7624 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7625 7626 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7627 // parameter. 7628 if (metaDataKey != null 7629 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7630 continue; 7631 } 7632 7633 if (finalList == null) { 7634 finalList = new ArrayList<ProviderInfo>(3); 7635 } 7636 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7637 ps.readUserState(userId), userId); 7638 if (info != null) { 7639 finalList.add(info); 7640 } 7641 } 7642 } 7643 } 7644 7645 if (finalList != null) { 7646 Collections.sort(finalList, mProviderInitOrderSorter); 7647 return new ParceledListSlice<ProviderInfo>(finalList); 7648 } 7649 7650 return ParceledListSlice.emptyList(); 7651 } 7652 7653 @Override 7654 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7655 // reader 7656 synchronized (mPackages) { 7657 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7658 return PackageParser.generateInstrumentationInfo(i, flags); 7659 } 7660 } 7661 7662 @Override 7663 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7664 String targetPackage, int flags) { 7665 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7666 } 7667 7668 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7669 int flags) { 7670 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7671 7672 // reader 7673 synchronized (mPackages) { 7674 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7675 while (i.hasNext()) { 7676 final PackageParser.Instrumentation p = i.next(); 7677 if (targetPackage == null 7678 || targetPackage.equals(p.info.targetPackage)) { 7679 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7680 flags); 7681 if (ii != null) { 7682 finalList.add(ii); 7683 } 7684 } 7685 } 7686 } 7687 7688 return finalList; 7689 } 7690 7691 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7692 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7693 try { 7694 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7695 } finally { 7696 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7697 } 7698 } 7699 7700 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7701 final File[] files = dir.listFiles(); 7702 if (ArrayUtils.isEmpty(files)) { 7703 Log.d(TAG, "No files in app dir " + dir); 7704 return; 7705 } 7706 7707 if (DEBUG_PACKAGE_SCANNING) { 7708 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7709 + " flags=0x" + Integer.toHexString(parseFlags)); 7710 } 7711 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7712 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7713 7714 // Submit files for parsing in parallel 7715 int fileCount = 0; 7716 for (File file : files) { 7717 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7718 && !PackageInstallerService.isStageName(file.getName()); 7719 if (!isPackage) { 7720 // Ignore entries which are not packages 7721 continue; 7722 } 7723 parallelPackageParser.submit(file, parseFlags); 7724 fileCount++; 7725 } 7726 7727 // Process results one by one 7728 for (; fileCount > 0; fileCount--) { 7729 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7730 Throwable throwable = parseResult.throwable; 7731 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7732 7733 if (throwable == null) { 7734 // Static shared libraries have synthetic package names 7735 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7736 renameStaticSharedLibraryPackage(parseResult.pkg); 7737 } 7738 try { 7739 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7740 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7741 currentTime, null); 7742 } 7743 } catch (PackageManagerException e) { 7744 errorCode = e.error; 7745 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7746 } 7747 } else if (throwable instanceof PackageParser.PackageParserException) { 7748 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7749 throwable; 7750 errorCode = e.error; 7751 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7752 } else { 7753 throw new IllegalStateException("Unexpected exception occurred while parsing " 7754 + parseResult.scanFile, throwable); 7755 } 7756 7757 // Delete invalid userdata apps 7758 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7759 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7760 logCriticalInfo(Log.WARN, 7761 "Deleting invalid package at " + parseResult.scanFile); 7762 removeCodePathLI(parseResult.scanFile); 7763 } 7764 } 7765 parallelPackageParser.close(); 7766 } 7767 7768 private static File getSettingsProblemFile() { 7769 File dataDir = Environment.getDataDirectory(); 7770 File systemDir = new File(dataDir, "system"); 7771 File fname = new File(systemDir, "uiderrors.txt"); 7772 return fname; 7773 } 7774 7775 static void reportSettingsProblem(int priority, String msg) { 7776 logCriticalInfo(priority, msg); 7777 } 7778 7779 public static void logCriticalInfo(int priority, String msg) { 7780 Slog.println(priority, TAG, msg); 7781 EventLogTags.writePmCriticalInfo(msg); 7782 try { 7783 File fname = getSettingsProblemFile(); 7784 FileOutputStream out = new FileOutputStream(fname, true); 7785 PrintWriter pw = new FastPrintWriter(out); 7786 SimpleDateFormat formatter = new SimpleDateFormat(); 7787 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7788 pw.println(dateString + ": " + msg); 7789 pw.close(); 7790 FileUtils.setPermissions( 7791 fname.toString(), 7792 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7793 -1, -1); 7794 } catch (java.io.IOException e) { 7795 } 7796 } 7797 7798 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7799 if (srcFile.isDirectory()) { 7800 final File baseFile = new File(pkg.baseCodePath); 7801 long maxModifiedTime = baseFile.lastModified(); 7802 if (pkg.splitCodePaths != null) { 7803 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7804 final File splitFile = new File(pkg.splitCodePaths[i]); 7805 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7806 } 7807 } 7808 return maxModifiedTime; 7809 } 7810 return srcFile.lastModified(); 7811 } 7812 7813 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7814 final int policyFlags) throws PackageManagerException { 7815 // When upgrading from pre-N MR1, verify the package time stamp using the package 7816 // directory and not the APK file. 7817 final long lastModifiedTime = mIsPreNMR1Upgrade 7818 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7819 if (ps != null 7820 && ps.codePath.equals(srcFile) 7821 && ps.timeStamp == lastModifiedTime 7822 && !isCompatSignatureUpdateNeeded(pkg) 7823 && !isRecoverSignatureUpdateNeeded(pkg)) { 7824 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7825 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7826 ArraySet<PublicKey> signingKs; 7827 synchronized (mPackages) { 7828 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7829 } 7830 if (ps.signatures.mSignatures != null 7831 && ps.signatures.mSignatures.length != 0 7832 && signingKs != null) { 7833 // Optimization: reuse the existing cached certificates 7834 // if the package appears to be unchanged. 7835 pkg.mSignatures = ps.signatures.mSignatures; 7836 pkg.mSigningKeys = signingKs; 7837 return; 7838 } 7839 7840 Slog.w(TAG, "PackageSetting for " + ps.name 7841 + " is missing signatures. Collecting certs again to recover them."); 7842 } else { 7843 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7844 } 7845 7846 try { 7847 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7848 PackageParser.collectCertificates(pkg, policyFlags); 7849 } catch (PackageParserException e) { 7850 throw PackageManagerException.from(e); 7851 } finally { 7852 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7853 } 7854 } 7855 7856 /** 7857 * Traces a package scan. 7858 * @see #scanPackageLI(File, int, int, long, UserHandle) 7859 */ 7860 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7861 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7862 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7863 try { 7864 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7865 } finally { 7866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7867 } 7868 } 7869 7870 /** 7871 * Scans a package and returns the newly parsed package. 7872 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7873 */ 7874 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7875 long currentTime, UserHandle user) throws PackageManagerException { 7876 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7877 PackageParser pp = new PackageParser(); 7878 pp.setSeparateProcesses(mSeparateProcesses); 7879 pp.setOnlyCoreApps(mOnlyCore); 7880 pp.setDisplayMetrics(mMetrics); 7881 pp.setCallback(mPackageParserCallback); 7882 7883 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7884 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7885 } 7886 7887 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7888 final PackageParser.Package pkg; 7889 try { 7890 pkg = pp.parsePackage(scanFile, parseFlags); 7891 } catch (PackageParserException e) { 7892 throw PackageManagerException.from(e); 7893 } finally { 7894 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7895 } 7896 7897 // Static shared libraries have synthetic package names 7898 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7899 renameStaticSharedLibraryPackage(pkg); 7900 } 7901 7902 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7903 } 7904 7905 /** 7906 * Scans a package and returns the newly parsed package. 7907 * @throws PackageManagerException on a parse error. 7908 */ 7909 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7910 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7911 throws PackageManagerException { 7912 // If the package has children and this is the first dive in the function 7913 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7914 // packages (parent and children) would be successfully scanned before the 7915 // actual scan since scanning mutates internal state and we want to atomically 7916 // install the package and its children. 7917 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7918 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7919 scanFlags |= SCAN_CHECK_ONLY; 7920 } 7921 } else { 7922 scanFlags &= ~SCAN_CHECK_ONLY; 7923 } 7924 7925 // Scan the parent 7926 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7927 scanFlags, currentTime, user); 7928 7929 // Scan the children 7930 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7931 for (int i = 0; i < childCount; i++) { 7932 PackageParser.Package childPackage = pkg.childPackages.get(i); 7933 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7934 currentTime, user); 7935 } 7936 7937 7938 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7939 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7940 } 7941 7942 return scannedPkg; 7943 } 7944 7945 /** 7946 * Scans a package and returns the newly parsed package. 7947 * @throws PackageManagerException on a parse error. 7948 */ 7949 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7950 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7951 throws PackageManagerException { 7952 PackageSetting ps = null; 7953 PackageSetting updatedPkg; 7954 // reader 7955 synchronized (mPackages) { 7956 // Look to see if we already know about this package. 7957 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7958 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7959 // This package has been renamed to its original name. Let's 7960 // use that. 7961 ps = mSettings.getPackageLPr(oldName); 7962 } 7963 // If there was no original package, see one for the real package name. 7964 if (ps == null) { 7965 ps = mSettings.getPackageLPr(pkg.packageName); 7966 } 7967 // Check to see if this package could be hiding/updating a system 7968 // package. Must look for it either under the original or real 7969 // package name depending on our state. 7970 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7971 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7972 7973 // If this is a package we don't know about on the system partition, we 7974 // may need to remove disabled child packages on the system partition 7975 // or may need to not add child packages if the parent apk is updated 7976 // on the data partition and no longer defines this child package. 7977 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7978 // If this is a parent package for an updated system app and this system 7979 // app got an OTA update which no longer defines some of the child packages 7980 // we have to prune them from the disabled system packages. 7981 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7982 if (disabledPs != null) { 7983 final int scannedChildCount = (pkg.childPackages != null) 7984 ? pkg.childPackages.size() : 0; 7985 final int disabledChildCount = disabledPs.childPackageNames != null 7986 ? disabledPs.childPackageNames.size() : 0; 7987 for (int i = 0; i < disabledChildCount; i++) { 7988 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7989 boolean disabledPackageAvailable = false; 7990 for (int j = 0; j < scannedChildCount; j++) { 7991 PackageParser.Package childPkg = pkg.childPackages.get(j); 7992 if (childPkg.packageName.equals(disabledChildPackageName)) { 7993 disabledPackageAvailable = true; 7994 break; 7995 } 7996 } 7997 if (!disabledPackageAvailable) { 7998 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7999 } 8000 } 8001 } 8002 } 8003 } 8004 8005 boolean updatedPkgBetter = false; 8006 // First check if this is a system package that may involve an update 8007 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 8008 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 8009 // it needs to drop FLAG_PRIVILEGED. 8010 if (locationIsPrivileged(scanFile)) { 8011 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8012 } else { 8013 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8014 } 8015 8016 if (ps != null && !ps.codePath.equals(scanFile)) { 8017 // The path has changed from what was last scanned... check the 8018 // version of the new path against what we have stored to determine 8019 // what to do. 8020 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8021 if (pkg.mVersionCode <= ps.versionCode) { 8022 // The system package has been updated and the code path does not match 8023 // Ignore entry. Skip it. 8024 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8025 + " ignored: updated version " + ps.versionCode 8026 + " better than this " + pkg.mVersionCode); 8027 if (!updatedPkg.codePath.equals(scanFile)) { 8028 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8029 + ps.name + " changing from " + updatedPkg.codePathString 8030 + " to " + scanFile); 8031 updatedPkg.codePath = scanFile; 8032 updatedPkg.codePathString = scanFile.toString(); 8033 updatedPkg.resourcePath = scanFile; 8034 updatedPkg.resourcePathString = scanFile.toString(); 8035 } 8036 updatedPkg.pkg = pkg; 8037 updatedPkg.versionCode = pkg.mVersionCode; 8038 8039 // Update the disabled system child packages to point to the package too. 8040 final int childCount = updatedPkg.childPackageNames != null 8041 ? updatedPkg.childPackageNames.size() : 0; 8042 for (int i = 0; i < childCount; i++) { 8043 String childPackageName = updatedPkg.childPackageNames.get(i); 8044 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8045 childPackageName); 8046 if (updatedChildPkg != null) { 8047 updatedChildPkg.pkg = pkg; 8048 updatedChildPkg.versionCode = pkg.mVersionCode; 8049 } 8050 } 8051 8052 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8053 + scanFile + " ignored: updated version " + ps.versionCode 8054 + " better than this " + pkg.mVersionCode); 8055 } else { 8056 // The current app on the system partition is better than 8057 // what we have updated to on the data partition; switch 8058 // back to the system partition version. 8059 // At this point, its safely assumed that package installation for 8060 // apps in system partition will go through. If not there won't be a working 8061 // version of the app 8062 // writer 8063 synchronized (mPackages) { 8064 // Just remove the loaded entries from package lists. 8065 mPackages.remove(ps.name); 8066 } 8067 8068 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8069 + " reverting from " + ps.codePathString 8070 + ": new version " + pkg.mVersionCode 8071 + " better than installed " + ps.versionCode); 8072 8073 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8074 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8075 synchronized (mInstallLock) { 8076 args.cleanUpResourcesLI(); 8077 } 8078 synchronized (mPackages) { 8079 mSettings.enableSystemPackageLPw(ps.name); 8080 } 8081 updatedPkgBetter = true; 8082 } 8083 } 8084 } 8085 8086 if (updatedPkg != null) { 8087 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8088 // initially 8089 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8090 8091 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8092 // flag set initially 8093 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8094 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8095 } 8096 } 8097 8098 // Verify certificates against what was last scanned 8099 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8100 8101 /* 8102 * A new system app appeared, but we already had a non-system one of the 8103 * same name installed earlier. 8104 */ 8105 boolean shouldHideSystemApp = false; 8106 if (updatedPkg == null && ps != null 8107 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8108 /* 8109 * Check to make sure the signatures match first. If they don't, 8110 * wipe the installed application and its data. 8111 */ 8112 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8113 != PackageManager.SIGNATURE_MATCH) { 8114 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8115 + " signatures don't match existing userdata copy; removing"); 8116 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8117 "scanPackageInternalLI")) { 8118 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8119 } 8120 ps = null; 8121 } else { 8122 /* 8123 * If the newly-added system app is an older version than the 8124 * already installed version, hide it. It will be scanned later 8125 * and re-added like an update. 8126 */ 8127 if (pkg.mVersionCode <= ps.versionCode) { 8128 shouldHideSystemApp = true; 8129 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8130 + " but new version " + pkg.mVersionCode + " better than installed " 8131 + ps.versionCode + "; hiding system"); 8132 } else { 8133 /* 8134 * The newly found system app is a newer version that the 8135 * one previously installed. Simply remove the 8136 * already-installed application and replace it with our own 8137 * while keeping the application data. 8138 */ 8139 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8140 + " reverting from " + ps.codePathString + ": new version " 8141 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8142 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8143 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8144 synchronized (mInstallLock) { 8145 args.cleanUpResourcesLI(); 8146 } 8147 } 8148 } 8149 } 8150 8151 // The apk is forward locked (not public) if its code and resources 8152 // are kept in different files. (except for app in either system or 8153 // vendor path). 8154 // TODO grab this value from PackageSettings 8155 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8156 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8157 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8158 } 8159 } 8160 8161 // TODO: extend to support forward-locked splits 8162 String resourcePath = null; 8163 String baseResourcePath = null; 8164 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8165 if (ps != null && ps.resourcePathString != null) { 8166 resourcePath = ps.resourcePathString; 8167 baseResourcePath = ps.resourcePathString; 8168 } else { 8169 // Should not happen at all. Just log an error. 8170 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8171 } 8172 } else { 8173 resourcePath = pkg.codePath; 8174 baseResourcePath = pkg.baseCodePath; 8175 } 8176 8177 // Set application objects path explicitly. 8178 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8179 pkg.setApplicationInfoCodePath(pkg.codePath); 8180 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8181 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8182 pkg.setApplicationInfoResourcePath(resourcePath); 8183 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8184 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8185 8186 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8187 if (ps != null && ps.getInstantApp(userId)) { 8188 scanFlags |= SCAN_AS_INSTANT_APP; 8189 } 8190 8191 // Note that we invoke the following method only if we are about to unpack an application 8192 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8193 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8194 8195 /* 8196 * If the system app should be overridden by a previously installed 8197 * data, hide the system app now and let the /data/app scan pick it up 8198 * again. 8199 */ 8200 if (shouldHideSystemApp) { 8201 synchronized (mPackages) { 8202 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8203 } 8204 } 8205 8206 return scannedPkg; 8207 } 8208 8209 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8210 // Derive the new package synthetic package name 8211 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8212 + pkg.staticSharedLibVersion); 8213 } 8214 8215 private static String fixProcessName(String defProcessName, 8216 String processName) { 8217 if (processName == null) { 8218 return defProcessName; 8219 } 8220 return processName; 8221 } 8222 8223 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8224 throws PackageManagerException { 8225 if (pkgSetting.signatures.mSignatures != null) { 8226 // Already existing package. Make sure signatures match 8227 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8228 == PackageManager.SIGNATURE_MATCH; 8229 if (!match) { 8230 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8231 == PackageManager.SIGNATURE_MATCH; 8232 } 8233 if (!match) { 8234 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8235 == PackageManager.SIGNATURE_MATCH; 8236 } 8237 if (!match) { 8238 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8239 + pkg.packageName + " signatures do not match the " 8240 + "previously installed version; ignoring!"); 8241 } 8242 } 8243 8244 // Check for shared user signatures 8245 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8246 // Already existing package. Make sure signatures match 8247 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8248 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8249 if (!match) { 8250 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8251 == PackageManager.SIGNATURE_MATCH; 8252 } 8253 if (!match) { 8254 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8255 == PackageManager.SIGNATURE_MATCH; 8256 } 8257 if (!match) { 8258 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8259 "Package " + pkg.packageName 8260 + " has no signatures that match those in shared user " 8261 + pkgSetting.sharedUser.name + "; ignoring!"); 8262 } 8263 } 8264 } 8265 8266 /** 8267 * Enforces that only the system UID or root's UID can call a method exposed 8268 * via Binder. 8269 * 8270 * @param message used as message if SecurityException is thrown 8271 * @throws SecurityException if the caller is not system or root 8272 */ 8273 private static final void enforceSystemOrRoot(String message) { 8274 final int uid = Binder.getCallingUid(); 8275 if (uid != Process.SYSTEM_UID && uid != 0) { 8276 throw new SecurityException(message); 8277 } 8278 } 8279 8280 @Override 8281 public void performFstrimIfNeeded() { 8282 enforceSystemOrRoot("Only the system can request fstrim"); 8283 8284 // Before everything else, see whether we need to fstrim. 8285 try { 8286 IStorageManager sm = PackageHelper.getStorageManager(); 8287 if (sm != null) { 8288 boolean doTrim = false; 8289 final long interval = android.provider.Settings.Global.getLong( 8290 mContext.getContentResolver(), 8291 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8292 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8293 if (interval > 0) { 8294 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8295 if (timeSinceLast > interval) { 8296 doTrim = true; 8297 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8298 + "; running immediately"); 8299 } 8300 } 8301 if (doTrim) { 8302 final boolean dexOptDialogShown; 8303 synchronized (mPackages) { 8304 dexOptDialogShown = mDexOptDialogShown; 8305 } 8306 if (!isFirstBoot() && dexOptDialogShown) { 8307 try { 8308 ActivityManager.getService().showBootMessage( 8309 mContext.getResources().getString( 8310 R.string.android_upgrading_fstrim), true); 8311 } catch (RemoteException e) { 8312 } 8313 } 8314 sm.runMaintenance(); 8315 } 8316 } else { 8317 Slog.e(TAG, "storageManager service unavailable!"); 8318 } 8319 } catch (RemoteException e) { 8320 // Can't happen; StorageManagerService is local 8321 } 8322 } 8323 8324 @Override 8325 public void updatePackagesIfNeeded() { 8326 enforceSystemOrRoot("Only the system can request package update"); 8327 8328 // We need to re-extract after an OTA. 8329 boolean causeUpgrade = isUpgrade(); 8330 8331 // First boot or factory reset. 8332 // Note: we also handle devices that are upgrading to N right now as if it is their 8333 // first boot, as they do not have profile data. 8334 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8335 8336 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8337 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8338 8339 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8340 return; 8341 } 8342 8343 List<PackageParser.Package> pkgs; 8344 synchronized (mPackages) { 8345 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8346 } 8347 8348 final long startTime = System.nanoTime(); 8349 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8350 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8351 8352 final int elapsedTimeSeconds = 8353 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8354 8355 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8356 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8357 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8358 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8359 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8360 } 8361 8362 /** 8363 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8364 * containing statistics about the invocation. The array consists of three elements, 8365 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8366 * and {@code numberOfPackagesFailed}. 8367 */ 8368 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8369 String compilerFilter) { 8370 8371 int numberOfPackagesVisited = 0; 8372 int numberOfPackagesOptimized = 0; 8373 int numberOfPackagesSkipped = 0; 8374 int numberOfPackagesFailed = 0; 8375 final int numberOfPackagesToDexopt = pkgs.size(); 8376 8377 for (PackageParser.Package pkg : pkgs) { 8378 numberOfPackagesVisited++; 8379 8380 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8381 if (DEBUG_DEXOPT) { 8382 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8383 } 8384 numberOfPackagesSkipped++; 8385 continue; 8386 } 8387 8388 if (DEBUG_DEXOPT) { 8389 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8390 numberOfPackagesToDexopt + ": " + pkg.packageName); 8391 } 8392 8393 if (showDialog) { 8394 try { 8395 ActivityManager.getService().showBootMessage( 8396 mContext.getResources().getString(R.string.android_upgrading_apk, 8397 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8398 } catch (RemoteException e) { 8399 } 8400 synchronized (mPackages) { 8401 mDexOptDialogShown = true; 8402 } 8403 } 8404 8405 // If the OTA updates a system app which was previously preopted to a non-preopted state 8406 // the app might end up being verified at runtime. That's because by default the apps 8407 // are verify-profile but for preopted apps there's no profile. 8408 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8409 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8410 // filter (by default interpret-only). 8411 // Note that at this stage unused apps are already filtered. 8412 if (isSystemApp(pkg) && 8413 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8414 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8415 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8416 } 8417 8418 // checkProfiles is false to avoid merging profiles during boot which 8419 // might interfere with background compilation (b/28612421). 8420 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8421 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8422 // trade-off worth doing to save boot time work. 8423 int dexOptStatus = performDexOptTraced(pkg.packageName, 8424 false /* checkProfiles */, 8425 compilerFilter, 8426 false /* force */); 8427 switch (dexOptStatus) { 8428 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8429 numberOfPackagesOptimized++; 8430 break; 8431 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8432 numberOfPackagesSkipped++; 8433 break; 8434 case PackageDexOptimizer.DEX_OPT_FAILED: 8435 numberOfPackagesFailed++; 8436 break; 8437 default: 8438 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8439 break; 8440 } 8441 } 8442 8443 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8444 numberOfPackagesFailed }; 8445 } 8446 8447 @Override 8448 public void notifyPackageUse(String packageName, int reason) { 8449 synchronized (mPackages) { 8450 PackageParser.Package p = mPackages.get(packageName); 8451 if (p == null) { 8452 return; 8453 } 8454 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8455 } 8456 } 8457 8458 @Override 8459 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8460 int userId = UserHandle.getCallingUserId(); 8461 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8462 if (ai == null) { 8463 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8464 + loadingPackageName + ", user=" + userId); 8465 return; 8466 } 8467 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8468 } 8469 8470 // TODO: this is not used nor needed. Delete it. 8471 @Override 8472 public boolean performDexOptIfNeeded(String packageName) { 8473 int dexOptStatus = performDexOptTraced(packageName, 8474 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8475 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8476 } 8477 8478 @Override 8479 public boolean performDexOpt(String packageName, 8480 boolean checkProfiles, int compileReason, boolean force) { 8481 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8482 getCompilerFilterForReason(compileReason), force); 8483 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8484 } 8485 8486 @Override 8487 public boolean performDexOptMode(String packageName, 8488 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8489 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8490 targetCompilerFilter, force); 8491 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8492 } 8493 8494 private int performDexOptTraced(String packageName, 8495 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8496 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8497 try { 8498 return performDexOptInternal(packageName, checkProfiles, 8499 targetCompilerFilter, force); 8500 } finally { 8501 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8502 } 8503 } 8504 8505 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8506 // if the package can now be considered up to date for the given filter. 8507 private int performDexOptInternal(String packageName, 8508 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8509 PackageParser.Package p; 8510 synchronized (mPackages) { 8511 p = mPackages.get(packageName); 8512 if (p == null) { 8513 // Package could not be found. Report failure. 8514 return PackageDexOptimizer.DEX_OPT_FAILED; 8515 } 8516 mPackageUsage.maybeWriteAsync(mPackages); 8517 mCompilerStats.maybeWriteAsync(); 8518 } 8519 long callingId = Binder.clearCallingIdentity(); 8520 try { 8521 synchronized (mInstallLock) { 8522 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8523 targetCompilerFilter, force); 8524 } 8525 } finally { 8526 Binder.restoreCallingIdentity(callingId); 8527 } 8528 } 8529 8530 public ArraySet<String> getOptimizablePackages() { 8531 ArraySet<String> pkgs = new ArraySet<String>(); 8532 synchronized (mPackages) { 8533 for (PackageParser.Package p : mPackages.values()) { 8534 if (PackageDexOptimizer.canOptimizePackage(p)) { 8535 pkgs.add(p.packageName); 8536 } 8537 } 8538 } 8539 return pkgs; 8540 } 8541 8542 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8543 boolean checkProfiles, String targetCompilerFilter, 8544 boolean force) { 8545 // Select the dex optimizer based on the force parameter. 8546 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8547 // allocate an object here. 8548 PackageDexOptimizer pdo = force 8549 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8550 : mPackageDexOptimizer; 8551 8552 // Dexopt all dependencies first. Note: we ignore the return value and march on 8553 // on errors. 8554 // Note that we are going to call performDexOpt on those libraries as many times as 8555 // they are referenced in packages. When we do a batch of performDexOpt (for example 8556 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8557 // and the first package that uses the library will dexopt it. The 8558 // others will see that the compiled code for the library is up to date. 8559 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8560 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8561 if (!deps.isEmpty()) { 8562 for (PackageParser.Package depPackage : deps) { 8563 // TODO: Analyze and investigate if we (should) profile libraries. 8564 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8565 false /* checkProfiles */, 8566 targetCompilerFilter, 8567 getOrCreateCompilerPackageStats(depPackage), 8568 true /* isUsedByOtherApps */); 8569 } 8570 } 8571 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8572 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8573 mDexManager.isUsedByOtherApps(p.packageName)); 8574 } 8575 8576 // Performs dexopt on the used secondary dex files belonging to the given package. 8577 // Returns true if all dex files were process successfully (which could mean either dexopt or 8578 // skip). Returns false if any of the files caused errors. 8579 @Override 8580 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8581 boolean force) { 8582 mDexManager.reconcileSecondaryDexFiles(packageName); 8583 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8584 } 8585 8586 public boolean performDexOptSecondary(String packageName, int compileReason, 8587 boolean force) { 8588 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8589 } 8590 8591 /** 8592 * Reconcile the information we have about the secondary dex files belonging to 8593 * {@code packagName} and the actual dex files. For all dex files that were 8594 * deleted, update the internal records and delete the generated oat files. 8595 */ 8596 @Override 8597 public void reconcileSecondaryDexFiles(String packageName) { 8598 mDexManager.reconcileSecondaryDexFiles(packageName); 8599 } 8600 8601 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8602 // a reference there. 8603 /*package*/ DexManager getDexManager() { 8604 return mDexManager; 8605 } 8606 8607 /** 8608 * Execute the background dexopt job immediately. 8609 */ 8610 @Override 8611 public boolean runBackgroundDexoptJob() { 8612 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8613 } 8614 8615 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8616 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8617 || p.usesStaticLibraries != null) { 8618 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8619 Set<String> collectedNames = new HashSet<>(); 8620 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8621 8622 retValue.remove(p); 8623 8624 return retValue; 8625 } else { 8626 return Collections.emptyList(); 8627 } 8628 } 8629 8630 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8631 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8632 if (!collectedNames.contains(p.packageName)) { 8633 collectedNames.add(p.packageName); 8634 collected.add(p); 8635 8636 if (p.usesLibraries != null) { 8637 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8638 null, collected, collectedNames); 8639 } 8640 if (p.usesOptionalLibraries != null) { 8641 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8642 null, collected, collectedNames); 8643 } 8644 if (p.usesStaticLibraries != null) { 8645 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8646 p.usesStaticLibrariesVersions, collected, collectedNames); 8647 } 8648 } 8649 } 8650 8651 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8652 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8653 final int libNameCount = libs.size(); 8654 for (int i = 0; i < libNameCount; i++) { 8655 String libName = libs.get(i); 8656 int version = (versions != null && versions.length == libNameCount) 8657 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8658 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8659 if (libPkg != null) { 8660 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8661 } 8662 } 8663 } 8664 8665 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8666 synchronized (mPackages) { 8667 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8668 if (libEntry != null) { 8669 return mPackages.get(libEntry.apk); 8670 } 8671 return null; 8672 } 8673 } 8674 8675 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8676 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8677 if (versionedLib == null) { 8678 return null; 8679 } 8680 return versionedLib.get(version); 8681 } 8682 8683 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8684 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8685 pkg.staticSharedLibName); 8686 if (versionedLib == null) { 8687 return null; 8688 } 8689 int previousLibVersion = -1; 8690 final int versionCount = versionedLib.size(); 8691 for (int i = 0; i < versionCount; i++) { 8692 final int libVersion = versionedLib.keyAt(i); 8693 if (libVersion < pkg.staticSharedLibVersion) { 8694 previousLibVersion = Math.max(previousLibVersion, libVersion); 8695 } 8696 } 8697 if (previousLibVersion >= 0) { 8698 return versionedLib.get(previousLibVersion); 8699 } 8700 return null; 8701 } 8702 8703 public void shutdown() { 8704 mPackageUsage.writeNow(mPackages); 8705 mCompilerStats.writeNow(); 8706 } 8707 8708 @Override 8709 public void dumpProfiles(String packageName) { 8710 PackageParser.Package pkg; 8711 synchronized (mPackages) { 8712 pkg = mPackages.get(packageName); 8713 if (pkg == null) { 8714 throw new IllegalArgumentException("Unknown package: " + packageName); 8715 } 8716 } 8717 /* Only the shell, root, or the app user should be able to dump profiles. */ 8718 int callingUid = Binder.getCallingUid(); 8719 if (callingUid != Process.SHELL_UID && 8720 callingUid != Process.ROOT_UID && 8721 callingUid != pkg.applicationInfo.uid) { 8722 throw new SecurityException("dumpProfiles"); 8723 } 8724 8725 synchronized (mInstallLock) { 8726 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8727 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8728 try { 8729 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8730 String codePaths = TextUtils.join(";", allCodePaths); 8731 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8732 } catch (InstallerException e) { 8733 Slog.w(TAG, "Failed to dump profiles", e); 8734 } 8735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8736 } 8737 } 8738 8739 @Override 8740 public void forceDexOpt(String packageName) { 8741 enforceSystemOrRoot("forceDexOpt"); 8742 8743 PackageParser.Package pkg; 8744 synchronized (mPackages) { 8745 pkg = mPackages.get(packageName); 8746 if (pkg == null) { 8747 throw new IllegalArgumentException("Unknown package: " + packageName); 8748 } 8749 } 8750 8751 synchronized (mInstallLock) { 8752 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8753 8754 // Whoever is calling forceDexOpt wants a fully compiled package. 8755 // Don't use profiles since that may cause compilation to be skipped. 8756 final int res = performDexOptInternalWithDependenciesLI(pkg, 8757 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8758 true /* force */); 8759 8760 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8761 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8762 throw new IllegalStateException("Failed to dexopt: " + res); 8763 } 8764 } 8765 } 8766 8767 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8768 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8769 Slog.w(TAG, "Unable to update from " + oldPkg.name 8770 + " to " + newPkg.packageName 8771 + ": old package not in system partition"); 8772 return false; 8773 } else if (mPackages.get(oldPkg.name) != null) { 8774 Slog.w(TAG, "Unable to update from " + oldPkg.name 8775 + " to " + newPkg.packageName 8776 + ": old package still exists"); 8777 return false; 8778 } 8779 return true; 8780 } 8781 8782 void removeCodePathLI(File codePath) { 8783 if (codePath.isDirectory()) { 8784 try { 8785 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8786 } catch (InstallerException e) { 8787 Slog.w(TAG, "Failed to remove code path", e); 8788 } 8789 } else { 8790 codePath.delete(); 8791 } 8792 } 8793 8794 private int[] resolveUserIds(int userId) { 8795 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8796 } 8797 8798 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8799 if (pkg == null) { 8800 Slog.wtf(TAG, "Package was null!", new Throwable()); 8801 return; 8802 } 8803 clearAppDataLeafLIF(pkg, userId, flags); 8804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8805 for (int i = 0; i < childCount; i++) { 8806 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8807 } 8808 } 8809 8810 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8811 final PackageSetting ps; 8812 synchronized (mPackages) { 8813 ps = mSettings.mPackages.get(pkg.packageName); 8814 } 8815 for (int realUserId : resolveUserIds(userId)) { 8816 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8817 try { 8818 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8819 ceDataInode); 8820 } catch (InstallerException e) { 8821 Slog.w(TAG, String.valueOf(e)); 8822 } 8823 } 8824 } 8825 8826 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8827 if (pkg == null) { 8828 Slog.wtf(TAG, "Package was null!", new Throwable()); 8829 return; 8830 } 8831 destroyAppDataLeafLIF(pkg, userId, flags); 8832 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8833 for (int i = 0; i < childCount; i++) { 8834 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8835 } 8836 } 8837 8838 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8839 final PackageSetting ps; 8840 synchronized (mPackages) { 8841 ps = mSettings.mPackages.get(pkg.packageName); 8842 } 8843 for (int realUserId : resolveUserIds(userId)) { 8844 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8845 try { 8846 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8847 ceDataInode); 8848 } catch (InstallerException e) { 8849 Slog.w(TAG, String.valueOf(e)); 8850 } 8851 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8852 } 8853 } 8854 8855 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8856 if (pkg == null) { 8857 Slog.wtf(TAG, "Package was null!", new Throwable()); 8858 return; 8859 } 8860 destroyAppProfilesLeafLIF(pkg); 8861 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8862 for (int i = 0; i < childCount; i++) { 8863 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8864 } 8865 } 8866 8867 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8868 try { 8869 mInstaller.destroyAppProfiles(pkg.packageName); 8870 } catch (InstallerException e) { 8871 Slog.w(TAG, String.valueOf(e)); 8872 } 8873 } 8874 8875 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8876 if (pkg == null) { 8877 Slog.wtf(TAG, "Package was null!", new Throwable()); 8878 return; 8879 } 8880 clearAppProfilesLeafLIF(pkg); 8881 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8882 for (int i = 0; i < childCount; i++) { 8883 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8884 } 8885 } 8886 8887 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8888 try { 8889 mInstaller.clearAppProfiles(pkg.packageName); 8890 } catch (InstallerException e) { 8891 Slog.w(TAG, String.valueOf(e)); 8892 } 8893 } 8894 8895 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8896 long lastUpdateTime) { 8897 // Set parent install/update time 8898 PackageSetting ps = (PackageSetting) pkg.mExtras; 8899 if (ps != null) { 8900 ps.firstInstallTime = firstInstallTime; 8901 ps.lastUpdateTime = lastUpdateTime; 8902 } 8903 // Set children install/update time 8904 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8905 for (int i = 0; i < childCount; i++) { 8906 PackageParser.Package childPkg = pkg.childPackages.get(i); 8907 ps = (PackageSetting) childPkg.mExtras; 8908 if (ps != null) { 8909 ps.firstInstallTime = firstInstallTime; 8910 ps.lastUpdateTime = lastUpdateTime; 8911 } 8912 } 8913 } 8914 8915 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8916 PackageParser.Package changingLib) { 8917 if (file.path != null) { 8918 usesLibraryFiles.add(file.path); 8919 return; 8920 } 8921 PackageParser.Package p = mPackages.get(file.apk); 8922 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8923 // If we are doing this while in the middle of updating a library apk, 8924 // then we need to make sure to use that new apk for determining the 8925 // dependencies here. (We haven't yet finished committing the new apk 8926 // to the package manager state.) 8927 if (p == null || p.packageName.equals(changingLib.packageName)) { 8928 p = changingLib; 8929 } 8930 } 8931 if (p != null) { 8932 usesLibraryFiles.addAll(p.getAllCodePaths()); 8933 } 8934 } 8935 8936 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8937 PackageParser.Package changingLib) throws PackageManagerException { 8938 if (pkg == null) { 8939 return; 8940 } 8941 ArraySet<String> usesLibraryFiles = null; 8942 if (pkg.usesLibraries != null) { 8943 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8944 null, null, pkg.packageName, changingLib, true, null); 8945 } 8946 if (pkg.usesStaticLibraries != null) { 8947 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8948 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8949 pkg.packageName, changingLib, true, usesLibraryFiles); 8950 } 8951 if (pkg.usesOptionalLibraries != null) { 8952 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8953 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8954 } 8955 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8956 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8957 } else { 8958 pkg.usesLibraryFiles = null; 8959 } 8960 } 8961 8962 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8963 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8964 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8965 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8966 throws PackageManagerException { 8967 final int libCount = requestedLibraries.size(); 8968 for (int i = 0; i < libCount; i++) { 8969 final String libName = requestedLibraries.get(i); 8970 final int libVersion = requiredVersions != null ? requiredVersions[i] 8971 : SharedLibraryInfo.VERSION_UNDEFINED; 8972 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8973 if (libEntry == null) { 8974 if (required) { 8975 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8976 "Package " + packageName + " requires unavailable shared library " 8977 + libName + "; failing!"); 8978 } else { 8979 Slog.w(TAG, "Package " + packageName 8980 + " desires unavailable shared library " 8981 + libName + "; ignoring!"); 8982 } 8983 } else { 8984 if (requiredVersions != null && requiredCertDigests != null) { 8985 if (libEntry.info.getVersion() != requiredVersions[i]) { 8986 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8987 "Package " + packageName + " requires unavailable static shared" 8988 + " library " + libName + " version " 8989 + libEntry.info.getVersion() + "; failing!"); 8990 } 8991 8992 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8993 if (libPkg == null) { 8994 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8995 "Package " + packageName + " requires unavailable static shared" 8996 + " library; failing!"); 8997 } 8998 8999 String expectedCertDigest = requiredCertDigests[i]; 9000 String libCertDigest = PackageUtils.computeCertSha256Digest( 9001 libPkg.mSignatures[0]); 9002 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 9003 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9004 "Package " + packageName + " requires differently signed" + 9005 " static shared library; failing!"); 9006 } 9007 } 9008 9009 if (outUsedLibraries == null) { 9010 outUsedLibraries = new ArraySet<>(); 9011 } 9012 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9013 } 9014 } 9015 return outUsedLibraries; 9016 } 9017 9018 private static boolean hasString(List<String> list, List<String> which) { 9019 if (list == null) { 9020 return false; 9021 } 9022 for (int i=list.size()-1; i>=0; i--) { 9023 for (int j=which.size()-1; j>=0; j--) { 9024 if (which.get(j).equals(list.get(i))) { 9025 return true; 9026 } 9027 } 9028 } 9029 return false; 9030 } 9031 9032 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9033 PackageParser.Package changingPkg) { 9034 ArrayList<PackageParser.Package> res = null; 9035 for (PackageParser.Package pkg : mPackages.values()) { 9036 if (changingPkg != null 9037 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9038 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9039 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9040 changingPkg.staticSharedLibName)) { 9041 return null; 9042 } 9043 if (res == null) { 9044 res = new ArrayList<>(); 9045 } 9046 res.add(pkg); 9047 try { 9048 updateSharedLibrariesLPr(pkg, changingPkg); 9049 } catch (PackageManagerException e) { 9050 // If a system app update or an app and a required lib missing we 9051 // delete the package and for updated system apps keep the data as 9052 // it is better for the user to reinstall than to be in an limbo 9053 // state. Also libs disappearing under an app should never happen 9054 // - just in case. 9055 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9056 final int flags = pkg.isUpdatedSystemApp() 9057 ? PackageManager.DELETE_KEEP_DATA : 0; 9058 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9059 flags , null, true, null); 9060 } 9061 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9062 } 9063 } 9064 return res; 9065 } 9066 9067 /** 9068 * Derive the value of the {@code cpuAbiOverride} based on the provided 9069 * value and an optional stored value from the package settings. 9070 */ 9071 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9072 String cpuAbiOverride = null; 9073 9074 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9075 cpuAbiOverride = null; 9076 } else if (abiOverride != null) { 9077 cpuAbiOverride = abiOverride; 9078 } else if (settings != null) { 9079 cpuAbiOverride = settings.cpuAbiOverrideString; 9080 } 9081 9082 return cpuAbiOverride; 9083 } 9084 9085 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9086 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9087 throws PackageManagerException { 9088 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9089 // If the package has children and this is the first dive in the function 9090 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9091 // whether all packages (parent and children) would be successfully scanned 9092 // before the actual scan since scanning mutates internal state and we want 9093 // to atomically install the package and its children. 9094 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9095 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9096 scanFlags |= SCAN_CHECK_ONLY; 9097 } 9098 } else { 9099 scanFlags &= ~SCAN_CHECK_ONLY; 9100 } 9101 9102 final PackageParser.Package scannedPkg; 9103 try { 9104 // Scan the parent 9105 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9106 // Scan the children 9107 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9108 for (int i = 0; i < childCount; i++) { 9109 PackageParser.Package childPkg = pkg.childPackages.get(i); 9110 scanPackageLI(childPkg, policyFlags, 9111 scanFlags, currentTime, user); 9112 } 9113 } finally { 9114 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9115 } 9116 9117 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9118 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9119 } 9120 9121 return scannedPkg; 9122 } 9123 9124 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9125 int scanFlags, long currentTime, @Nullable UserHandle user) 9126 throws PackageManagerException { 9127 boolean success = false; 9128 try { 9129 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9130 currentTime, user); 9131 success = true; 9132 return res; 9133 } finally { 9134 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9135 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9136 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9137 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9138 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9139 } 9140 } 9141 } 9142 9143 /** 9144 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9145 */ 9146 private static boolean apkHasCode(String fileName) { 9147 StrictJarFile jarFile = null; 9148 try { 9149 jarFile = new StrictJarFile(fileName, 9150 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9151 return jarFile.findEntry("classes.dex") != null; 9152 } catch (IOException ignore) { 9153 } finally { 9154 try { 9155 if (jarFile != null) { 9156 jarFile.close(); 9157 } 9158 } catch (IOException ignore) {} 9159 } 9160 return false; 9161 } 9162 9163 /** 9164 * Enforces code policy for the package. This ensures that if an APK has 9165 * declared hasCode="true" in its manifest that the APK actually contains 9166 * code. 9167 * 9168 * @throws PackageManagerException If bytecode could not be found when it should exist 9169 */ 9170 private static void assertCodePolicy(PackageParser.Package pkg) 9171 throws PackageManagerException { 9172 final boolean shouldHaveCode = 9173 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9174 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9175 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9176 "Package " + pkg.baseCodePath + " code is missing"); 9177 } 9178 9179 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9180 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9181 final boolean splitShouldHaveCode = 9182 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9183 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9184 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9185 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9186 } 9187 } 9188 } 9189 } 9190 9191 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9192 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9193 throws PackageManagerException { 9194 if (DEBUG_PACKAGE_SCANNING) { 9195 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9196 Log.d(TAG, "Scanning package " + pkg.packageName); 9197 } 9198 9199 applyPolicy(pkg, policyFlags); 9200 9201 assertPackageIsValid(pkg, policyFlags, scanFlags); 9202 9203 // Initialize package source and resource directories 9204 final File scanFile = new File(pkg.codePath); 9205 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9206 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9207 9208 SharedUserSetting suid = null; 9209 PackageSetting pkgSetting = null; 9210 9211 // Getting the package setting may have a side-effect, so if we 9212 // are only checking if scan would succeed, stash a copy of the 9213 // old setting to restore at the end. 9214 PackageSetting nonMutatedPs = null; 9215 9216 // We keep references to the derived CPU Abis from settings in oder to reuse 9217 // them in the case where we're not upgrading or booting for the first time. 9218 String primaryCpuAbiFromSettings = null; 9219 String secondaryCpuAbiFromSettings = null; 9220 9221 // writer 9222 synchronized (mPackages) { 9223 if (pkg.mSharedUserId != null) { 9224 // SIDE EFFECTS; may potentially allocate a new shared user 9225 suid = mSettings.getSharedUserLPw( 9226 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9227 if (DEBUG_PACKAGE_SCANNING) { 9228 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9229 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9230 + "): packages=" + suid.packages); 9231 } 9232 } 9233 9234 // Check if we are renaming from an original package name. 9235 PackageSetting origPackage = null; 9236 String realName = null; 9237 if (pkg.mOriginalPackages != null) { 9238 // This package may need to be renamed to a previously 9239 // installed name. Let's check on that... 9240 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9241 if (pkg.mOriginalPackages.contains(renamed)) { 9242 // This package had originally been installed as the 9243 // original name, and we have already taken care of 9244 // transitioning to the new one. Just update the new 9245 // one to continue using the old name. 9246 realName = pkg.mRealPackage; 9247 if (!pkg.packageName.equals(renamed)) { 9248 // Callers into this function may have already taken 9249 // care of renaming the package; only do it here if 9250 // it is not already done. 9251 pkg.setPackageName(renamed); 9252 } 9253 } else { 9254 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9255 if ((origPackage = mSettings.getPackageLPr( 9256 pkg.mOriginalPackages.get(i))) != null) { 9257 // We do have the package already installed under its 9258 // original name... should we use it? 9259 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9260 // New package is not compatible with original. 9261 origPackage = null; 9262 continue; 9263 } else if (origPackage.sharedUser != null) { 9264 // Make sure uid is compatible between packages. 9265 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9266 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9267 + " to " + pkg.packageName + ": old uid " 9268 + origPackage.sharedUser.name 9269 + " differs from " + pkg.mSharedUserId); 9270 origPackage = null; 9271 continue; 9272 } 9273 // TODO: Add case when shared user id is added [b/28144775] 9274 } else { 9275 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9276 + pkg.packageName + " to old name " + origPackage.name); 9277 } 9278 break; 9279 } 9280 } 9281 } 9282 } 9283 9284 if (mTransferedPackages.contains(pkg.packageName)) { 9285 Slog.w(TAG, "Package " + pkg.packageName 9286 + " was transferred to another, but its .apk remains"); 9287 } 9288 9289 // See comments in nonMutatedPs declaration 9290 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9291 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9292 if (foundPs != null) { 9293 nonMutatedPs = new PackageSetting(foundPs); 9294 } 9295 } 9296 9297 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9298 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9299 if (foundPs != null) { 9300 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9301 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9302 } 9303 } 9304 9305 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9306 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9307 PackageManagerService.reportSettingsProblem(Log.WARN, 9308 "Package " + pkg.packageName + " shared user changed from " 9309 + (pkgSetting.sharedUser != null 9310 ? pkgSetting.sharedUser.name : "<nothing>") 9311 + " to " 9312 + (suid != null ? suid.name : "<nothing>") 9313 + "; replacing with new"); 9314 pkgSetting = null; 9315 } 9316 final PackageSetting oldPkgSetting = 9317 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9318 final PackageSetting disabledPkgSetting = 9319 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9320 9321 String[] usesStaticLibraries = null; 9322 if (pkg.usesStaticLibraries != null) { 9323 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9324 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9325 } 9326 9327 if (pkgSetting == null) { 9328 final String parentPackageName = (pkg.parentPackage != null) 9329 ? pkg.parentPackage.packageName : null; 9330 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9331 // REMOVE SharedUserSetting from method; update in a separate call 9332 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9333 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9334 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9335 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9336 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9337 true /*allowInstall*/, instantApp, parentPackageName, 9338 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9339 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9340 // SIDE EFFECTS; updates system state; move elsewhere 9341 if (origPackage != null) { 9342 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9343 } 9344 mSettings.addUserToSettingLPw(pkgSetting); 9345 } else { 9346 // REMOVE SharedUserSetting from method; update in a separate call. 9347 // 9348 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9349 // secondaryCpuAbi are not known at this point so we always update them 9350 // to null here, only to reset them at a later point. 9351 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9352 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9353 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9354 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9355 UserManagerService.getInstance(), usesStaticLibraries, 9356 pkg.usesStaticLibrariesVersions); 9357 } 9358 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9359 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9360 9361 // SIDE EFFECTS; modifies system state; move elsewhere 9362 if (pkgSetting.origPackage != null) { 9363 // If we are first transitioning from an original package, 9364 // fix up the new package's name now. We need to do this after 9365 // looking up the package under its new name, so getPackageLP 9366 // can take care of fiddling things correctly. 9367 pkg.setPackageName(origPackage.name); 9368 9369 // File a report about this. 9370 String msg = "New package " + pkgSetting.realName 9371 + " renamed to replace old package " + pkgSetting.name; 9372 reportSettingsProblem(Log.WARN, msg); 9373 9374 // Make a note of it. 9375 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9376 mTransferedPackages.add(origPackage.name); 9377 } 9378 9379 // No longer need to retain this. 9380 pkgSetting.origPackage = null; 9381 } 9382 9383 // SIDE EFFECTS; modifies system state; move elsewhere 9384 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9385 // Make a note of it. 9386 mTransferedPackages.add(pkg.packageName); 9387 } 9388 9389 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9390 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9391 } 9392 9393 if ((scanFlags & SCAN_BOOTING) == 0 9394 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9395 // Check all shared libraries and map to their actual file path. 9396 // We only do this here for apps not on a system dir, because those 9397 // are the only ones that can fail an install due to this. We 9398 // will take care of the system apps by updating all of their 9399 // library paths after the scan is done. Also during the initial 9400 // scan don't update any libs as we do this wholesale after all 9401 // apps are scanned to avoid dependency based scanning. 9402 updateSharedLibrariesLPr(pkg, null); 9403 } 9404 9405 if (mFoundPolicyFile) { 9406 SELinuxMMAC.assignSeInfoValue(pkg); 9407 } 9408 pkg.applicationInfo.uid = pkgSetting.appId; 9409 pkg.mExtras = pkgSetting; 9410 9411 9412 // Static shared libs have same package with different versions where 9413 // we internally use a synthetic package name to allow multiple versions 9414 // of the same package, therefore we need to compare signatures against 9415 // the package setting for the latest library version. 9416 PackageSetting signatureCheckPs = pkgSetting; 9417 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9418 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9419 if (libraryEntry != null) { 9420 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9421 } 9422 } 9423 9424 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9425 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9426 // We just determined the app is signed correctly, so bring 9427 // over the latest parsed certs. 9428 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9429 } else { 9430 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9431 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9432 "Package " + pkg.packageName + " upgrade keys do not match the " 9433 + "previously installed version"); 9434 } else { 9435 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9436 String msg = "System package " + pkg.packageName 9437 + " signature changed; retaining data."; 9438 reportSettingsProblem(Log.WARN, msg); 9439 } 9440 } 9441 } else { 9442 try { 9443 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9444 verifySignaturesLP(signatureCheckPs, pkg); 9445 // We just determined the app is signed correctly, so bring 9446 // over the latest parsed certs. 9447 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9448 } catch (PackageManagerException e) { 9449 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9450 throw e; 9451 } 9452 // The signature has changed, but this package is in the system 9453 // image... let's recover! 9454 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9455 // However... if this package is part of a shared user, but it 9456 // doesn't match the signature of the shared user, let's fail. 9457 // What this means is that you can't change the signatures 9458 // associated with an overall shared user, which doesn't seem all 9459 // that unreasonable. 9460 if (signatureCheckPs.sharedUser != null) { 9461 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9462 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9463 throw new PackageManagerException( 9464 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9465 "Signature mismatch for shared user: " 9466 + pkgSetting.sharedUser); 9467 } 9468 } 9469 // File a report about this. 9470 String msg = "System package " + pkg.packageName 9471 + " signature changed; retaining data."; 9472 reportSettingsProblem(Log.WARN, msg); 9473 } 9474 } 9475 9476 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9477 // This package wants to adopt ownership of permissions from 9478 // another package. 9479 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9480 final String origName = pkg.mAdoptPermissions.get(i); 9481 final PackageSetting orig = mSettings.getPackageLPr(origName); 9482 if (orig != null) { 9483 if (verifyPackageUpdateLPr(orig, pkg)) { 9484 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9485 + pkg.packageName); 9486 // SIDE EFFECTS; updates permissions system state; move elsewhere 9487 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9488 } 9489 } 9490 } 9491 } 9492 } 9493 9494 pkg.applicationInfo.processName = fixProcessName( 9495 pkg.applicationInfo.packageName, 9496 pkg.applicationInfo.processName); 9497 9498 if (pkg != mPlatformPackage) { 9499 // Get all of our default paths setup 9500 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9501 } 9502 9503 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9504 9505 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9506 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9508 derivePackageAbi( 9509 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9511 9512 // Some system apps still use directory structure for native libraries 9513 // in which case we might end up not detecting abi solely based on apk 9514 // structure. Try to detect abi based on directory structure. 9515 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9516 pkg.applicationInfo.primaryCpuAbi == null) { 9517 setBundledAppAbisAndRoots(pkg, pkgSetting); 9518 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9519 } 9520 } else { 9521 // This is not a first boot or an upgrade, don't bother deriving the 9522 // ABI during the scan. Instead, trust the value that was stored in the 9523 // package setting. 9524 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9525 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9526 9527 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9528 9529 if (DEBUG_ABI_SELECTION) { 9530 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9531 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9532 pkg.applicationInfo.secondaryCpuAbi); 9533 } 9534 } 9535 } else { 9536 if ((scanFlags & SCAN_MOVE) != 0) { 9537 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9538 // but we already have this packages package info in the PackageSetting. We just 9539 // use that and derive the native library path based on the new codepath. 9540 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9541 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9542 } 9543 9544 // Set native library paths again. For moves, the path will be updated based on the 9545 // ABIs we've determined above. For non-moves, the path will be updated based on the 9546 // ABIs we determined during compilation, but the path will depend on the final 9547 // package path (after the rename away from the stage path). 9548 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9549 } 9550 9551 // This is a special case for the "system" package, where the ABI is 9552 // dictated by the zygote configuration (and init.rc). We should keep track 9553 // of this ABI so that we can deal with "normal" applications that run under 9554 // the same UID correctly. 9555 if (mPlatformPackage == pkg) { 9556 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9557 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9558 } 9559 9560 // If there's a mismatch between the abi-override in the package setting 9561 // and the abiOverride specified for the install. Warn about this because we 9562 // would've already compiled the app without taking the package setting into 9563 // account. 9564 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9565 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9566 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9567 " for package " + pkg.packageName); 9568 } 9569 } 9570 9571 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9572 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9573 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9574 9575 // Copy the derived override back to the parsed package, so that we can 9576 // update the package settings accordingly. 9577 pkg.cpuAbiOverride = cpuAbiOverride; 9578 9579 if (DEBUG_ABI_SELECTION) { 9580 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9581 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9582 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9583 } 9584 9585 // Push the derived path down into PackageSettings so we know what to 9586 // clean up at uninstall time. 9587 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9588 9589 if (DEBUG_ABI_SELECTION) { 9590 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9591 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9592 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9593 } 9594 9595 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9596 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9597 // We don't do this here during boot because we can do it all 9598 // at once after scanning all existing packages. 9599 // 9600 // We also do this *before* we perform dexopt on this package, so that 9601 // we can avoid redundant dexopts, and also to make sure we've got the 9602 // code and package path correct. 9603 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9604 } 9605 9606 if (mFactoryTest && pkg.requestedPermissions.contains( 9607 android.Manifest.permission.FACTORY_TEST)) { 9608 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9609 } 9610 9611 if (isSystemApp(pkg)) { 9612 pkgSetting.isOrphaned = true; 9613 } 9614 9615 // Take care of first install / last update times. 9616 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9617 if (currentTime != 0) { 9618 if (pkgSetting.firstInstallTime == 0) { 9619 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9620 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9621 pkgSetting.lastUpdateTime = currentTime; 9622 } 9623 } else if (pkgSetting.firstInstallTime == 0) { 9624 // We need *something*. Take time time stamp of the file. 9625 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9626 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9627 if (scanFileTime != pkgSetting.timeStamp) { 9628 // A package on the system image has changed; consider this 9629 // to be an update. 9630 pkgSetting.lastUpdateTime = scanFileTime; 9631 } 9632 } 9633 pkgSetting.setTimeStamp(scanFileTime); 9634 9635 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9636 if (nonMutatedPs != null) { 9637 synchronized (mPackages) { 9638 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9639 } 9640 } 9641 } else { 9642 final int userId = user == null ? 0 : user.getIdentifier(); 9643 // Modify state for the given package setting 9644 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9645 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9646 if (pkgSetting.getInstantApp(userId)) { 9647 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9648 } 9649 } 9650 return pkg; 9651 } 9652 9653 /** 9654 * Applies policy to the parsed package based upon the given policy flags. 9655 * Ensures the package is in a good state. 9656 * <p> 9657 * Implementation detail: This method must NOT have any side effect. It would 9658 * ideally be static, but, it requires locks to read system state. 9659 */ 9660 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9661 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9662 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9663 if (pkg.applicationInfo.isDirectBootAware()) { 9664 // we're direct boot aware; set for all components 9665 for (PackageParser.Service s : pkg.services) { 9666 s.info.encryptionAware = s.info.directBootAware = true; 9667 } 9668 for (PackageParser.Provider p : pkg.providers) { 9669 p.info.encryptionAware = p.info.directBootAware = true; 9670 } 9671 for (PackageParser.Activity a : pkg.activities) { 9672 a.info.encryptionAware = a.info.directBootAware = true; 9673 } 9674 for (PackageParser.Activity r : pkg.receivers) { 9675 r.info.encryptionAware = r.info.directBootAware = true; 9676 } 9677 } 9678 } else { 9679 // Only allow system apps to be flagged as core apps. 9680 pkg.coreApp = false; 9681 // clear flags not applicable to regular apps 9682 pkg.applicationInfo.privateFlags &= 9683 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9684 pkg.applicationInfo.privateFlags &= 9685 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9686 } 9687 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9688 9689 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9690 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9691 } 9692 9693 if (!isSystemApp(pkg)) { 9694 // Only system apps can use these features. 9695 pkg.mOriginalPackages = null; 9696 pkg.mRealPackage = null; 9697 pkg.mAdoptPermissions = null; 9698 } 9699 } 9700 9701 /** 9702 * Asserts the parsed package is valid according to the given policy. If the 9703 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9704 * <p> 9705 * Implementation detail: This method must NOT have any side effects. It would 9706 * ideally be static, but, it requires locks to read system state. 9707 * 9708 * @throws PackageManagerException If the package fails any of the validation checks 9709 */ 9710 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9711 throws PackageManagerException { 9712 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9713 assertCodePolicy(pkg); 9714 } 9715 9716 if (pkg.applicationInfo.getCodePath() == null || 9717 pkg.applicationInfo.getResourcePath() == null) { 9718 // Bail out. The resource and code paths haven't been set. 9719 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9720 "Code and resource paths haven't been set correctly"); 9721 } 9722 9723 // Make sure we're not adding any bogus keyset info 9724 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9725 ksms.assertScannedPackageValid(pkg); 9726 9727 synchronized (mPackages) { 9728 // The special "android" package can only be defined once 9729 if (pkg.packageName.equals("android")) { 9730 if (mAndroidApplication != null) { 9731 Slog.w(TAG, "*************************************************"); 9732 Slog.w(TAG, "Core android package being redefined. Skipping."); 9733 Slog.w(TAG, " codePath=" + pkg.codePath); 9734 Slog.w(TAG, "*************************************************"); 9735 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9736 "Core android package being redefined. Skipping."); 9737 } 9738 } 9739 9740 // A package name must be unique; don't allow duplicates 9741 if (mPackages.containsKey(pkg.packageName)) { 9742 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9743 "Application package " + pkg.packageName 9744 + " already installed. Skipping duplicate."); 9745 } 9746 9747 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9748 // Static libs have a synthetic package name containing the version 9749 // but we still want the base name to be unique. 9750 if (mPackages.containsKey(pkg.manifestPackageName)) { 9751 throw new PackageManagerException( 9752 "Duplicate static shared lib provider package"); 9753 } 9754 9755 // Static shared libraries should have at least O target SDK 9756 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9757 throw new PackageManagerException( 9758 "Packages declaring static-shared libs must target O SDK or higher"); 9759 } 9760 9761 // Package declaring static a shared lib cannot be instant apps 9762 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9763 throw new PackageManagerException( 9764 "Packages declaring static-shared libs cannot be instant apps"); 9765 } 9766 9767 // Package declaring static a shared lib cannot be renamed since the package 9768 // name is synthetic and apps can't code around package manager internals. 9769 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9770 throw new PackageManagerException( 9771 "Packages declaring static-shared libs cannot be renamed"); 9772 } 9773 9774 // Package declaring static a shared lib cannot declare child packages 9775 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9776 throw new PackageManagerException( 9777 "Packages declaring static-shared libs cannot have child packages"); 9778 } 9779 9780 // Package declaring static a shared lib cannot declare dynamic libs 9781 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9782 throw new PackageManagerException( 9783 "Packages declaring static-shared libs cannot declare dynamic libs"); 9784 } 9785 9786 // Package declaring static a shared lib cannot declare shared users 9787 if (pkg.mSharedUserId != null) { 9788 throw new PackageManagerException( 9789 "Packages declaring static-shared libs cannot declare shared users"); 9790 } 9791 9792 // Static shared libs cannot declare activities 9793 if (!pkg.activities.isEmpty()) { 9794 throw new PackageManagerException( 9795 "Static shared libs cannot declare activities"); 9796 } 9797 9798 // Static shared libs cannot declare services 9799 if (!pkg.services.isEmpty()) { 9800 throw new PackageManagerException( 9801 "Static shared libs cannot declare services"); 9802 } 9803 9804 // Static shared libs cannot declare providers 9805 if (!pkg.providers.isEmpty()) { 9806 throw new PackageManagerException( 9807 "Static shared libs cannot declare content providers"); 9808 } 9809 9810 // Static shared libs cannot declare receivers 9811 if (!pkg.receivers.isEmpty()) { 9812 throw new PackageManagerException( 9813 "Static shared libs cannot declare broadcast receivers"); 9814 } 9815 9816 // Static shared libs cannot declare permission groups 9817 if (!pkg.permissionGroups.isEmpty()) { 9818 throw new PackageManagerException( 9819 "Static shared libs cannot declare permission groups"); 9820 } 9821 9822 // Static shared libs cannot declare permissions 9823 if (!pkg.permissions.isEmpty()) { 9824 throw new PackageManagerException( 9825 "Static shared libs cannot declare permissions"); 9826 } 9827 9828 // Static shared libs cannot declare protected broadcasts 9829 if (pkg.protectedBroadcasts != null) { 9830 throw new PackageManagerException( 9831 "Static shared libs cannot declare protected broadcasts"); 9832 } 9833 9834 // Static shared libs cannot be overlay targets 9835 if (pkg.mOverlayTarget != null) { 9836 throw new PackageManagerException( 9837 "Static shared libs cannot be overlay targets"); 9838 } 9839 9840 // The version codes must be ordered as lib versions 9841 int minVersionCode = Integer.MIN_VALUE; 9842 int maxVersionCode = Integer.MAX_VALUE; 9843 9844 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9845 pkg.staticSharedLibName); 9846 if (versionedLib != null) { 9847 final int versionCount = versionedLib.size(); 9848 for (int i = 0; i < versionCount; i++) { 9849 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9850 // TODO: We will change version code to long, so in the new API it is long 9851 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9852 .getVersionCode(); 9853 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9854 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9855 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9856 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9857 } else { 9858 minVersionCode = maxVersionCode = libVersionCode; 9859 break; 9860 } 9861 } 9862 } 9863 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9864 throw new PackageManagerException("Static shared" 9865 + " lib version codes must be ordered as lib versions"); 9866 } 9867 } 9868 9869 // Only privileged apps and updated privileged apps can add child packages. 9870 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9871 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9872 throw new PackageManagerException("Only privileged apps can add child " 9873 + "packages. Ignoring package " + pkg.packageName); 9874 } 9875 final int childCount = pkg.childPackages.size(); 9876 for (int i = 0; i < childCount; i++) { 9877 PackageParser.Package childPkg = pkg.childPackages.get(i); 9878 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9879 childPkg.packageName)) { 9880 throw new PackageManagerException("Can't override child of " 9881 + "another disabled app. Ignoring package " + pkg.packageName); 9882 } 9883 } 9884 } 9885 9886 // If we're only installing presumed-existing packages, require that the 9887 // scanned APK is both already known and at the path previously established 9888 // for it. Previously unknown packages we pick up normally, but if we have an 9889 // a priori expectation about this package's install presence, enforce it. 9890 // With a singular exception for new system packages. When an OTA contains 9891 // a new system package, we allow the codepath to change from a system location 9892 // to the user-installed location. If we don't allow this change, any newer, 9893 // user-installed version of the application will be ignored. 9894 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9895 if (mExpectingBetter.containsKey(pkg.packageName)) { 9896 logCriticalInfo(Log.WARN, 9897 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9898 } else { 9899 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9900 if (known != null) { 9901 if (DEBUG_PACKAGE_SCANNING) { 9902 Log.d(TAG, "Examining " + pkg.codePath 9903 + " and requiring known paths " + known.codePathString 9904 + " & " + known.resourcePathString); 9905 } 9906 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9907 || !pkg.applicationInfo.getResourcePath().equals( 9908 known.resourcePathString)) { 9909 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9910 "Application package " + pkg.packageName 9911 + " found at " + pkg.applicationInfo.getCodePath() 9912 + " but expected at " + known.codePathString 9913 + "; ignoring."); 9914 } 9915 } 9916 } 9917 } 9918 9919 // Verify that this new package doesn't have any content providers 9920 // that conflict with existing packages. Only do this if the 9921 // package isn't already installed, since we don't want to break 9922 // things that are installed. 9923 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9924 final int N = pkg.providers.size(); 9925 int i; 9926 for (i=0; i<N; i++) { 9927 PackageParser.Provider p = pkg.providers.get(i); 9928 if (p.info.authority != null) { 9929 String names[] = p.info.authority.split(";"); 9930 for (int j = 0; j < names.length; j++) { 9931 if (mProvidersByAuthority.containsKey(names[j])) { 9932 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9933 final String otherPackageName = 9934 ((other != null && other.getComponentName() != null) ? 9935 other.getComponentName().getPackageName() : "?"); 9936 throw new PackageManagerException( 9937 INSTALL_FAILED_CONFLICTING_PROVIDER, 9938 "Can't install because provider name " + names[j] 9939 + " (in package " + pkg.applicationInfo.packageName 9940 + ") is already used by " + otherPackageName); 9941 } 9942 } 9943 } 9944 } 9945 } 9946 } 9947 } 9948 9949 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9950 int type, String declaringPackageName, int declaringVersionCode) { 9951 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9952 if (versionedLib == null) { 9953 versionedLib = new SparseArray<>(); 9954 mSharedLibraries.put(name, versionedLib); 9955 if (type == SharedLibraryInfo.TYPE_STATIC) { 9956 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9957 } 9958 } else if (versionedLib.indexOfKey(version) >= 0) { 9959 return false; 9960 } 9961 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9962 version, type, declaringPackageName, declaringVersionCode); 9963 versionedLib.put(version, libEntry); 9964 return true; 9965 } 9966 9967 private boolean removeSharedLibraryLPw(String name, int version) { 9968 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9969 if (versionedLib == null) { 9970 return false; 9971 } 9972 final int libIdx = versionedLib.indexOfKey(version); 9973 if (libIdx < 0) { 9974 return false; 9975 } 9976 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9977 versionedLib.remove(version); 9978 if (versionedLib.size() <= 0) { 9979 mSharedLibraries.remove(name); 9980 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9981 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9982 .getPackageName()); 9983 } 9984 } 9985 return true; 9986 } 9987 9988 /** 9989 * Adds a scanned package to the system. When this method is finished, the package will 9990 * be available for query, resolution, etc... 9991 */ 9992 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9993 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9994 final String pkgName = pkg.packageName; 9995 if (mCustomResolverComponentName != null && 9996 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9997 setUpCustomResolverActivity(pkg); 9998 } 9999 10000 if (pkg.packageName.equals("android")) { 10001 synchronized (mPackages) { 10002 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10003 // Set up information for our fall-back user intent resolution activity. 10004 mPlatformPackage = pkg; 10005 pkg.mVersionCode = mSdkVersion; 10006 mAndroidApplication = pkg.applicationInfo; 10007 if (!mResolverReplaced) { 10008 mResolveActivity.applicationInfo = mAndroidApplication; 10009 mResolveActivity.name = ResolverActivity.class.getName(); 10010 mResolveActivity.packageName = mAndroidApplication.packageName; 10011 mResolveActivity.processName = "system:ui"; 10012 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10013 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10014 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10015 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10016 mResolveActivity.exported = true; 10017 mResolveActivity.enabled = true; 10018 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10019 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10020 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10021 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10022 | ActivityInfo.CONFIG_ORIENTATION 10023 | ActivityInfo.CONFIG_KEYBOARD 10024 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10025 mResolveInfo.activityInfo = mResolveActivity; 10026 mResolveInfo.priority = 0; 10027 mResolveInfo.preferredOrder = 0; 10028 mResolveInfo.match = 0; 10029 mResolveComponentName = new ComponentName( 10030 mAndroidApplication.packageName, mResolveActivity.name); 10031 } 10032 } 10033 } 10034 } 10035 10036 ArrayList<PackageParser.Package> clientLibPkgs = null; 10037 // writer 10038 synchronized (mPackages) { 10039 boolean hasStaticSharedLibs = false; 10040 10041 // Any app can add new static shared libraries 10042 if (pkg.staticSharedLibName != null) { 10043 // Static shared libs don't allow renaming as they have synthetic package 10044 // names to allow install of multiple versions, so use name from manifest. 10045 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10046 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10047 pkg.manifestPackageName, pkg.mVersionCode)) { 10048 hasStaticSharedLibs = true; 10049 } else { 10050 Slog.w(TAG, "Package " + pkg.packageName + " library " 10051 + pkg.staticSharedLibName + " already exists; skipping"); 10052 } 10053 // Static shared libs cannot be updated once installed since they 10054 // use synthetic package name which includes the version code, so 10055 // not need to update other packages's shared lib dependencies. 10056 } 10057 10058 if (!hasStaticSharedLibs 10059 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10060 // Only system apps can add new dynamic shared libraries. 10061 if (pkg.libraryNames != null) { 10062 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10063 String name = pkg.libraryNames.get(i); 10064 boolean allowed = false; 10065 if (pkg.isUpdatedSystemApp()) { 10066 // New library entries can only be added through the 10067 // system image. This is important to get rid of a lot 10068 // of nasty edge cases: for example if we allowed a non- 10069 // system update of the app to add a library, then uninstalling 10070 // the update would make the library go away, and assumptions 10071 // we made such as through app install filtering would now 10072 // have allowed apps on the device which aren't compatible 10073 // with it. Better to just have the restriction here, be 10074 // conservative, and create many fewer cases that can negatively 10075 // impact the user experience. 10076 final PackageSetting sysPs = mSettings 10077 .getDisabledSystemPkgLPr(pkg.packageName); 10078 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10079 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10080 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10081 allowed = true; 10082 break; 10083 } 10084 } 10085 } 10086 } else { 10087 allowed = true; 10088 } 10089 if (allowed) { 10090 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10091 SharedLibraryInfo.VERSION_UNDEFINED, 10092 SharedLibraryInfo.TYPE_DYNAMIC, 10093 pkg.packageName, pkg.mVersionCode)) { 10094 Slog.w(TAG, "Package " + pkg.packageName + " library " 10095 + name + " already exists; skipping"); 10096 } 10097 } else { 10098 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10099 + name + " that is not declared on system image; skipping"); 10100 } 10101 } 10102 10103 if ((scanFlags & SCAN_BOOTING) == 0) { 10104 // If we are not booting, we need to update any applications 10105 // that are clients of our shared library. If we are booting, 10106 // this will all be done once the scan is complete. 10107 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10108 } 10109 } 10110 } 10111 } 10112 10113 if ((scanFlags & SCAN_BOOTING) != 0) { 10114 // No apps can run during boot scan, so they don't need to be frozen 10115 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10116 // Caller asked to not kill app, so it's probably not frozen 10117 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10118 // Caller asked us to ignore frozen check for some reason; they 10119 // probably didn't know the package name 10120 } else { 10121 // We're doing major surgery on this package, so it better be frozen 10122 // right now to keep it from launching 10123 checkPackageFrozen(pkgName); 10124 } 10125 10126 // Also need to kill any apps that are dependent on the library. 10127 if (clientLibPkgs != null) { 10128 for (int i=0; i<clientLibPkgs.size(); i++) { 10129 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10130 killApplication(clientPkg.applicationInfo.packageName, 10131 clientPkg.applicationInfo.uid, "update lib"); 10132 } 10133 } 10134 10135 // writer 10136 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10137 10138 synchronized (mPackages) { 10139 // We don't expect installation to fail beyond this point 10140 10141 // Add the new setting to mSettings 10142 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10143 // Add the new setting to mPackages 10144 mPackages.put(pkg.applicationInfo.packageName, pkg); 10145 // Make sure we don't accidentally delete its data. 10146 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10147 while (iter.hasNext()) { 10148 PackageCleanItem item = iter.next(); 10149 if (pkgName.equals(item.packageName)) { 10150 iter.remove(); 10151 } 10152 } 10153 10154 // Add the package's KeySets to the global KeySetManagerService 10155 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10156 ksms.addScannedPackageLPw(pkg); 10157 10158 int N = pkg.providers.size(); 10159 StringBuilder r = null; 10160 int i; 10161 for (i=0; i<N; i++) { 10162 PackageParser.Provider p = pkg.providers.get(i); 10163 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10164 p.info.processName); 10165 mProviders.addProvider(p); 10166 p.syncable = p.info.isSyncable; 10167 if (p.info.authority != null) { 10168 String names[] = p.info.authority.split(";"); 10169 p.info.authority = null; 10170 for (int j = 0; j < names.length; j++) { 10171 if (j == 1 && p.syncable) { 10172 // We only want the first authority for a provider to possibly be 10173 // syncable, so if we already added this provider using a different 10174 // authority clear the syncable flag. We copy the provider before 10175 // changing it because the mProviders object contains a reference 10176 // to a provider that we don't want to change. 10177 // Only do this for the second authority since the resulting provider 10178 // object can be the same for all future authorities for this provider. 10179 p = new PackageParser.Provider(p); 10180 p.syncable = false; 10181 } 10182 if (!mProvidersByAuthority.containsKey(names[j])) { 10183 mProvidersByAuthority.put(names[j], p); 10184 if (p.info.authority == null) { 10185 p.info.authority = names[j]; 10186 } else { 10187 p.info.authority = p.info.authority + ";" + names[j]; 10188 } 10189 if (DEBUG_PACKAGE_SCANNING) { 10190 if (chatty) 10191 Log.d(TAG, "Registered content provider: " + names[j] 10192 + ", className = " + p.info.name + ", isSyncable = " 10193 + p.info.isSyncable); 10194 } 10195 } else { 10196 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10197 Slog.w(TAG, "Skipping provider name " + names[j] + 10198 " (in package " + pkg.applicationInfo.packageName + 10199 "): name already used by " 10200 + ((other != null && other.getComponentName() != null) 10201 ? other.getComponentName().getPackageName() : "?")); 10202 } 10203 } 10204 } 10205 if (chatty) { 10206 if (r == null) { 10207 r = new StringBuilder(256); 10208 } else { 10209 r.append(' '); 10210 } 10211 r.append(p.info.name); 10212 } 10213 } 10214 if (r != null) { 10215 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10216 } 10217 10218 N = pkg.services.size(); 10219 r = null; 10220 for (i=0; i<N; i++) { 10221 PackageParser.Service s = pkg.services.get(i); 10222 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10223 s.info.processName); 10224 mServices.addService(s); 10225 if (chatty) { 10226 if (r == null) { 10227 r = new StringBuilder(256); 10228 } else { 10229 r.append(' '); 10230 } 10231 r.append(s.info.name); 10232 } 10233 } 10234 if (r != null) { 10235 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10236 } 10237 10238 N = pkg.receivers.size(); 10239 r = null; 10240 for (i=0; i<N; i++) { 10241 PackageParser.Activity a = pkg.receivers.get(i); 10242 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10243 a.info.processName); 10244 mReceivers.addActivity(a, "receiver"); 10245 if (chatty) { 10246 if (r == null) { 10247 r = new StringBuilder(256); 10248 } else { 10249 r.append(' '); 10250 } 10251 r.append(a.info.name); 10252 } 10253 } 10254 if (r != null) { 10255 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10256 } 10257 10258 N = pkg.activities.size(); 10259 r = null; 10260 for (i=0; i<N; i++) { 10261 PackageParser.Activity a = pkg.activities.get(i); 10262 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10263 a.info.processName); 10264 mActivities.addActivity(a, "activity"); 10265 if (chatty) { 10266 if (r == null) { 10267 r = new StringBuilder(256); 10268 } else { 10269 r.append(' '); 10270 } 10271 r.append(a.info.name); 10272 } 10273 } 10274 if (r != null) { 10275 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10276 } 10277 10278 N = pkg.permissionGroups.size(); 10279 r = null; 10280 for (i=0; i<N; i++) { 10281 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10282 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10283 final String curPackageName = cur == null ? null : cur.info.packageName; 10284 // Dont allow ephemeral apps to define new permission groups. 10285 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10286 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10287 + pg.info.packageName 10288 + " ignored: instant apps cannot define new permission groups."); 10289 continue; 10290 } 10291 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10292 if (cur == null || isPackageUpdate) { 10293 mPermissionGroups.put(pg.info.name, pg); 10294 if (chatty) { 10295 if (r == null) { 10296 r = new StringBuilder(256); 10297 } else { 10298 r.append(' '); 10299 } 10300 if (isPackageUpdate) { 10301 r.append("UPD:"); 10302 } 10303 r.append(pg.info.name); 10304 } 10305 } else { 10306 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10307 + pg.info.packageName + " ignored: original from " 10308 + cur.info.packageName); 10309 if (chatty) { 10310 if (r == null) { 10311 r = new StringBuilder(256); 10312 } else { 10313 r.append(' '); 10314 } 10315 r.append("DUP:"); 10316 r.append(pg.info.name); 10317 } 10318 } 10319 } 10320 if (r != null) { 10321 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10322 } 10323 10324 N = pkg.permissions.size(); 10325 r = null; 10326 for (i=0; i<N; i++) { 10327 PackageParser.Permission p = pkg.permissions.get(i); 10328 10329 // Dont allow ephemeral apps to define new permissions. 10330 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10331 Slog.w(TAG, "Permission " + p.info.name + " from package " 10332 + p.info.packageName 10333 + " ignored: instant apps cannot define new permissions."); 10334 continue; 10335 } 10336 10337 // Assume by default that we did not install this permission into the system. 10338 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10339 10340 // Now that permission groups have a special meaning, we ignore permission 10341 // groups for legacy apps to prevent unexpected behavior. In particular, 10342 // permissions for one app being granted to someone just becase they happen 10343 // to be in a group defined by another app (before this had no implications). 10344 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10345 p.group = mPermissionGroups.get(p.info.group); 10346 // Warn for a permission in an unknown group. 10347 if (p.info.group != null && p.group == null) { 10348 Slog.w(TAG, "Permission " + p.info.name + " from package " 10349 + p.info.packageName + " in an unknown group " + p.info.group); 10350 } 10351 } 10352 10353 ArrayMap<String, BasePermission> permissionMap = 10354 p.tree ? mSettings.mPermissionTrees 10355 : mSettings.mPermissions; 10356 BasePermission bp = permissionMap.get(p.info.name); 10357 10358 // Allow system apps to redefine non-system permissions 10359 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10360 final boolean currentOwnerIsSystem = (bp.perm != null 10361 && isSystemApp(bp.perm.owner)); 10362 if (isSystemApp(p.owner)) { 10363 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10364 // It's a built-in permission and no owner, take ownership now 10365 bp.packageSetting = pkgSetting; 10366 bp.perm = p; 10367 bp.uid = pkg.applicationInfo.uid; 10368 bp.sourcePackage = p.info.packageName; 10369 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10370 } else if (!currentOwnerIsSystem) { 10371 String msg = "New decl " + p.owner + " of permission " 10372 + p.info.name + " is system; overriding " + bp.sourcePackage; 10373 reportSettingsProblem(Log.WARN, msg); 10374 bp = null; 10375 } 10376 } 10377 } 10378 10379 if (bp == null) { 10380 bp = new BasePermission(p.info.name, p.info.packageName, 10381 BasePermission.TYPE_NORMAL); 10382 permissionMap.put(p.info.name, bp); 10383 } 10384 10385 if (bp.perm == null) { 10386 if (bp.sourcePackage == null 10387 || bp.sourcePackage.equals(p.info.packageName)) { 10388 BasePermission tree = findPermissionTreeLP(p.info.name); 10389 if (tree == null 10390 || tree.sourcePackage.equals(p.info.packageName)) { 10391 bp.packageSetting = pkgSetting; 10392 bp.perm = p; 10393 bp.uid = pkg.applicationInfo.uid; 10394 bp.sourcePackage = p.info.packageName; 10395 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10396 if (chatty) { 10397 if (r == null) { 10398 r = new StringBuilder(256); 10399 } else { 10400 r.append(' '); 10401 } 10402 r.append(p.info.name); 10403 } 10404 } else { 10405 Slog.w(TAG, "Permission " + p.info.name + " from package " 10406 + p.info.packageName + " ignored: base tree " 10407 + tree.name + " is from package " 10408 + tree.sourcePackage); 10409 } 10410 } else { 10411 Slog.w(TAG, "Permission " + p.info.name + " from package " 10412 + p.info.packageName + " ignored: original from " 10413 + bp.sourcePackage); 10414 } 10415 } else if (chatty) { 10416 if (r == null) { 10417 r = new StringBuilder(256); 10418 } else { 10419 r.append(' '); 10420 } 10421 r.append("DUP:"); 10422 r.append(p.info.name); 10423 } 10424 if (bp.perm == p) { 10425 bp.protectionLevel = p.info.protectionLevel; 10426 } 10427 } 10428 10429 if (r != null) { 10430 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10431 } 10432 10433 N = pkg.instrumentation.size(); 10434 r = null; 10435 for (i=0; i<N; i++) { 10436 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10437 a.info.packageName = pkg.applicationInfo.packageName; 10438 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10439 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10440 a.info.splitNames = pkg.splitNames; 10441 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10442 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10443 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10444 a.info.dataDir = pkg.applicationInfo.dataDir; 10445 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10446 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10447 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10448 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10449 mInstrumentation.put(a.getComponentName(), a); 10450 if (chatty) { 10451 if (r == null) { 10452 r = new StringBuilder(256); 10453 } else { 10454 r.append(' '); 10455 } 10456 r.append(a.info.name); 10457 } 10458 } 10459 if (r != null) { 10460 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10461 } 10462 10463 if (pkg.protectedBroadcasts != null) { 10464 N = pkg.protectedBroadcasts.size(); 10465 for (i=0; i<N; i++) { 10466 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10467 } 10468 } 10469 } 10470 10471 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10472 } 10473 10474 /** 10475 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10476 * is derived purely on the basis of the contents of {@code scanFile} and 10477 * {@code cpuAbiOverride}. 10478 * 10479 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10480 */ 10481 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10482 String cpuAbiOverride, boolean extractLibs, 10483 File appLib32InstallDir) 10484 throws PackageManagerException { 10485 // Give ourselves some initial paths; we'll come back for another 10486 // pass once we've determined ABI below. 10487 setNativeLibraryPaths(pkg, appLib32InstallDir); 10488 10489 // We would never need to extract libs for forward-locked and external packages, 10490 // since the container service will do it for us. We shouldn't attempt to 10491 // extract libs from system app when it was not updated. 10492 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10493 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10494 extractLibs = false; 10495 } 10496 10497 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10498 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10499 10500 NativeLibraryHelper.Handle handle = null; 10501 try { 10502 handle = NativeLibraryHelper.Handle.create(pkg); 10503 // TODO(multiArch): This can be null for apps that didn't go through the 10504 // usual installation process. We can calculate it again, like we 10505 // do during install time. 10506 // 10507 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10508 // unnecessary. 10509 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10510 10511 // Null out the abis so that they can be recalculated. 10512 pkg.applicationInfo.primaryCpuAbi = null; 10513 pkg.applicationInfo.secondaryCpuAbi = null; 10514 if (isMultiArch(pkg.applicationInfo)) { 10515 // Warn if we've set an abiOverride for multi-lib packages.. 10516 // By definition, we need to copy both 32 and 64 bit libraries for 10517 // such packages. 10518 if (pkg.cpuAbiOverride != null 10519 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10520 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10521 } 10522 10523 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10524 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10525 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10526 if (extractLibs) { 10527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10528 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10529 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10530 useIsaSpecificSubdirs); 10531 } else { 10532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10533 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10534 } 10535 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10536 } 10537 10538 maybeThrowExceptionForMultiArchCopy( 10539 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10540 10541 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10542 if (extractLibs) { 10543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10544 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10545 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10546 useIsaSpecificSubdirs); 10547 } else { 10548 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10549 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10550 } 10551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10552 } 10553 10554 maybeThrowExceptionForMultiArchCopy( 10555 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10556 10557 if (abi64 >= 0) { 10558 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10559 } 10560 10561 if (abi32 >= 0) { 10562 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10563 if (abi64 >= 0) { 10564 if (pkg.use32bitAbi) { 10565 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10566 pkg.applicationInfo.primaryCpuAbi = abi; 10567 } else { 10568 pkg.applicationInfo.secondaryCpuAbi = abi; 10569 } 10570 } else { 10571 pkg.applicationInfo.primaryCpuAbi = abi; 10572 } 10573 } 10574 10575 } else { 10576 String[] abiList = (cpuAbiOverride != null) ? 10577 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10578 10579 // Enable gross and lame hacks for apps that are built with old 10580 // SDK tools. We must scan their APKs for renderscript bitcode and 10581 // not launch them if it's present. Don't bother checking on devices 10582 // that don't have 64 bit support. 10583 boolean needsRenderScriptOverride = false; 10584 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10585 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10586 abiList = Build.SUPPORTED_32_BIT_ABIS; 10587 needsRenderScriptOverride = true; 10588 } 10589 10590 final int copyRet; 10591 if (extractLibs) { 10592 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10593 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10594 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10595 } else { 10596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10597 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10598 } 10599 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10600 10601 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10602 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10603 "Error unpackaging native libs for app, errorCode=" + copyRet); 10604 } 10605 10606 if (copyRet >= 0) { 10607 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10608 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10609 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10610 } else if (needsRenderScriptOverride) { 10611 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10612 } 10613 } 10614 } catch (IOException ioe) { 10615 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10616 } finally { 10617 IoUtils.closeQuietly(handle); 10618 } 10619 10620 // Now that we've calculated the ABIs and determined if it's an internal app, 10621 // we will go ahead and populate the nativeLibraryPath. 10622 setNativeLibraryPaths(pkg, appLib32InstallDir); 10623 } 10624 10625 /** 10626 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10627 * i.e, so that all packages can be run inside a single process if required. 10628 * 10629 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10630 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10631 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10632 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10633 * updating a package that belongs to a shared user. 10634 * 10635 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10636 * adds unnecessary complexity. 10637 */ 10638 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10639 PackageParser.Package scannedPackage) { 10640 String requiredInstructionSet = null; 10641 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10642 requiredInstructionSet = VMRuntime.getInstructionSet( 10643 scannedPackage.applicationInfo.primaryCpuAbi); 10644 } 10645 10646 PackageSetting requirer = null; 10647 for (PackageSetting ps : packagesForUser) { 10648 // If packagesForUser contains scannedPackage, we skip it. This will happen 10649 // when scannedPackage is an update of an existing package. Without this check, 10650 // we will never be able to change the ABI of any package belonging to a shared 10651 // user, even if it's compatible with other packages. 10652 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10653 if (ps.primaryCpuAbiString == null) { 10654 continue; 10655 } 10656 10657 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10658 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10659 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10660 // this but there's not much we can do. 10661 String errorMessage = "Instruction set mismatch, " 10662 + ((requirer == null) ? "[caller]" : requirer) 10663 + " requires " + requiredInstructionSet + " whereas " + ps 10664 + " requires " + instructionSet; 10665 Slog.w(TAG, errorMessage); 10666 } 10667 10668 if (requiredInstructionSet == null) { 10669 requiredInstructionSet = instructionSet; 10670 requirer = ps; 10671 } 10672 } 10673 } 10674 10675 if (requiredInstructionSet != null) { 10676 String adjustedAbi; 10677 if (requirer != null) { 10678 // requirer != null implies that either scannedPackage was null or that scannedPackage 10679 // did not require an ABI, in which case we have to adjust scannedPackage to match 10680 // the ABI of the set (which is the same as requirer's ABI) 10681 adjustedAbi = requirer.primaryCpuAbiString; 10682 if (scannedPackage != null) { 10683 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10684 } 10685 } else { 10686 // requirer == null implies that we're updating all ABIs in the set to 10687 // match scannedPackage. 10688 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10689 } 10690 10691 for (PackageSetting ps : packagesForUser) { 10692 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10693 if (ps.primaryCpuAbiString != null) { 10694 continue; 10695 } 10696 10697 ps.primaryCpuAbiString = adjustedAbi; 10698 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10699 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10700 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10701 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10702 + " (requirer=" 10703 + (requirer != null ? requirer.pkg : "null") 10704 + ", scannedPackage=" 10705 + (scannedPackage != null ? scannedPackage : "null") 10706 + ")"); 10707 try { 10708 mInstaller.rmdex(ps.codePathString, 10709 getDexCodeInstructionSet(getPreferredInstructionSet())); 10710 } catch (InstallerException ignored) { 10711 } 10712 } 10713 } 10714 } 10715 } 10716 } 10717 10718 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10719 synchronized (mPackages) { 10720 mResolverReplaced = true; 10721 // Set up information for custom user intent resolution activity. 10722 mResolveActivity.applicationInfo = pkg.applicationInfo; 10723 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10724 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10725 mResolveActivity.processName = pkg.applicationInfo.packageName; 10726 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10727 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10728 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10729 mResolveActivity.theme = 0; 10730 mResolveActivity.exported = true; 10731 mResolveActivity.enabled = true; 10732 mResolveInfo.activityInfo = mResolveActivity; 10733 mResolveInfo.priority = 0; 10734 mResolveInfo.preferredOrder = 0; 10735 mResolveInfo.match = 0; 10736 mResolveComponentName = mCustomResolverComponentName; 10737 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10738 mResolveComponentName); 10739 } 10740 } 10741 10742 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10743 if (installerActivity == null) { 10744 if (DEBUG_EPHEMERAL) { 10745 Slog.d(TAG, "Clear ephemeral installer activity"); 10746 } 10747 mInstantAppInstallerActivity = null; 10748 return; 10749 } 10750 10751 if (DEBUG_EPHEMERAL) { 10752 Slog.d(TAG, "Set ephemeral installer activity: " 10753 + installerActivity.getComponentName()); 10754 } 10755 // Set up information for ephemeral installer activity 10756 mInstantAppInstallerActivity = installerActivity; 10757 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10758 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10759 mInstantAppInstallerActivity.exported = true; 10760 mInstantAppInstallerActivity.enabled = true; 10761 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10762 mInstantAppInstallerInfo.priority = 0; 10763 mInstantAppInstallerInfo.preferredOrder = 1; 10764 mInstantAppInstallerInfo.isDefault = true; 10765 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10766 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10767 } 10768 10769 private static String calculateBundledApkRoot(final String codePathString) { 10770 final File codePath = new File(codePathString); 10771 final File codeRoot; 10772 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10773 codeRoot = Environment.getRootDirectory(); 10774 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10775 codeRoot = Environment.getOemDirectory(); 10776 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10777 codeRoot = Environment.getVendorDirectory(); 10778 } else { 10779 // Unrecognized code path; take its top real segment as the apk root: 10780 // e.g. /something/app/blah.apk => /something 10781 try { 10782 File f = codePath.getCanonicalFile(); 10783 File parent = f.getParentFile(); // non-null because codePath is a file 10784 File tmp; 10785 while ((tmp = parent.getParentFile()) != null) { 10786 f = parent; 10787 parent = tmp; 10788 } 10789 codeRoot = f; 10790 Slog.w(TAG, "Unrecognized code path " 10791 + codePath + " - using " + codeRoot); 10792 } catch (IOException e) { 10793 // Can't canonicalize the code path -- shenanigans? 10794 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10795 return Environment.getRootDirectory().getPath(); 10796 } 10797 } 10798 return codeRoot.getPath(); 10799 } 10800 10801 /** 10802 * Derive and set the location of native libraries for the given package, 10803 * which varies depending on where and how the package was installed. 10804 */ 10805 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10806 final ApplicationInfo info = pkg.applicationInfo; 10807 final String codePath = pkg.codePath; 10808 final File codeFile = new File(codePath); 10809 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10810 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10811 10812 info.nativeLibraryRootDir = null; 10813 info.nativeLibraryRootRequiresIsa = false; 10814 info.nativeLibraryDir = null; 10815 info.secondaryNativeLibraryDir = null; 10816 10817 if (isApkFile(codeFile)) { 10818 // Monolithic install 10819 if (bundledApp) { 10820 // If "/system/lib64/apkname" exists, assume that is the per-package 10821 // native library directory to use; otherwise use "/system/lib/apkname". 10822 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10823 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10824 getPrimaryInstructionSet(info)); 10825 10826 // This is a bundled system app so choose the path based on the ABI. 10827 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10828 // is just the default path. 10829 final String apkName = deriveCodePathName(codePath); 10830 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10831 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10832 apkName).getAbsolutePath(); 10833 10834 if (info.secondaryCpuAbi != null) { 10835 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10836 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10837 secondaryLibDir, apkName).getAbsolutePath(); 10838 } 10839 } else if (asecApp) { 10840 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10841 .getAbsolutePath(); 10842 } else { 10843 final String apkName = deriveCodePathName(codePath); 10844 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10845 .getAbsolutePath(); 10846 } 10847 10848 info.nativeLibraryRootRequiresIsa = false; 10849 info.nativeLibraryDir = info.nativeLibraryRootDir; 10850 } else { 10851 // Cluster install 10852 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10853 info.nativeLibraryRootRequiresIsa = true; 10854 10855 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10856 getPrimaryInstructionSet(info)).getAbsolutePath(); 10857 10858 if (info.secondaryCpuAbi != null) { 10859 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10860 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10861 } 10862 } 10863 } 10864 10865 /** 10866 * Calculate the abis and roots for a bundled app. These can uniquely 10867 * be determined from the contents of the system partition, i.e whether 10868 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10869 * of this information, and instead assume that the system was built 10870 * sensibly. 10871 */ 10872 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10873 PackageSetting pkgSetting) { 10874 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10875 10876 // If "/system/lib64/apkname" exists, assume that is the per-package 10877 // native library directory to use; otherwise use "/system/lib/apkname". 10878 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10879 setBundledAppAbi(pkg, apkRoot, apkName); 10880 // pkgSetting might be null during rescan following uninstall of updates 10881 // to a bundled app, so accommodate that possibility. The settings in 10882 // that case will be established later from the parsed package. 10883 // 10884 // If the settings aren't null, sync them up with what we've just derived. 10885 // note that apkRoot isn't stored in the package settings. 10886 if (pkgSetting != null) { 10887 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10888 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10889 } 10890 } 10891 10892 /** 10893 * Deduces the ABI of a bundled app and sets the relevant fields on the 10894 * parsed pkg object. 10895 * 10896 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10897 * under which system libraries are installed. 10898 * @param apkName the name of the installed package. 10899 */ 10900 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10901 final File codeFile = new File(pkg.codePath); 10902 10903 final boolean has64BitLibs; 10904 final boolean has32BitLibs; 10905 if (isApkFile(codeFile)) { 10906 // Monolithic install 10907 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10908 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10909 } else { 10910 // Cluster install 10911 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10912 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10913 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10914 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10915 has64BitLibs = (new File(rootDir, isa)).exists(); 10916 } else { 10917 has64BitLibs = false; 10918 } 10919 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10920 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10921 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10922 has32BitLibs = (new File(rootDir, isa)).exists(); 10923 } else { 10924 has32BitLibs = false; 10925 } 10926 } 10927 10928 if (has64BitLibs && !has32BitLibs) { 10929 // The package has 64 bit libs, but not 32 bit libs. Its primary 10930 // ABI should be 64 bit. We can safely assume here that the bundled 10931 // native libraries correspond to the most preferred ABI in the list. 10932 10933 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10934 pkg.applicationInfo.secondaryCpuAbi = null; 10935 } else if (has32BitLibs && !has64BitLibs) { 10936 // The package has 32 bit libs but not 64 bit libs. Its primary 10937 // ABI should be 32 bit. 10938 10939 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10940 pkg.applicationInfo.secondaryCpuAbi = null; 10941 } else if (has32BitLibs && has64BitLibs) { 10942 // The application has both 64 and 32 bit bundled libraries. We check 10943 // here that the app declares multiArch support, and warn if it doesn't. 10944 // 10945 // We will be lenient here and record both ABIs. The primary will be the 10946 // ABI that's higher on the list, i.e, a device that's configured to prefer 10947 // 64 bit apps will see a 64 bit primary ABI, 10948 10949 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10950 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10951 } 10952 10953 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10954 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10955 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10956 } else { 10957 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10958 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10959 } 10960 } else { 10961 pkg.applicationInfo.primaryCpuAbi = null; 10962 pkg.applicationInfo.secondaryCpuAbi = null; 10963 } 10964 } 10965 10966 private void killApplication(String pkgName, int appId, String reason) { 10967 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10968 } 10969 10970 private void killApplication(String pkgName, int appId, int userId, String reason) { 10971 // Request the ActivityManager to kill the process(only for existing packages) 10972 // so that we do not end up in a confused state while the user is still using the older 10973 // version of the application while the new one gets installed. 10974 final long token = Binder.clearCallingIdentity(); 10975 try { 10976 IActivityManager am = ActivityManager.getService(); 10977 if (am != null) { 10978 try { 10979 am.killApplication(pkgName, appId, userId, reason); 10980 } catch (RemoteException e) { 10981 } 10982 } 10983 } finally { 10984 Binder.restoreCallingIdentity(token); 10985 } 10986 } 10987 10988 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10989 // Remove the parent package setting 10990 PackageSetting ps = (PackageSetting) pkg.mExtras; 10991 if (ps != null) { 10992 removePackageLI(ps, chatty); 10993 } 10994 // Remove the child package setting 10995 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10996 for (int i = 0; i < childCount; i++) { 10997 PackageParser.Package childPkg = pkg.childPackages.get(i); 10998 ps = (PackageSetting) childPkg.mExtras; 10999 if (ps != null) { 11000 removePackageLI(ps, chatty); 11001 } 11002 } 11003 } 11004 11005 void removePackageLI(PackageSetting ps, boolean chatty) { 11006 if (DEBUG_INSTALL) { 11007 if (chatty) 11008 Log.d(TAG, "Removing package " + ps.name); 11009 } 11010 11011 // writer 11012 synchronized (mPackages) { 11013 mPackages.remove(ps.name); 11014 final PackageParser.Package pkg = ps.pkg; 11015 if (pkg != null) { 11016 cleanPackageDataStructuresLILPw(pkg, chatty); 11017 } 11018 } 11019 } 11020 11021 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11022 if (DEBUG_INSTALL) { 11023 if (chatty) 11024 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11025 } 11026 11027 // writer 11028 synchronized (mPackages) { 11029 // Remove the parent package 11030 mPackages.remove(pkg.applicationInfo.packageName); 11031 cleanPackageDataStructuresLILPw(pkg, chatty); 11032 11033 // Remove the child packages 11034 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11035 for (int i = 0; i < childCount; i++) { 11036 PackageParser.Package childPkg = pkg.childPackages.get(i); 11037 mPackages.remove(childPkg.applicationInfo.packageName); 11038 cleanPackageDataStructuresLILPw(childPkg, chatty); 11039 } 11040 } 11041 } 11042 11043 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11044 int N = pkg.providers.size(); 11045 StringBuilder r = null; 11046 int i; 11047 for (i=0; i<N; i++) { 11048 PackageParser.Provider p = pkg.providers.get(i); 11049 mProviders.removeProvider(p); 11050 if (p.info.authority == null) { 11051 11052 /* There was another ContentProvider with this authority when 11053 * this app was installed so this authority is null, 11054 * Ignore it as we don't have to unregister the provider. 11055 */ 11056 continue; 11057 } 11058 String names[] = p.info.authority.split(";"); 11059 for (int j = 0; j < names.length; j++) { 11060 if (mProvidersByAuthority.get(names[j]) == p) { 11061 mProvidersByAuthority.remove(names[j]); 11062 if (DEBUG_REMOVE) { 11063 if (chatty) 11064 Log.d(TAG, "Unregistered content provider: " + names[j] 11065 + ", className = " + p.info.name + ", isSyncable = " 11066 + p.info.isSyncable); 11067 } 11068 } 11069 } 11070 if (DEBUG_REMOVE && chatty) { 11071 if (r == null) { 11072 r = new StringBuilder(256); 11073 } else { 11074 r.append(' '); 11075 } 11076 r.append(p.info.name); 11077 } 11078 } 11079 if (r != null) { 11080 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11081 } 11082 11083 N = pkg.services.size(); 11084 r = null; 11085 for (i=0; i<N; i++) { 11086 PackageParser.Service s = pkg.services.get(i); 11087 mServices.removeService(s); 11088 if (chatty) { 11089 if (r == null) { 11090 r = new StringBuilder(256); 11091 } else { 11092 r.append(' '); 11093 } 11094 r.append(s.info.name); 11095 } 11096 } 11097 if (r != null) { 11098 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11099 } 11100 11101 N = pkg.receivers.size(); 11102 r = null; 11103 for (i=0; i<N; i++) { 11104 PackageParser.Activity a = pkg.receivers.get(i); 11105 mReceivers.removeActivity(a, "receiver"); 11106 if (DEBUG_REMOVE && chatty) { 11107 if (r == null) { 11108 r = new StringBuilder(256); 11109 } else { 11110 r.append(' '); 11111 } 11112 r.append(a.info.name); 11113 } 11114 } 11115 if (r != null) { 11116 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11117 } 11118 11119 N = pkg.activities.size(); 11120 r = null; 11121 for (i=0; i<N; i++) { 11122 PackageParser.Activity a = pkg.activities.get(i); 11123 mActivities.removeActivity(a, "activity"); 11124 if (DEBUG_REMOVE && chatty) { 11125 if (r == null) { 11126 r = new StringBuilder(256); 11127 } else { 11128 r.append(' '); 11129 } 11130 r.append(a.info.name); 11131 } 11132 } 11133 if (r != null) { 11134 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11135 } 11136 11137 N = pkg.permissions.size(); 11138 r = null; 11139 for (i=0; i<N; i++) { 11140 PackageParser.Permission p = pkg.permissions.get(i); 11141 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11142 if (bp == null) { 11143 bp = mSettings.mPermissionTrees.get(p.info.name); 11144 } 11145 if (bp != null && bp.perm == p) { 11146 bp.perm = null; 11147 if (DEBUG_REMOVE && chatty) { 11148 if (r == null) { 11149 r = new StringBuilder(256); 11150 } else { 11151 r.append(' '); 11152 } 11153 r.append(p.info.name); 11154 } 11155 } 11156 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11157 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11158 if (appOpPkgs != null) { 11159 appOpPkgs.remove(pkg.packageName); 11160 } 11161 } 11162 } 11163 if (r != null) { 11164 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11165 } 11166 11167 N = pkg.requestedPermissions.size(); 11168 r = null; 11169 for (i=0; i<N; i++) { 11170 String perm = pkg.requestedPermissions.get(i); 11171 BasePermission bp = mSettings.mPermissions.get(perm); 11172 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11173 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11174 if (appOpPkgs != null) { 11175 appOpPkgs.remove(pkg.packageName); 11176 if (appOpPkgs.isEmpty()) { 11177 mAppOpPermissionPackages.remove(perm); 11178 } 11179 } 11180 } 11181 } 11182 if (r != null) { 11183 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11184 } 11185 11186 N = pkg.instrumentation.size(); 11187 r = null; 11188 for (i=0; i<N; i++) { 11189 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11190 mInstrumentation.remove(a.getComponentName()); 11191 if (DEBUG_REMOVE && chatty) { 11192 if (r == null) { 11193 r = new StringBuilder(256); 11194 } else { 11195 r.append(' '); 11196 } 11197 r.append(a.info.name); 11198 } 11199 } 11200 if (r != null) { 11201 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11202 } 11203 11204 r = null; 11205 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11206 // Only system apps can hold shared libraries. 11207 if (pkg.libraryNames != null) { 11208 for (i = 0; i < pkg.libraryNames.size(); i++) { 11209 String name = pkg.libraryNames.get(i); 11210 if (removeSharedLibraryLPw(name, 0)) { 11211 if (DEBUG_REMOVE && chatty) { 11212 if (r == null) { 11213 r = new StringBuilder(256); 11214 } else { 11215 r.append(' '); 11216 } 11217 r.append(name); 11218 } 11219 } 11220 } 11221 } 11222 } 11223 11224 r = null; 11225 11226 // Any package can hold static shared libraries. 11227 if (pkg.staticSharedLibName != null) { 11228 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11229 if (DEBUG_REMOVE && chatty) { 11230 if (r == null) { 11231 r = new StringBuilder(256); 11232 } else { 11233 r.append(' '); 11234 } 11235 r.append(pkg.staticSharedLibName); 11236 } 11237 } 11238 } 11239 11240 if (r != null) { 11241 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11242 } 11243 } 11244 11245 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11246 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11247 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11248 return true; 11249 } 11250 } 11251 return false; 11252 } 11253 11254 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11255 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11256 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11257 11258 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11259 // Update the parent permissions 11260 updatePermissionsLPw(pkg.packageName, pkg, flags); 11261 // Update the child permissions 11262 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11263 for (int i = 0; i < childCount; i++) { 11264 PackageParser.Package childPkg = pkg.childPackages.get(i); 11265 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11266 } 11267 } 11268 11269 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11270 int flags) { 11271 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11272 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11273 } 11274 11275 private void updatePermissionsLPw(String changingPkg, 11276 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11277 // Make sure there are no dangling permission trees. 11278 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11279 while (it.hasNext()) { 11280 final BasePermission bp = it.next(); 11281 if (bp.packageSetting == null) { 11282 // We may not yet have parsed the package, so just see if 11283 // we still know about its settings. 11284 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11285 } 11286 if (bp.packageSetting == null) { 11287 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11288 + " from package " + bp.sourcePackage); 11289 it.remove(); 11290 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11291 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11292 Slog.i(TAG, "Removing old permission tree: " + bp.name 11293 + " from package " + bp.sourcePackage); 11294 flags |= UPDATE_PERMISSIONS_ALL; 11295 it.remove(); 11296 } 11297 } 11298 } 11299 11300 // Make sure all dynamic permissions have been assigned to a package, 11301 // and make sure there are no dangling permissions. 11302 it = mSettings.mPermissions.values().iterator(); 11303 while (it.hasNext()) { 11304 final BasePermission bp = it.next(); 11305 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11306 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11307 + bp.name + " pkg=" + bp.sourcePackage 11308 + " info=" + bp.pendingInfo); 11309 if (bp.packageSetting == null && bp.pendingInfo != null) { 11310 final BasePermission tree = findPermissionTreeLP(bp.name); 11311 if (tree != null && tree.perm != null) { 11312 bp.packageSetting = tree.packageSetting; 11313 bp.perm = new PackageParser.Permission(tree.perm.owner, 11314 new PermissionInfo(bp.pendingInfo)); 11315 bp.perm.info.packageName = tree.perm.info.packageName; 11316 bp.perm.info.name = bp.name; 11317 bp.uid = tree.uid; 11318 } 11319 } 11320 } 11321 if (bp.packageSetting == null) { 11322 // We may not yet have parsed the package, so just see if 11323 // we still know about its settings. 11324 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11325 } 11326 if (bp.packageSetting == null) { 11327 Slog.w(TAG, "Removing dangling permission: " + bp.name 11328 + " from package " + bp.sourcePackage); 11329 it.remove(); 11330 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11331 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11332 Slog.i(TAG, "Removing old permission: " + bp.name 11333 + " from package " + bp.sourcePackage); 11334 flags |= UPDATE_PERMISSIONS_ALL; 11335 it.remove(); 11336 } 11337 } 11338 } 11339 11340 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11341 // Now update the permissions for all packages, in particular 11342 // replace the granted permissions of the system packages. 11343 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11344 for (PackageParser.Package pkg : mPackages.values()) { 11345 if (pkg != pkgInfo) { 11346 // Only replace for packages on requested volume 11347 final String volumeUuid = getVolumeUuidForPackage(pkg); 11348 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11349 && Objects.equals(replaceVolumeUuid, volumeUuid); 11350 grantPermissionsLPw(pkg, replace, changingPkg); 11351 } 11352 } 11353 } 11354 11355 if (pkgInfo != null) { 11356 // Only replace for packages on requested volume 11357 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11358 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11359 && Objects.equals(replaceVolumeUuid, volumeUuid); 11360 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11361 } 11362 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11363 } 11364 11365 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11366 String packageOfInterest) { 11367 // IMPORTANT: There are two types of permissions: install and runtime. 11368 // Install time permissions are granted when the app is installed to 11369 // all device users and users added in the future. Runtime permissions 11370 // are granted at runtime explicitly to specific users. Normal and signature 11371 // protected permissions are install time permissions. Dangerous permissions 11372 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11373 // otherwise they are runtime permissions. This function does not manage 11374 // runtime permissions except for the case an app targeting Lollipop MR1 11375 // being upgraded to target a newer SDK, in which case dangerous permissions 11376 // are transformed from install time to runtime ones. 11377 11378 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11379 if (ps == null) { 11380 return; 11381 } 11382 11383 PermissionsState permissionsState = ps.getPermissionsState(); 11384 PermissionsState origPermissions = permissionsState; 11385 11386 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11387 11388 boolean runtimePermissionsRevoked = false; 11389 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11390 11391 boolean changedInstallPermission = false; 11392 11393 if (replace) { 11394 ps.installPermissionsFixed = false; 11395 if (!ps.isSharedUser()) { 11396 origPermissions = new PermissionsState(permissionsState); 11397 permissionsState.reset(); 11398 } else { 11399 // We need to know only about runtime permission changes since the 11400 // calling code always writes the install permissions state but 11401 // the runtime ones are written only if changed. The only cases of 11402 // changed runtime permissions here are promotion of an install to 11403 // runtime and revocation of a runtime from a shared user. 11404 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11405 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11406 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11407 runtimePermissionsRevoked = true; 11408 } 11409 } 11410 } 11411 11412 permissionsState.setGlobalGids(mGlobalGids); 11413 11414 final int N = pkg.requestedPermissions.size(); 11415 for (int i=0; i<N; i++) { 11416 final String name = pkg.requestedPermissions.get(i); 11417 final BasePermission bp = mSettings.mPermissions.get(name); 11418 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11419 >= Build.VERSION_CODES.M; 11420 11421 if (DEBUG_INSTALL) { 11422 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11423 } 11424 11425 if (bp == null || bp.packageSetting == null) { 11426 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11427 Slog.w(TAG, "Unknown permission " + name 11428 + " in package " + pkg.packageName); 11429 } 11430 continue; 11431 } 11432 11433 11434 // Limit ephemeral apps to ephemeral allowed permissions. 11435 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11436 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11437 + pkg.packageName); 11438 continue; 11439 } 11440 11441 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 11442 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 11443 + pkg.packageName); 11444 continue; 11445 } 11446 11447 final String perm = bp.name; 11448 boolean allowedSig = false; 11449 int grant = GRANT_DENIED; 11450 11451 // Keep track of app op permissions. 11452 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11453 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11454 if (pkgs == null) { 11455 pkgs = new ArraySet<>(); 11456 mAppOpPermissionPackages.put(bp.name, pkgs); 11457 } 11458 pkgs.add(pkg.packageName); 11459 } 11460 11461 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11462 switch (level) { 11463 case PermissionInfo.PROTECTION_NORMAL: { 11464 // For all apps normal permissions are install time ones. 11465 grant = GRANT_INSTALL; 11466 } break; 11467 11468 case PermissionInfo.PROTECTION_DANGEROUS: { 11469 // If a permission review is required for legacy apps we represent 11470 // their permissions as always granted runtime ones since we need 11471 // to keep the review required permission flag per user while an 11472 // install permission's state is shared across all users. 11473 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11474 // For legacy apps dangerous permissions are install time ones. 11475 grant = GRANT_INSTALL; 11476 } else if (origPermissions.hasInstallPermission(bp.name)) { 11477 // For legacy apps that became modern, install becomes runtime. 11478 grant = GRANT_UPGRADE; 11479 } else if (mPromoteSystemApps 11480 && isSystemApp(ps) 11481 && mExistingSystemPackages.contains(ps.name)) { 11482 // For legacy system apps, install becomes runtime. 11483 // We cannot check hasInstallPermission() for system apps since those 11484 // permissions were granted implicitly and not persisted pre-M. 11485 grant = GRANT_UPGRADE; 11486 } else { 11487 // For modern apps keep runtime permissions unchanged. 11488 grant = GRANT_RUNTIME; 11489 } 11490 } break; 11491 11492 case PermissionInfo.PROTECTION_SIGNATURE: { 11493 // For all apps signature permissions are install time ones. 11494 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11495 if (allowedSig) { 11496 grant = GRANT_INSTALL; 11497 } 11498 } break; 11499 } 11500 11501 if (DEBUG_INSTALL) { 11502 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11503 } 11504 11505 if (grant != GRANT_DENIED) { 11506 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11507 // If this is an existing, non-system package, then 11508 // we can't add any new permissions to it. 11509 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11510 // Except... if this is a permission that was added 11511 // to the platform (note: need to only do this when 11512 // updating the platform). 11513 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11514 grant = GRANT_DENIED; 11515 } 11516 } 11517 } 11518 11519 switch (grant) { 11520 case GRANT_INSTALL: { 11521 // Revoke this as runtime permission to handle the case of 11522 // a runtime permission being downgraded to an install one. 11523 // Also in permission review mode we keep dangerous permissions 11524 // for legacy apps 11525 for (int userId : UserManagerService.getInstance().getUserIds()) { 11526 if (origPermissions.getRuntimePermissionState( 11527 bp.name, userId) != null) { 11528 // Revoke the runtime permission and clear the flags. 11529 origPermissions.revokeRuntimePermission(bp, userId); 11530 origPermissions.updatePermissionFlags(bp, userId, 11531 PackageManager.MASK_PERMISSION_FLAGS, 0); 11532 // If we revoked a permission permission, we have to write. 11533 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11534 changedRuntimePermissionUserIds, userId); 11535 } 11536 } 11537 // Grant an install permission. 11538 if (permissionsState.grantInstallPermission(bp) != 11539 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11540 changedInstallPermission = true; 11541 } 11542 } break; 11543 11544 case GRANT_RUNTIME: { 11545 // Grant previously granted runtime permissions. 11546 for (int userId : UserManagerService.getInstance().getUserIds()) { 11547 PermissionState permissionState = origPermissions 11548 .getRuntimePermissionState(bp.name, userId); 11549 int flags = permissionState != null 11550 ? permissionState.getFlags() : 0; 11551 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11552 // Don't propagate the permission in a permission review mode if 11553 // the former was revoked, i.e. marked to not propagate on upgrade. 11554 // Note that in a permission review mode install permissions are 11555 // represented as constantly granted runtime ones since we need to 11556 // keep a per user state associated with the permission. Also the 11557 // revoke on upgrade flag is no longer applicable and is reset. 11558 final boolean revokeOnUpgrade = (flags & PackageManager 11559 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11560 if (revokeOnUpgrade) { 11561 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11562 // Since we changed the flags, we have to write. 11563 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11564 changedRuntimePermissionUserIds, userId); 11565 } 11566 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11567 if (permissionsState.grantRuntimePermission(bp, userId) == 11568 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11569 // If we cannot put the permission as it was, 11570 // we have to write. 11571 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11572 changedRuntimePermissionUserIds, userId); 11573 } 11574 } 11575 11576 // If the app supports runtime permissions no need for a review. 11577 if (mPermissionReviewRequired 11578 && appSupportsRuntimePermissions 11579 && (flags & PackageManager 11580 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11581 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11582 // Since we changed the flags, we have to write. 11583 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11584 changedRuntimePermissionUserIds, userId); 11585 } 11586 } else if (mPermissionReviewRequired 11587 && !appSupportsRuntimePermissions) { 11588 // For legacy apps that need a permission review, every new 11589 // runtime permission is granted but it is pending a review. 11590 // We also need to review only platform defined runtime 11591 // permissions as these are the only ones the platform knows 11592 // how to disable the API to simulate revocation as legacy 11593 // apps don't expect to run with revoked permissions. 11594 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11595 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11596 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11597 // We changed the flags, hence have to write. 11598 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11599 changedRuntimePermissionUserIds, userId); 11600 } 11601 } 11602 if (permissionsState.grantRuntimePermission(bp, userId) 11603 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11604 // We changed the permission, hence have to write. 11605 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11606 changedRuntimePermissionUserIds, userId); 11607 } 11608 } 11609 // Propagate the permission flags. 11610 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11611 } 11612 } break; 11613 11614 case GRANT_UPGRADE: { 11615 // Grant runtime permissions for a previously held install permission. 11616 PermissionState permissionState = origPermissions 11617 .getInstallPermissionState(bp.name); 11618 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11619 11620 if (origPermissions.revokeInstallPermission(bp) 11621 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11622 // We will be transferring the permission flags, so clear them. 11623 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11624 PackageManager.MASK_PERMISSION_FLAGS, 0); 11625 changedInstallPermission = true; 11626 } 11627 11628 // If the permission is not to be promoted to runtime we ignore it and 11629 // also its other flags as they are not applicable to install permissions. 11630 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11631 for (int userId : currentUserIds) { 11632 if (permissionsState.grantRuntimePermission(bp, userId) != 11633 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11634 // Transfer the permission flags. 11635 permissionsState.updatePermissionFlags(bp, userId, 11636 flags, flags); 11637 // If we granted the permission, we have to write. 11638 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11639 changedRuntimePermissionUserIds, userId); 11640 } 11641 } 11642 } 11643 } break; 11644 11645 default: { 11646 if (packageOfInterest == null 11647 || packageOfInterest.equals(pkg.packageName)) { 11648 Slog.w(TAG, "Not granting permission " + perm 11649 + " to package " + pkg.packageName 11650 + " because it was previously installed without"); 11651 } 11652 } break; 11653 } 11654 } else { 11655 if (permissionsState.revokeInstallPermission(bp) != 11656 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11657 // Also drop the permission flags. 11658 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11659 PackageManager.MASK_PERMISSION_FLAGS, 0); 11660 changedInstallPermission = true; 11661 Slog.i(TAG, "Un-granting permission " + perm 11662 + " from package " + pkg.packageName 11663 + " (protectionLevel=" + bp.protectionLevel 11664 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11665 + ")"); 11666 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11667 // Don't print warning for app op permissions, since it is fine for them 11668 // not to be granted, there is a UI for the user to decide. 11669 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11670 Slog.w(TAG, "Not granting permission " + perm 11671 + " to package " + pkg.packageName 11672 + " (protectionLevel=" + bp.protectionLevel 11673 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11674 + ")"); 11675 } 11676 } 11677 } 11678 } 11679 11680 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11681 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11682 // This is the first that we have heard about this package, so the 11683 // permissions we have now selected are fixed until explicitly 11684 // changed. 11685 ps.installPermissionsFixed = true; 11686 } 11687 11688 // Persist the runtime permissions state for users with changes. If permissions 11689 // were revoked because no app in the shared user declares them we have to 11690 // write synchronously to avoid losing runtime permissions state. 11691 for (int userId : changedRuntimePermissionUserIds) { 11692 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11693 } 11694 } 11695 11696 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11697 boolean allowed = false; 11698 final int NP = PackageParser.NEW_PERMISSIONS.length; 11699 for (int ip=0; ip<NP; ip++) { 11700 final PackageParser.NewPermissionInfo npi 11701 = PackageParser.NEW_PERMISSIONS[ip]; 11702 if (npi.name.equals(perm) 11703 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11704 allowed = true; 11705 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11706 + pkg.packageName); 11707 break; 11708 } 11709 } 11710 return allowed; 11711 } 11712 11713 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11714 BasePermission bp, PermissionsState origPermissions) { 11715 boolean privilegedPermission = (bp.protectionLevel 11716 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11717 boolean privappPermissionsDisable = 11718 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11719 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11720 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11721 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11722 && !platformPackage && platformPermission) { 11723 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11724 .getPrivAppPermissions(pkg.packageName); 11725 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11726 if (!whitelisted) { 11727 Slog.w(TAG, "Privileged permission " + perm + " for package " 11728 + pkg.packageName + " - not in privapp-permissions whitelist"); 11729 // Only report violations for apps on system image 11730 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11731 if (mPrivappPermissionsViolations == null) { 11732 mPrivappPermissionsViolations = new ArraySet<>(); 11733 } 11734 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11735 } 11736 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11737 return false; 11738 } 11739 } 11740 } 11741 boolean allowed = (compareSignatures( 11742 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11743 == PackageManager.SIGNATURE_MATCH) 11744 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11745 == PackageManager.SIGNATURE_MATCH); 11746 if (!allowed && privilegedPermission) { 11747 if (isSystemApp(pkg)) { 11748 // For updated system applications, a system permission 11749 // is granted only if it had been defined by the original application. 11750 if (pkg.isUpdatedSystemApp()) { 11751 final PackageSetting sysPs = mSettings 11752 .getDisabledSystemPkgLPr(pkg.packageName); 11753 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11754 // If the original was granted this permission, we take 11755 // that grant decision as read and propagate it to the 11756 // update. 11757 if (sysPs.isPrivileged()) { 11758 allowed = true; 11759 } 11760 } else { 11761 // The system apk may have been updated with an older 11762 // version of the one on the data partition, but which 11763 // granted a new system permission that it didn't have 11764 // before. In this case we do want to allow the app to 11765 // now get the new permission if the ancestral apk is 11766 // privileged to get it. 11767 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11768 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11769 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11770 allowed = true; 11771 break; 11772 } 11773 } 11774 } 11775 // Also if a privileged parent package on the system image or any of 11776 // its children requested a privileged permission, the updated child 11777 // packages can also get the permission. 11778 if (pkg.parentPackage != null) { 11779 final PackageSetting disabledSysParentPs = mSettings 11780 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11781 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11782 && disabledSysParentPs.isPrivileged()) { 11783 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11784 allowed = true; 11785 } else if (disabledSysParentPs.pkg.childPackages != null) { 11786 final int count = disabledSysParentPs.pkg.childPackages.size(); 11787 for (int i = 0; i < count; i++) { 11788 PackageParser.Package disabledSysChildPkg = 11789 disabledSysParentPs.pkg.childPackages.get(i); 11790 if (isPackageRequestingPermission(disabledSysChildPkg, 11791 perm)) { 11792 allowed = true; 11793 break; 11794 } 11795 } 11796 } 11797 } 11798 } 11799 } 11800 } else { 11801 allowed = isPrivilegedApp(pkg); 11802 } 11803 } 11804 } 11805 if (!allowed) { 11806 if (!allowed && (bp.protectionLevel 11807 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11808 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11809 // If this was a previously normal/dangerous permission that got moved 11810 // to a system permission as part of the runtime permission redesign, then 11811 // we still want to blindly grant it to old apps. 11812 allowed = true; 11813 } 11814 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11815 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11816 // If this permission is to be granted to the system installer and 11817 // this app is an installer, then it gets the permission. 11818 allowed = true; 11819 } 11820 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11821 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11822 // If this permission is to be granted to the system verifier and 11823 // this app is a verifier, then it gets the permission. 11824 allowed = true; 11825 } 11826 if (!allowed && (bp.protectionLevel 11827 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11828 && isSystemApp(pkg)) { 11829 // Any pre-installed system app is allowed to get this permission. 11830 allowed = true; 11831 } 11832 if (!allowed && (bp.protectionLevel 11833 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11834 // For development permissions, a development permission 11835 // is granted only if it was already granted. 11836 allowed = origPermissions.hasInstallPermission(perm); 11837 } 11838 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11839 && pkg.packageName.equals(mSetupWizardPackage)) { 11840 // If this permission is to be granted to the system setup wizard and 11841 // this app is a setup wizard, then it gets the permission. 11842 allowed = true; 11843 } 11844 } 11845 return allowed; 11846 } 11847 11848 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11849 final int permCount = pkg.requestedPermissions.size(); 11850 for (int j = 0; j < permCount; j++) { 11851 String requestedPermission = pkg.requestedPermissions.get(j); 11852 if (permission.equals(requestedPermission)) { 11853 return true; 11854 } 11855 } 11856 return false; 11857 } 11858 11859 final class ActivityIntentResolver 11860 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11861 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11862 boolean defaultOnly, int userId) { 11863 if (!sUserManager.exists(userId)) return null; 11864 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11865 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11866 } 11867 11868 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11869 int userId) { 11870 if (!sUserManager.exists(userId)) return null; 11871 mFlags = flags; 11872 return super.queryIntent(intent, resolvedType, 11873 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11874 userId); 11875 } 11876 11877 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11878 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11879 if (!sUserManager.exists(userId)) return null; 11880 if (packageActivities == null) { 11881 return null; 11882 } 11883 mFlags = flags; 11884 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11885 final int N = packageActivities.size(); 11886 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11887 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11888 11889 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11890 for (int i = 0; i < N; ++i) { 11891 intentFilters = packageActivities.get(i).intents; 11892 if (intentFilters != null && intentFilters.size() > 0) { 11893 PackageParser.ActivityIntentInfo[] array = 11894 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11895 intentFilters.toArray(array); 11896 listCut.add(array); 11897 } 11898 } 11899 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11900 } 11901 11902 /** 11903 * Finds a privileged activity that matches the specified activity names. 11904 */ 11905 private PackageParser.Activity findMatchingActivity( 11906 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11907 for (PackageParser.Activity sysActivity : activityList) { 11908 if (sysActivity.info.name.equals(activityInfo.name)) { 11909 return sysActivity; 11910 } 11911 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11912 return sysActivity; 11913 } 11914 if (sysActivity.info.targetActivity != null) { 11915 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11916 return sysActivity; 11917 } 11918 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11919 return sysActivity; 11920 } 11921 } 11922 } 11923 return null; 11924 } 11925 11926 public class IterGenerator<E> { 11927 public Iterator<E> generate(ActivityIntentInfo info) { 11928 return null; 11929 } 11930 } 11931 11932 public class ActionIterGenerator extends IterGenerator<String> { 11933 @Override 11934 public Iterator<String> generate(ActivityIntentInfo info) { 11935 return info.actionsIterator(); 11936 } 11937 } 11938 11939 public class CategoriesIterGenerator extends IterGenerator<String> { 11940 @Override 11941 public Iterator<String> generate(ActivityIntentInfo info) { 11942 return info.categoriesIterator(); 11943 } 11944 } 11945 11946 public class SchemesIterGenerator extends IterGenerator<String> { 11947 @Override 11948 public Iterator<String> generate(ActivityIntentInfo info) { 11949 return info.schemesIterator(); 11950 } 11951 } 11952 11953 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11954 @Override 11955 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11956 return info.authoritiesIterator(); 11957 } 11958 } 11959 11960 /** 11961 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11962 * MODIFIED. Do not pass in a list that should not be changed. 11963 */ 11964 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11965 IterGenerator<T> generator, Iterator<T> searchIterator) { 11966 // loop through the set of actions; every one must be found in the intent filter 11967 while (searchIterator.hasNext()) { 11968 // we must have at least one filter in the list to consider a match 11969 if (intentList.size() == 0) { 11970 break; 11971 } 11972 11973 final T searchAction = searchIterator.next(); 11974 11975 // loop through the set of intent filters 11976 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11977 while (intentIter.hasNext()) { 11978 final ActivityIntentInfo intentInfo = intentIter.next(); 11979 boolean selectionFound = false; 11980 11981 // loop through the intent filter's selection criteria; at least one 11982 // of them must match the searched criteria 11983 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11984 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11985 final T intentSelection = intentSelectionIter.next(); 11986 if (intentSelection != null && intentSelection.equals(searchAction)) { 11987 selectionFound = true; 11988 break; 11989 } 11990 } 11991 11992 // the selection criteria wasn't found in this filter's set; this filter 11993 // is not a potential match 11994 if (!selectionFound) { 11995 intentIter.remove(); 11996 } 11997 } 11998 } 11999 } 12000 12001 private boolean isProtectedAction(ActivityIntentInfo filter) { 12002 final Iterator<String> actionsIter = filter.actionsIterator(); 12003 while (actionsIter != null && actionsIter.hasNext()) { 12004 final String filterAction = actionsIter.next(); 12005 if (PROTECTED_ACTIONS.contains(filterAction)) { 12006 return true; 12007 } 12008 } 12009 return false; 12010 } 12011 12012 /** 12013 * Adjusts the priority of the given intent filter according to policy. 12014 * <p> 12015 * <ul> 12016 * <li>The priority for non privileged applications is capped to '0'</li> 12017 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12018 * <li>The priority for unbundled updates to privileged applications is capped to the 12019 * priority defined on the system partition</li> 12020 * </ul> 12021 * <p> 12022 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12023 * allowed to obtain any priority on any action. 12024 */ 12025 private void adjustPriority( 12026 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12027 // nothing to do; priority is fine as-is 12028 if (intent.getPriority() <= 0) { 12029 return; 12030 } 12031 12032 final ActivityInfo activityInfo = intent.activity.info; 12033 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12034 12035 final boolean privilegedApp = 12036 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12037 if (!privilegedApp) { 12038 // non-privileged applications can never define a priority >0 12039 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12040 + " package: " + applicationInfo.packageName 12041 + " activity: " + intent.activity.className 12042 + " origPrio: " + intent.getPriority()); 12043 intent.setPriority(0); 12044 return; 12045 } 12046 12047 if (systemActivities == null) { 12048 // the system package is not disabled; we're parsing the system partition 12049 if (isProtectedAction(intent)) { 12050 if (mDeferProtectedFilters) { 12051 // We can't deal with these just yet. No component should ever obtain a 12052 // >0 priority for a protected actions, with ONE exception -- the setup 12053 // wizard. The setup wizard, however, cannot be known until we're able to 12054 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12055 // until all intent filters have been processed. Chicken, meet egg. 12056 // Let the filter temporarily have a high priority and rectify the 12057 // priorities after all system packages have been scanned. 12058 mProtectedFilters.add(intent); 12059 if (DEBUG_FILTERS) { 12060 Slog.i(TAG, "Protected action; save for later;" 12061 + " package: " + applicationInfo.packageName 12062 + " activity: " + intent.activity.className 12063 + " origPrio: " + intent.getPriority()); 12064 } 12065 return; 12066 } else { 12067 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12068 Slog.i(TAG, "No setup wizard;" 12069 + " All protected intents capped to priority 0"); 12070 } 12071 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12072 if (DEBUG_FILTERS) { 12073 Slog.i(TAG, "Found setup wizard;" 12074 + " allow priority " + intent.getPriority() + ";" 12075 + " package: " + intent.activity.info.packageName 12076 + " activity: " + intent.activity.className 12077 + " priority: " + intent.getPriority()); 12078 } 12079 // setup wizard gets whatever it wants 12080 return; 12081 } 12082 Slog.w(TAG, "Protected action; cap priority to 0;" 12083 + " package: " + intent.activity.info.packageName 12084 + " activity: " + intent.activity.className 12085 + " origPrio: " + intent.getPriority()); 12086 intent.setPriority(0); 12087 return; 12088 } 12089 } 12090 // privileged apps on the system image get whatever priority they request 12091 return; 12092 } 12093 12094 // privileged app unbundled update ... try to find the same activity 12095 final PackageParser.Activity foundActivity = 12096 findMatchingActivity(systemActivities, activityInfo); 12097 if (foundActivity == null) { 12098 // this is a new activity; it cannot obtain >0 priority 12099 if (DEBUG_FILTERS) { 12100 Slog.i(TAG, "New activity; cap priority to 0;" 12101 + " package: " + applicationInfo.packageName 12102 + " activity: " + intent.activity.className 12103 + " origPrio: " + intent.getPriority()); 12104 } 12105 intent.setPriority(0); 12106 return; 12107 } 12108 12109 // found activity, now check for filter equivalence 12110 12111 // a shallow copy is enough; we modify the list, not its contents 12112 final List<ActivityIntentInfo> intentListCopy = 12113 new ArrayList<>(foundActivity.intents); 12114 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12115 12116 // find matching action subsets 12117 final Iterator<String> actionsIterator = intent.actionsIterator(); 12118 if (actionsIterator != null) { 12119 getIntentListSubset( 12120 intentListCopy, new ActionIterGenerator(), actionsIterator); 12121 if (intentListCopy.size() == 0) { 12122 // no more intents to match; we're not equivalent 12123 if (DEBUG_FILTERS) { 12124 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12125 + " package: " + applicationInfo.packageName 12126 + " activity: " + intent.activity.className 12127 + " origPrio: " + intent.getPriority()); 12128 } 12129 intent.setPriority(0); 12130 return; 12131 } 12132 } 12133 12134 // find matching category subsets 12135 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12136 if (categoriesIterator != null) { 12137 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12138 categoriesIterator); 12139 if (intentListCopy.size() == 0) { 12140 // no more intents to match; we're not equivalent 12141 if (DEBUG_FILTERS) { 12142 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12143 + " package: " + applicationInfo.packageName 12144 + " activity: " + intent.activity.className 12145 + " origPrio: " + intent.getPriority()); 12146 } 12147 intent.setPriority(0); 12148 return; 12149 } 12150 } 12151 12152 // find matching schemes subsets 12153 final Iterator<String> schemesIterator = intent.schemesIterator(); 12154 if (schemesIterator != null) { 12155 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12156 schemesIterator); 12157 if (intentListCopy.size() == 0) { 12158 // no more intents to match; we're not equivalent 12159 if (DEBUG_FILTERS) { 12160 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12161 + " package: " + applicationInfo.packageName 12162 + " activity: " + intent.activity.className 12163 + " origPrio: " + intent.getPriority()); 12164 } 12165 intent.setPriority(0); 12166 return; 12167 } 12168 } 12169 12170 // find matching authorities subsets 12171 final Iterator<IntentFilter.AuthorityEntry> 12172 authoritiesIterator = intent.authoritiesIterator(); 12173 if (authoritiesIterator != null) { 12174 getIntentListSubset(intentListCopy, 12175 new AuthoritiesIterGenerator(), 12176 authoritiesIterator); 12177 if (intentListCopy.size() == 0) { 12178 // no more intents to match; we're not equivalent 12179 if (DEBUG_FILTERS) { 12180 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12181 + " package: " + applicationInfo.packageName 12182 + " activity: " + intent.activity.className 12183 + " origPrio: " + intent.getPriority()); 12184 } 12185 intent.setPriority(0); 12186 return; 12187 } 12188 } 12189 12190 // we found matching filter(s); app gets the max priority of all intents 12191 int cappedPriority = 0; 12192 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12193 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12194 } 12195 if (intent.getPriority() > cappedPriority) { 12196 if (DEBUG_FILTERS) { 12197 Slog.i(TAG, "Found matching filter(s);" 12198 + " cap priority to " + cappedPriority + ";" 12199 + " package: " + applicationInfo.packageName 12200 + " activity: " + intent.activity.className 12201 + " origPrio: " + intent.getPriority()); 12202 } 12203 intent.setPriority(cappedPriority); 12204 return; 12205 } 12206 // all this for nothing; the requested priority was <= what was on the system 12207 } 12208 12209 public final void addActivity(PackageParser.Activity a, String type) { 12210 mActivities.put(a.getComponentName(), a); 12211 if (DEBUG_SHOW_INFO) 12212 Log.v( 12213 TAG, " " + type + " " + 12214 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12215 if (DEBUG_SHOW_INFO) 12216 Log.v(TAG, " Class=" + a.info.name); 12217 final int NI = a.intents.size(); 12218 for (int j=0; j<NI; j++) { 12219 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12220 if ("activity".equals(type)) { 12221 final PackageSetting ps = 12222 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12223 final List<PackageParser.Activity> systemActivities = 12224 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12225 adjustPriority(systemActivities, intent); 12226 } 12227 if (DEBUG_SHOW_INFO) { 12228 Log.v(TAG, " IntentFilter:"); 12229 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12230 } 12231 if (!intent.debugCheck()) { 12232 Log.w(TAG, "==> For Activity " + a.info.name); 12233 } 12234 addFilter(intent); 12235 } 12236 } 12237 12238 public final void removeActivity(PackageParser.Activity a, String type) { 12239 mActivities.remove(a.getComponentName()); 12240 if (DEBUG_SHOW_INFO) { 12241 Log.v(TAG, " " + type + " " 12242 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12243 : a.info.name) + ":"); 12244 Log.v(TAG, " Class=" + a.info.name); 12245 } 12246 final int NI = a.intents.size(); 12247 for (int j=0; j<NI; j++) { 12248 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12249 if (DEBUG_SHOW_INFO) { 12250 Log.v(TAG, " IntentFilter:"); 12251 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12252 } 12253 removeFilter(intent); 12254 } 12255 } 12256 12257 @Override 12258 protected boolean allowFilterResult( 12259 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12260 ActivityInfo filterAi = filter.activity.info; 12261 for (int i=dest.size()-1; i>=0; i--) { 12262 ActivityInfo destAi = dest.get(i).activityInfo; 12263 if (destAi.name == filterAi.name 12264 && destAi.packageName == filterAi.packageName) { 12265 return false; 12266 } 12267 } 12268 return true; 12269 } 12270 12271 @Override 12272 protected ActivityIntentInfo[] newArray(int size) { 12273 return new ActivityIntentInfo[size]; 12274 } 12275 12276 @Override 12277 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12278 if (!sUserManager.exists(userId)) return true; 12279 PackageParser.Package p = filter.activity.owner; 12280 if (p != null) { 12281 PackageSetting ps = (PackageSetting)p.mExtras; 12282 if (ps != null) { 12283 // System apps are never considered stopped for purposes of 12284 // filtering, because there may be no way for the user to 12285 // actually re-launch them. 12286 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12287 && ps.getStopped(userId); 12288 } 12289 } 12290 return false; 12291 } 12292 12293 @Override 12294 protected boolean isPackageForFilter(String packageName, 12295 PackageParser.ActivityIntentInfo info) { 12296 return packageName.equals(info.activity.owner.packageName); 12297 } 12298 12299 @Override 12300 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12301 int match, int userId) { 12302 if (!sUserManager.exists(userId)) return null; 12303 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12304 return null; 12305 } 12306 final PackageParser.Activity activity = info.activity; 12307 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12308 if (ps == null) { 12309 return null; 12310 } 12311 final PackageUserState userState = ps.readUserState(userId); 12312 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12313 userState, userId); 12314 if (ai == null) { 12315 return null; 12316 } 12317 final boolean matchVisibleToInstantApp = 12318 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12319 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12320 // throw out filters that aren't visible to ephemeral apps 12321 if (matchVisibleToInstantApp 12322 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12323 return null; 12324 } 12325 // throw out ephemeral filters if we're not explicitly requesting them 12326 if (!isInstantApp && userState.instantApp) { 12327 return null; 12328 } 12329 // throw out instant app filters if updates are available; will trigger 12330 // instant app resolution 12331 if (userState.instantApp && ps.isUpdateAvailable()) { 12332 return null; 12333 } 12334 final ResolveInfo res = new ResolveInfo(); 12335 res.activityInfo = ai; 12336 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12337 res.filter = info; 12338 } 12339 if (info != null) { 12340 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12341 } 12342 res.priority = info.getPriority(); 12343 res.preferredOrder = activity.owner.mPreferredOrder; 12344 //System.out.println("Result: " + res.activityInfo.className + 12345 // " = " + res.priority); 12346 res.match = match; 12347 res.isDefault = info.hasDefault; 12348 res.labelRes = info.labelRes; 12349 res.nonLocalizedLabel = info.nonLocalizedLabel; 12350 if (userNeedsBadging(userId)) { 12351 res.noResourceId = true; 12352 } else { 12353 res.icon = info.icon; 12354 } 12355 res.iconResourceId = info.icon; 12356 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12357 res.instantAppAvailable = userState.instantApp; 12358 return res; 12359 } 12360 12361 @Override 12362 protected void sortResults(List<ResolveInfo> results) { 12363 Collections.sort(results, mResolvePrioritySorter); 12364 } 12365 12366 @Override 12367 protected void dumpFilter(PrintWriter out, String prefix, 12368 PackageParser.ActivityIntentInfo filter) { 12369 out.print(prefix); out.print( 12370 Integer.toHexString(System.identityHashCode(filter.activity))); 12371 out.print(' '); 12372 filter.activity.printComponentShortName(out); 12373 out.print(" filter "); 12374 out.println(Integer.toHexString(System.identityHashCode(filter))); 12375 } 12376 12377 @Override 12378 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12379 return filter.activity; 12380 } 12381 12382 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12383 PackageParser.Activity activity = (PackageParser.Activity)label; 12384 out.print(prefix); out.print( 12385 Integer.toHexString(System.identityHashCode(activity))); 12386 out.print(' '); 12387 activity.printComponentShortName(out); 12388 if (count > 1) { 12389 out.print(" ("); out.print(count); out.print(" filters)"); 12390 } 12391 out.println(); 12392 } 12393 12394 // Keys are String (activity class name), values are Activity. 12395 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12396 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12397 private int mFlags; 12398 } 12399 12400 private final class ServiceIntentResolver 12401 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12402 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12403 boolean defaultOnly, int userId) { 12404 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12405 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12406 } 12407 12408 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12409 int userId) { 12410 if (!sUserManager.exists(userId)) return null; 12411 mFlags = flags; 12412 return super.queryIntent(intent, resolvedType, 12413 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12414 userId); 12415 } 12416 12417 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12418 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12419 if (!sUserManager.exists(userId)) return null; 12420 if (packageServices == null) { 12421 return null; 12422 } 12423 mFlags = flags; 12424 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12425 final int N = packageServices.size(); 12426 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12427 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12428 12429 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12430 for (int i = 0; i < N; ++i) { 12431 intentFilters = packageServices.get(i).intents; 12432 if (intentFilters != null && intentFilters.size() > 0) { 12433 PackageParser.ServiceIntentInfo[] array = 12434 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12435 intentFilters.toArray(array); 12436 listCut.add(array); 12437 } 12438 } 12439 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12440 } 12441 12442 public final void addService(PackageParser.Service s) { 12443 mServices.put(s.getComponentName(), s); 12444 if (DEBUG_SHOW_INFO) { 12445 Log.v(TAG, " " 12446 + (s.info.nonLocalizedLabel != null 12447 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12448 Log.v(TAG, " Class=" + s.info.name); 12449 } 12450 final int NI = s.intents.size(); 12451 int j; 12452 for (j=0; j<NI; j++) { 12453 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12454 if (DEBUG_SHOW_INFO) { 12455 Log.v(TAG, " IntentFilter:"); 12456 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12457 } 12458 if (!intent.debugCheck()) { 12459 Log.w(TAG, "==> For Service " + s.info.name); 12460 } 12461 addFilter(intent); 12462 } 12463 } 12464 12465 public final void removeService(PackageParser.Service s) { 12466 mServices.remove(s.getComponentName()); 12467 if (DEBUG_SHOW_INFO) { 12468 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12469 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12470 Log.v(TAG, " Class=" + s.info.name); 12471 } 12472 final int NI = s.intents.size(); 12473 int j; 12474 for (j=0; j<NI; j++) { 12475 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12476 if (DEBUG_SHOW_INFO) { 12477 Log.v(TAG, " IntentFilter:"); 12478 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12479 } 12480 removeFilter(intent); 12481 } 12482 } 12483 12484 @Override 12485 protected boolean allowFilterResult( 12486 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12487 ServiceInfo filterSi = filter.service.info; 12488 for (int i=dest.size()-1; i>=0; i--) { 12489 ServiceInfo destAi = dest.get(i).serviceInfo; 12490 if (destAi.name == filterSi.name 12491 && destAi.packageName == filterSi.packageName) { 12492 return false; 12493 } 12494 } 12495 return true; 12496 } 12497 12498 @Override 12499 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12500 return new PackageParser.ServiceIntentInfo[size]; 12501 } 12502 12503 @Override 12504 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12505 if (!sUserManager.exists(userId)) return true; 12506 PackageParser.Package p = filter.service.owner; 12507 if (p != null) { 12508 PackageSetting ps = (PackageSetting)p.mExtras; 12509 if (ps != null) { 12510 // System apps are never considered stopped for purposes of 12511 // filtering, because there may be no way for the user to 12512 // actually re-launch them. 12513 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12514 && ps.getStopped(userId); 12515 } 12516 } 12517 return false; 12518 } 12519 12520 @Override 12521 protected boolean isPackageForFilter(String packageName, 12522 PackageParser.ServiceIntentInfo info) { 12523 return packageName.equals(info.service.owner.packageName); 12524 } 12525 12526 @Override 12527 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12528 int match, int userId) { 12529 if (!sUserManager.exists(userId)) return null; 12530 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12531 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12532 return null; 12533 } 12534 final PackageParser.Service service = info.service; 12535 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12536 if (ps == null) { 12537 return null; 12538 } 12539 final PackageUserState userState = ps.readUserState(userId); 12540 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12541 userState, userId); 12542 if (si == null) { 12543 return null; 12544 } 12545 final boolean matchVisibleToInstantApp = 12546 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12547 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12548 // throw out filters that aren't visible to ephemeral apps 12549 if (matchVisibleToInstantApp 12550 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12551 return null; 12552 } 12553 // throw out ephemeral filters if we're not explicitly requesting them 12554 if (!isInstantApp && userState.instantApp) { 12555 return null; 12556 } 12557 // throw out instant app filters if updates are available; will trigger 12558 // instant app resolution 12559 if (userState.instantApp && ps.isUpdateAvailable()) { 12560 return null; 12561 } 12562 final ResolveInfo res = new ResolveInfo(); 12563 res.serviceInfo = si; 12564 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12565 res.filter = filter; 12566 } 12567 res.priority = info.getPriority(); 12568 res.preferredOrder = service.owner.mPreferredOrder; 12569 res.match = match; 12570 res.isDefault = info.hasDefault; 12571 res.labelRes = info.labelRes; 12572 res.nonLocalizedLabel = info.nonLocalizedLabel; 12573 res.icon = info.icon; 12574 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12575 return res; 12576 } 12577 12578 @Override 12579 protected void sortResults(List<ResolveInfo> results) { 12580 Collections.sort(results, mResolvePrioritySorter); 12581 } 12582 12583 @Override 12584 protected void dumpFilter(PrintWriter out, String prefix, 12585 PackageParser.ServiceIntentInfo filter) { 12586 out.print(prefix); out.print( 12587 Integer.toHexString(System.identityHashCode(filter.service))); 12588 out.print(' '); 12589 filter.service.printComponentShortName(out); 12590 out.print(" filter "); 12591 out.println(Integer.toHexString(System.identityHashCode(filter))); 12592 } 12593 12594 @Override 12595 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12596 return filter.service; 12597 } 12598 12599 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12600 PackageParser.Service service = (PackageParser.Service)label; 12601 out.print(prefix); out.print( 12602 Integer.toHexString(System.identityHashCode(service))); 12603 out.print(' '); 12604 service.printComponentShortName(out); 12605 if (count > 1) { 12606 out.print(" ("); out.print(count); out.print(" filters)"); 12607 } 12608 out.println(); 12609 } 12610 12611// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12612// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12613// final List<ResolveInfo> retList = Lists.newArrayList(); 12614// while (i.hasNext()) { 12615// final ResolveInfo resolveInfo = (ResolveInfo) i; 12616// if (isEnabledLP(resolveInfo.serviceInfo)) { 12617// retList.add(resolveInfo); 12618// } 12619// } 12620// return retList; 12621// } 12622 12623 // Keys are String (activity class name), values are Activity. 12624 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12625 = new ArrayMap<ComponentName, PackageParser.Service>(); 12626 private int mFlags; 12627 } 12628 12629 private final class ProviderIntentResolver 12630 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12631 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12632 boolean defaultOnly, int userId) { 12633 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12634 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12635 } 12636 12637 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12638 int userId) { 12639 if (!sUserManager.exists(userId)) 12640 return null; 12641 mFlags = flags; 12642 return super.queryIntent(intent, resolvedType, 12643 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12644 userId); 12645 } 12646 12647 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12648 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12649 if (!sUserManager.exists(userId)) 12650 return null; 12651 if (packageProviders == null) { 12652 return null; 12653 } 12654 mFlags = flags; 12655 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12656 final int N = packageProviders.size(); 12657 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12658 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12659 12660 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12661 for (int i = 0; i < N; ++i) { 12662 intentFilters = packageProviders.get(i).intents; 12663 if (intentFilters != null && intentFilters.size() > 0) { 12664 PackageParser.ProviderIntentInfo[] array = 12665 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12666 intentFilters.toArray(array); 12667 listCut.add(array); 12668 } 12669 } 12670 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12671 } 12672 12673 public final void addProvider(PackageParser.Provider p) { 12674 if (mProviders.containsKey(p.getComponentName())) { 12675 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12676 return; 12677 } 12678 12679 mProviders.put(p.getComponentName(), p); 12680 if (DEBUG_SHOW_INFO) { 12681 Log.v(TAG, " " 12682 + (p.info.nonLocalizedLabel != null 12683 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12684 Log.v(TAG, " Class=" + p.info.name); 12685 } 12686 final int NI = p.intents.size(); 12687 int j; 12688 for (j = 0; j < NI; j++) { 12689 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12690 if (DEBUG_SHOW_INFO) { 12691 Log.v(TAG, " IntentFilter:"); 12692 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12693 } 12694 if (!intent.debugCheck()) { 12695 Log.w(TAG, "==> For Provider " + p.info.name); 12696 } 12697 addFilter(intent); 12698 } 12699 } 12700 12701 public final void removeProvider(PackageParser.Provider p) { 12702 mProviders.remove(p.getComponentName()); 12703 if (DEBUG_SHOW_INFO) { 12704 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12705 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12706 Log.v(TAG, " Class=" + p.info.name); 12707 } 12708 final int NI = p.intents.size(); 12709 int j; 12710 for (j = 0; j < NI; j++) { 12711 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12712 if (DEBUG_SHOW_INFO) { 12713 Log.v(TAG, " IntentFilter:"); 12714 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12715 } 12716 removeFilter(intent); 12717 } 12718 } 12719 12720 @Override 12721 protected boolean allowFilterResult( 12722 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12723 ProviderInfo filterPi = filter.provider.info; 12724 for (int i = dest.size() - 1; i >= 0; i--) { 12725 ProviderInfo destPi = dest.get(i).providerInfo; 12726 if (destPi.name == filterPi.name 12727 && destPi.packageName == filterPi.packageName) { 12728 return false; 12729 } 12730 } 12731 return true; 12732 } 12733 12734 @Override 12735 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12736 return new PackageParser.ProviderIntentInfo[size]; 12737 } 12738 12739 @Override 12740 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12741 if (!sUserManager.exists(userId)) 12742 return true; 12743 PackageParser.Package p = filter.provider.owner; 12744 if (p != null) { 12745 PackageSetting ps = (PackageSetting) p.mExtras; 12746 if (ps != null) { 12747 // System apps are never considered stopped for purposes of 12748 // filtering, because there may be no way for the user to 12749 // actually re-launch them. 12750 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12751 && ps.getStopped(userId); 12752 } 12753 } 12754 return false; 12755 } 12756 12757 @Override 12758 protected boolean isPackageForFilter(String packageName, 12759 PackageParser.ProviderIntentInfo info) { 12760 return packageName.equals(info.provider.owner.packageName); 12761 } 12762 12763 @Override 12764 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12765 int match, int userId) { 12766 if (!sUserManager.exists(userId)) 12767 return null; 12768 final PackageParser.ProviderIntentInfo info = filter; 12769 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12770 return null; 12771 } 12772 final PackageParser.Provider provider = info.provider; 12773 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12774 if (ps == null) { 12775 return null; 12776 } 12777 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12778 ps.readUserState(userId), userId); 12779 if (pi == null) { 12780 return null; 12781 } 12782 final ResolveInfo res = new ResolveInfo(); 12783 res.providerInfo = pi; 12784 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12785 res.filter = filter; 12786 } 12787 res.priority = info.getPriority(); 12788 res.preferredOrder = provider.owner.mPreferredOrder; 12789 res.match = match; 12790 res.isDefault = info.hasDefault; 12791 res.labelRes = info.labelRes; 12792 res.nonLocalizedLabel = info.nonLocalizedLabel; 12793 res.icon = info.icon; 12794 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12795 return res; 12796 } 12797 12798 @Override 12799 protected void sortResults(List<ResolveInfo> results) { 12800 Collections.sort(results, mResolvePrioritySorter); 12801 } 12802 12803 @Override 12804 protected void dumpFilter(PrintWriter out, String prefix, 12805 PackageParser.ProviderIntentInfo filter) { 12806 out.print(prefix); 12807 out.print( 12808 Integer.toHexString(System.identityHashCode(filter.provider))); 12809 out.print(' '); 12810 filter.provider.printComponentShortName(out); 12811 out.print(" filter "); 12812 out.println(Integer.toHexString(System.identityHashCode(filter))); 12813 } 12814 12815 @Override 12816 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12817 return filter.provider; 12818 } 12819 12820 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12821 PackageParser.Provider provider = (PackageParser.Provider)label; 12822 out.print(prefix); out.print( 12823 Integer.toHexString(System.identityHashCode(provider))); 12824 out.print(' '); 12825 provider.printComponentShortName(out); 12826 if (count > 1) { 12827 out.print(" ("); out.print(count); out.print(" filters)"); 12828 } 12829 out.println(); 12830 } 12831 12832 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12833 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12834 private int mFlags; 12835 } 12836 12837 static final class EphemeralIntentResolver 12838 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12839 /** 12840 * The result that has the highest defined order. Ordering applies on a 12841 * per-package basis. Mapping is from package name to Pair of order and 12842 * EphemeralResolveInfo. 12843 * <p> 12844 * NOTE: This is implemented as a field variable for convenience and efficiency. 12845 * By having a field variable, we're able to track filter ordering as soon as 12846 * a non-zero order is defined. Otherwise, multiple loops across the result set 12847 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12848 * this needs to be contained entirely within {@link #filterResults}. 12849 */ 12850 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12851 12852 @Override 12853 protected AuxiliaryResolveInfo[] newArray(int size) { 12854 return new AuxiliaryResolveInfo[size]; 12855 } 12856 12857 @Override 12858 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12859 return true; 12860 } 12861 12862 @Override 12863 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12864 int userId) { 12865 if (!sUserManager.exists(userId)) { 12866 return null; 12867 } 12868 final String packageName = responseObj.resolveInfo.getPackageName(); 12869 final Integer order = responseObj.getOrder(); 12870 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12871 mOrderResult.get(packageName); 12872 // ordering is enabled and this item's order isn't high enough 12873 if (lastOrderResult != null && lastOrderResult.first >= order) { 12874 return null; 12875 } 12876 final InstantAppResolveInfo res = responseObj.resolveInfo; 12877 if (order > 0) { 12878 // non-zero order, enable ordering 12879 mOrderResult.put(packageName, new Pair<>(order, res)); 12880 } 12881 return responseObj; 12882 } 12883 12884 @Override 12885 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12886 // only do work if ordering is enabled [most of the time it won't be] 12887 if (mOrderResult.size() == 0) { 12888 return; 12889 } 12890 int resultSize = results.size(); 12891 for (int i = 0; i < resultSize; i++) { 12892 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12893 final String packageName = info.getPackageName(); 12894 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12895 if (savedInfo == null) { 12896 // package doesn't having ordering 12897 continue; 12898 } 12899 if (savedInfo.second == info) { 12900 // circled back to the highest ordered item; remove from order list 12901 mOrderResult.remove(savedInfo); 12902 if (mOrderResult.size() == 0) { 12903 // no more ordered items 12904 break; 12905 } 12906 continue; 12907 } 12908 // item has a worse order, remove it from the result list 12909 results.remove(i); 12910 resultSize--; 12911 i--; 12912 } 12913 } 12914 } 12915 12916 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12917 new Comparator<ResolveInfo>() { 12918 public int compare(ResolveInfo r1, ResolveInfo r2) { 12919 int v1 = r1.priority; 12920 int v2 = r2.priority; 12921 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12922 if (v1 != v2) { 12923 return (v1 > v2) ? -1 : 1; 12924 } 12925 v1 = r1.preferredOrder; 12926 v2 = r2.preferredOrder; 12927 if (v1 != v2) { 12928 return (v1 > v2) ? -1 : 1; 12929 } 12930 if (r1.isDefault != r2.isDefault) { 12931 return r1.isDefault ? -1 : 1; 12932 } 12933 v1 = r1.match; 12934 v2 = r2.match; 12935 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12936 if (v1 != v2) { 12937 return (v1 > v2) ? -1 : 1; 12938 } 12939 if (r1.system != r2.system) { 12940 return r1.system ? -1 : 1; 12941 } 12942 if (r1.activityInfo != null) { 12943 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12944 } 12945 if (r1.serviceInfo != null) { 12946 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12947 } 12948 if (r1.providerInfo != null) { 12949 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12950 } 12951 return 0; 12952 } 12953 }; 12954 12955 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12956 new Comparator<ProviderInfo>() { 12957 public int compare(ProviderInfo p1, ProviderInfo p2) { 12958 final int v1 = p1.initOrder; 12959 final int v2 = p2.initOrder; 12960 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12961 } 12962 }; 12963 12964 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12965 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12966 final int[] userIds) { 12967 mHandler.post(new Runnable() { 12968 @Override 12969 public void run() { 12970 try { 12971 final IActivityManager am = ActivityManager.getService(); 12972 if (am == null) return; 12973 final int[] resolvedUserIds; 12974 if (userIds == null) { 12975 resolvedUserIds = am.getRunningUserIds(); 12976 } else { 12977 resolvedUserIds = userIds; 12978 } 12979 for (int id : resolvedUserIds) { 12980 final Intent intent = new Intent(action, 12981 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12982 if (extras != null) { 12983 intent.putExtras(extras); 12984 } 12985 if (targetPkg != null) { 12986 intent.setPackage(targetPkg); 12987 } 12988 // Modify the UID when posting to other users 12989 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12990 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12991 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12992 intent.putExtra(Intent.EXTRA_UID, uid); 12993 } 12994 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12995 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12996 if (DEBUG_BROADCASTS) { 12997 RuntimeException here = new RuntimeException("here"); 12998 here.fillInStackTrace(); 12999 Slog.d(TAG, "Sending to user " + id + ": " 13000 + intent.toShortString(false, true, false, false) 13001 + " " + intent.getExtras(), here); 13002 } 13003 am.broadcastIntent(null, intent, null, finishedReceiver, 13004 0, null, null, null, android.app.AppOpsManager.OP_NONE, 13005 null, finishedReceiver != null, false, id); 13006 } 13007 } catch (RemoteException ex) { 13008 } 13009 } 13010 }); 13011 } 13012 13013 /** 13014 * Check if the external storage media is available. This is true if there 13015 * is a mounted external storage medium or if the external storage is 13016 * emulated. 13017 */ 13018 private boolean isExternalMediaAvailable() { 13019 return mMediaMounted || Environment.isExternalStorageEmulated(); 13020 } 13021 13022 @Override 13023 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13024 // writer 13025 synchronized (mPackages) { 13026 if (!isExternalMediaAvailable()) { 13027 // If the external storage is no longer mounted at this point, 13028 // the caller may not have been able to delete all of this 13029 // packages files and can not delete any more. Bail. 13030 return null; 13031 } 13032 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13033 if (lastPackage != null) { 13034 pkgs.remove(lastPackage); 13035 } 13036 if (pkgs.size() > 0) { 13037 return pkgs.get(0); 13038 } 13039 } 13040 return null; 13041 } 13042 13043 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13044 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13045 userId, andCode ? 1 : 0, packageName); 13046 if (mSystemReady) { 13047 msg.sendToTarget(); 13048 } else { 13049 if (mPostSystemReadyMessages == null) { 13050 mPostSystemReadyMessages = new ArrayList<>(); 13051 } 13052 mPostSystemReadyMessages.add(msg); 13053 } 13054 } 13055 13056 void startCleaningPackages() { 13057 // reader 13058 if (!isExternalMediaAvailable()) { 13059 return; 13060 } 13061 synchronized (mPackages) { 13062 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13063 return; 13064 } 13065 } 13066 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13067 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13068 IActivityManager am = ActivityManager.getService(); 13069 if (am != null) { 13070 int dcsUid = -1; 13071 synchronized (mPackages) { 13072 if (!mDefaultContainerWhitelisted) { 13073 mDefaultContainerWhitelisted = true; 13074 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13075 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13076 } 13077 } 13078 try { 13079 if (dcsUid > 0) { 13080 am.backgroundWhitelistUid(dcsUid); 13081 } 13082 am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(), 13083 UserHandle.USER_SYSTEM); 13084 } catch (RemoteException e) { 13085 } 13086 } 13087 } 13088 13089 @Override 13090 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13091 int installFlags, String installerPackageName, int userId) { 13092 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13093 13094 final int callingUid = Binder.getCallingUid(); 13095 enforceCrossUserPermission(callingUid, userId, 13096 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13097 13098 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13099 try { 13100 if (observer != null) { 13101 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13102 } 13103 } catch (RemoteException re) { 13104 } 13105 return; 13106 } 13107 13108 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13109 installFlags |= PackageManager.INSTALL_FROM_ADB; 13110 13111 } else { 13112 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13113 // about installerPackageName. 13114 13115 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13116 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13117 } 13118 13119 UserHandle user; 13120 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13121 user = UserHandle.ALL; 13122 } else { 13123 user = new UserHandle(userId); 13124 } 13125 13126 // Only system components can circumvent runtime permissions when installing. 13127 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13128 && mContext.checkCallingOrSelfPermission(Manifest.permission 13129 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13130 throw new SecurityException("You need the " 13131 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13132 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13133 } 13134 13135 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13136 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13137 throw new IllegalArgumentException( 13138 "New installs into ASEC containers no longer supported"); 13139 } 13140 13141 final File originFile = new File(originPath); 13142 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13143 13144 final Message msg = mHandler.obtainMessage(INIT_COPY); 13145 final VerificationInfo verificationInfo = new VerificationInfo( 13146 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13147 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13148 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13149 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13150 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13151 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13152 msg.obj = params; 13153 13154 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13155 System.identityHashCode(msg.obj)); 13156 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13157 System.identityHashCode(msg.obj)); 13158 13159 mHandler.sendMessage(msg); 13160 } 13161 13162 13163 /** 13164 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13165 * it is acting on behalf on an enterprise or the user). 13166 * 13167 * Note that the ordering of the conditionals in this method is important. The checks we perform 13168 * are as follows, in this order: 13169 * 13170 * 1) If the install is being performed by a system app, we can trust the app to have set the 13171 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13172 * what it is. 13173 * 2) If the install is being performed by a device or profile owner app, the install reason 13174 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13175 * set the install reason correctly. If the app targets an older SDK version where install 13176 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13177 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13178 * 3) In all other cases, the install is being performed by a regular app that is neither part 13179 * of the system nor a device or profile owner. We have no reason to believe that this app is 13180 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13181 * set to enterprise policy and if so, change it to unknown instead. 13182 */ 13183 private int fixUpInstallReason(String installerPackageName, int installerUid, 13184 int installReason) { 13185 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13186 == PERMISSION_GRANTED) { 13187 // If the install is being performed by a system app, we trust that app to have set the 13188 // install reason correctly. 13189 return installReason; 13190 } 13191 13192 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13193 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13194 if (dpm != null) { 13195 ComponentName owner = null; 13196 try { 13197 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13198 if (owner == null) { 13199 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13200 } 13201 } catch (RemoteException e) { 13202 } 13203 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13204 // If the install is being performed by a device or profile owner, the install 13205 // reason should be enterprise policy. 13206 return PackageManager.INSTALL_REASON_POLICY; 13207 } 13208 } 13209 13210 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13211 // If the install is being performed by a regular app (i.e. neither system app nor 13212 // device or profile owner), we have no reason to believe that the app is acting on 13213 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13214 // change it to unknown instead. 13215 return PackageManager.INSTALL_REASON_UNKNOWN; 13216 } 13217 13218 // If the install is being performed by a regular app and the install reason was set to any 13219 // value but enterprise policy, leave the install reason unchanged. 13220 return installReason; 13221 } 13222 13223 void installStage(String packageName, File stagedDir, String stagedCid, 13224 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13225 String installerPackageName, int installerUid, UserHandle user, 13226 Certificate[][] certificates) { 13227 if (DEBUG_EPHEMERAL) { 13228 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13229 Slog.d(TAG, "Ephemeral install of " + packageName); 13230 } 13231 } 13232 final VerificationInfo verificationInfo = new VerificationInfo( 13233 sessionParams.originatingUri, sessionParams.referrerUri, 13234 sessionParams.originatingUid, installerUid); 13235 13236 final OriginInfo origin; 13237 if (stagedDir != null) { 13238 origin = OriginInfo.fromStagedFile(stagedDir); 13239 } else { 13240 origin = OriginInfo.fromStagedContainer(stagedCid); 13241 } 13242 13243 final Message msg = mHandler.obtainMessage(INIT_COPY); 13244 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13245 sessionParams.installReason); 13246 final InstallParams params = new InstallParams(origin, null, observer, 13247 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13248 verificationInfo, user, sessionParams.abiOverride, 13249 sessionParams.grantedRuntimePermissions, certificates, installReason); 13250 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13251 msg.obj = params; 13252 13253 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13254 System.identityHashCode(msg.obj)); 13255 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13256 System.identityHashCode(msg.obj)); 13257 13258 mHandler.sendMessage(msg); 13259 } 13260 13261 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13262 int userId) { 13263 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13264 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13265 } 13266 13267 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13268 int appId, int... userIds) { 13269 if (ArrayUtils.isEmpty(userIds)) { 13270 return; 13271 } 13272 Bundle extras = new Bundle(1); 13273 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13274 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13275 13276 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13277 packageName, extras, 0, null, null, userIds); 13278 if (isSystem) { 13279 mHandler.post(() -> { 13280 for (int userId : userIds) { 13281 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13282 } 13283 } 13284 ); 13285 } 13286 } 13287 13288 /** 13289 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13290 * automatically without needing an explicit launch. 13291 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13292 */ 13293 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13294 // If user is not running, the app didn't miss any broadcast 13295 if (!mUserManagerInternal.isUserRunning(userId)) { 13296 return; 13297 } 13298 final IActivityManager am = ActivityManager.getService(); 13299 try { 13300 // Deliver LOCKED_BOOT_COMPLETED first 13301 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13302 .setPackage(packageName); 13303 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13304 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13305 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13306 13307 // Deliver BOOT_COMPLETED only if user is unlocked 13308 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13309 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13310 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13311 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13312 } 13313 } catch (RemoteException e) { 13314 throw e.rethrowFromSystemServer(); 13315 } 13316 } 13317 13318 @Override 13319 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13320 int userId) { 13321 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13322 PackageSetting pkgSetting; 13323 final int uid = Binder.getCallingUid(); 13324 enforceCrossUserPermission(uid, userId, 13325 true /* requireFullPermission */, true /* checkShell */, 13326 "setApplicationHiddenSetting for user " + userId); 13327 13328 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13329 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13330 return false; 13331 } 13332 13333 long callingId = Binder.clearCallingIdentity(); 13334 try { 13335 boolean sendAdded = false; 13336 boolean sendRemoved = false; 13337 // writer 13338 synchronized (mPackages) { 13339 pkgSetting = mSettings.mPackages.get(packageName); 13340 if (pkgSetting == null) { 13341 return false; 13342 } 13343 // Do not allow "android" is being disabled 13344 if ("android".equals(packageName)) { 13345 Slog.w(TAG, "Cannot hide package: android"); 13346 return false; 13347 } 13348 // Cannot hide static shared libs as they are considered 13349 // a part of the using app (emulating static linking). Also 13350 // static libs are installed always on internal storage. 13351 PackageParser.Package pkg = mPackages.get(packageName); 13352 if (pkg != null && pkg.staticSharedLibName != null) { 13353 Slog.w(TAG, "Cannot hide package: " + packageName 13354 + " providing static shared library: " 13355 + pkg.staticSharedLibName); 13356 return false; 13357 } 13358 // Only allow protected packages to hide themselves. 13359 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13360 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13361 Slog.w(TAG, "Not hiding protected package: " + packageName); 13362 return false; 13363 } 13364 13365 if (pkgSetting.getHidden(userId) != hidden) { 13366 pkgSetting.setHidden(hidden, userId); 13367 mSettings.writePackageRestrictionsLPr(userId); 13368 if (hidden) { 13369 sendRemoved = true; 13370 } else { 13371 sendAdded = true; 13372 } 13373 } 13374 } 13375 if (sendAdded) { 13376 sendPackageAddedForUser(packageName, pkgSetting, userId); 13377 return true; 13378 } 13379 if (sendRemoved) { 13380 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13381 "hiding pkg"); 13382 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13383 return true; 13384 } 13385 } finally { 13386 Binder.restoreCallingIdentity(callingId); 13387 } 13388 return false; 13389 } 13390 13391 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13392 int userId) { 13393 final PackageRemovedInfo info = new PackageRemovedInfo(); 13394 info.removedPackage = packageName; 13395 info.removedUsers = new int[] {userId}; 13396 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13397 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13398 } 13399 13400 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13401 if (pkgList.length > 0) { 13402 Bundle extras = new Bundle(1); 13403 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13404 13405 sendPackageBroadcast( 13406 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13407 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13408 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13409 new int[] {userId}); 13410 } 13411 } 13412 13413 /** 13414 * Returns true if application is not found or there was an error. Otherwise it returns 13415 * the hidden state of the package for the given user. 13416 */ 13417 @Override 13418 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13420 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13421 true /* requireFullPermission */, false /* checkShell */, 13422 "getApplicationHidden for user " + userId); 13423 PackageSetting pkgSetting; 13424 long callingId = Binder.clearCallingIdentity(); 13425 try { 13426 // writer 13427 synchronized (mPackages) { 13428 pkgSetting = mSettings.mPackages.get(packageName); 13429 if (pkgSetting == null) { 13430 return true; 13431 } 13432 return pkgSetting.getHidden(userId); 13433 } 13434 } finally { 13435 Binder.restoreCallingIdentity(callingId); 13436 } 13437 } 13438 13439 /** 13440 * @hide 13441 */ 13442 @Override 13443 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13444 int installReason) { 13445 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13446 null); 13447 PackageSetting pkgSetting; 13448 final int uid = Binder.getCallingUid(); 13449 enforceCrossUserPermission(uid, userId, 13450 true /* requireFullPermission */, true /* checkShell */, 13451 "installExistingPackage for user " + userId); 13452 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13453 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13454 } 13455 13456 long callingId = Binder.clearCallingIdentity(); 13457 try { 13458 boolean installed = false; 13459 final boolean instantApp = 13460 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13461 final boolean fullApp = 13462 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13463 13464 // writer 13465 synchronized (mPackages) { 13466 pkgSetting = mSettings.mPackages.get(packageName); 13467 if (pkgSetting == null) { 13468 return PackageManager.INSTALL_FAILED_INVALID_URI; 13469 } 13470 if (!pkgSetting.getInstalled(userId)) { 13471 pkgSetting.setInstalled(true, userId); 13472 pkgSetting.setHidden(false, userId); 13473 pkgSetting.setInstallReason(installReason, userId); 13474 mSettings.writePackageRestrictionsLPr(userId); 13475 mSettings.writeKernelMappingLPr(pkgSetting); 13476 installed = true; 13477 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13478 // upgrade app from instant to full; we don't allow app downgrade 13479 installed = true; 13480 } 13481 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13482 } 13483 13484 if (installed) { 13485 if (pkgSetting.pkg != null) { 13486 synchronized (mInstallLock) { 13487 // We don't need to freeze for a brand new install 13488 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13489 } 13490 } 13491 sendPackageAddedForUser(packageName, pkgSetting, userId); 13492 synchronized (mPackages) { 13493 updateSequenceNumberLP(packageName, new int[]{ userId }); 13494 } 13495 } 13496 } finally { 13497 Binder.restoreCallingIdentity(callingId); 13498 } 13499 13500 return PackageManager.INSTALL_SUCCEEDED; 13501 } 13502 13503 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13504 boolean instantApp, boolean fullApp) { 13505 // no state specified; do nothing 13506 if (!instantApp && !fullApp) { 13507 return; 13508 } 13509 if (userId != UserHandle.USER_ALL) { 13510 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13511 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13512 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13513 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13514 } 13515 } else { 13516 for (int currentUserId : sUserManager.getUserIds()) { 13517 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13518 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13519 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13520 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13521 } 13522 } 13523 } 13524 } 13525 13526 boolean isUserRestricted(int userId, String restrictionKey) { 13527 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13528 if (restrictions.getBoolean(restrictionKey, false)) { 13529 Log.w(TAG, "User is restricted: " + restrictionKey); 13530 return true; 13531 } 13532 return false; 13533 } 13534 13535 @Override 13536 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13537 int userId) { 13538 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13539 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13540 true /* requireFullPermission */, true /* checkShell */, 13541 "setPackagesSuspended for user " + userId); 13542 13543 if (ArrayUtils.isEmpty(packageNames)) { 13544 return packageNames; 13545 } 13546 13547 // List of package names for whom the suspended state has changed. 13548 List<String> changedPackages = new ArrayList<>(packageNames.length); 13549 // List of package names for whom the suspended state is not set as requested in this 13550 // method. 13551 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13552 long callingId = Binder.clearCallingIdentity(); 13553 try { 13554 for (int i = 0; i < packageNames.length; i++) { 13555 String packageName = packageNames[i]; 13556 boolean changed = false; 13557 final int appId; 13558 synchronized (mPackages) { 13559 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13560 if (pkgSetting == null) { 13561 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13562 + "\". Skipping suspending/un-suspending."); 13563 unactionedPackages.add(packageName); 13564 continue; 13565 } 13566 appId = pkgSetting.appId; 13567 if (pkgSetting.getSuspended(userId) != suspended) { 13568 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13569 unactionedPackages.add(packageName); 13570 continue; 13571 } 13572 pkgSetting.setSuspended(suspended, userId); 13573 mSettings.writePackageRestrictionsLPr(userId); 13574 changed = true; 13575 changedPackages.add(packageName); 13576 } 13577 } 13578 13579 if (changed && suspended) { 13580 killApplication(packageName, UserHandle.getUid(userId, appId), 13581 "suspending package"); 13582 } 13583 } 13584 } finally { 13585 Binder.restoreCallingIdentity(callingId); 13586 } 13587 13588 if (!changedPackages.isEmpty()) { 13589 sendPackagesSuspendedForUser(changedPackages.toArray( 13590 new String[changedPackages.size()]), userId, suspended); 13591 } 13592 13593 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13594 } 13595 13596 @Override 13597 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13598 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13599 true /* requireFullPermission */, false /* checkShell */, 13600 "isPackageSuspendedForUser for user " + userId); 13601 synchronized (mPackages) { 13602 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13603 if (pkgSetting == null) { 13604 throw new IllegalArgumentException("Unknown target package: " + packageName); 13605 } 13606 return pkgSetting.getSuspended(userId); 13607 } 13608 } 13609 13610 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13611 if (isPackageDeviceAdmin(packageName, userId)) { 13612 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13613 + "\": has an active device admin"); 13614 return false; 13615 } 13616 13617 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13618 if (packageName.equals(activeLauncherPackageName)) { 13619 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13620 + "\": contains the active launcher"); 13621 return false; 13622 } 13623 13624 if (packageName.equals(mRequiredInstallerPackage)) { 13625 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13626 + "\": required for package installation"); 13627 return false; 13628 } 13629 13630 if (packageName.equals(mRequiredUninstallerPackage)) { 13631 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13632 + "\": required for package uninstallation"); 13633 return false; 13634 } 13635 13636 if (packageName.equals(mRequiredVerifierPackage)) { 13637 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13638 + "\": required for package verification"); 13639 return false; 13640 } 13641 13642 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13643 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13644 + "\": is the default dialer"); 13645 return false; 13646 } 13647 13648 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13649 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13650 + "\": protected package"); 13651 return false; 13652 } 13653 13654 // Cannot suspend static shared libs as they are considered 13655 // a part of the using app (emulating static linking). Also 13656 // static libs are installed always on internal storage. 13657 PackageParser.Package pkg = mPackages.get(packageName); 13658 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13659 Slog.w(TAG, "Cannot suspend package: " + packageName 13660 + " providing static shared library: " 13661 + pkg.staticSharedLibName); 13662 return false; 13663 } 13664 13665 return true; 13666 } 13667 13668 private String getActiveLauncherPackageName(int userId) { 13669 Intent intent = new Intent(Intent.ACTION_MAIN); 13670 intent.addCategory(Intent.CATEGORY_HOME); 13671 ResolveInfo resolveInfo = resolveIntent( 13672 intent, 13673 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13674 PackageManager.MATCH_DEFAULT_ONLY, 13675 userId); 13676 13677 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13678 } 13679 13680 private String getDefaultDialerPackageName(int userId) { 13681 synchronized (mPackages) { 13682 return mSettings.getDefaultDialerPackageNameLPw(userId); 13683 } 13684 } 13685 13686 @Override 13687 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13688 mContext.enforceCallingOrSelfPermission( 13689 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13690 "Only package verification agents can verify applications"); 13691 13692 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13693 final PackageVerificationResponse response = new PackageVerificationResponse( 13694 verificationCode, Binder.getCallingUid()); 13695 msg.arg1 = id; 13696 msg.obj = response; 13697 mHandler.sendMessage(msg); 13698 } 13699 13700 @Override 13701 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13702 long millisecondsToDelay) { 13703 mContext.enforceCallingOrSelfPermission( 13704 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13705 "Only package verification agents can extend verification timeouts"); 13706 13707 final PackageVerificationState state = mPendingVerification.get(id); 13708 final PackageVerificationResponse response = new PackageVerificationResponse( 13709 verificationCodeAtTimeout, Binder.getCallingUid()); 13710 13711 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13712 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13713 } 13714 if (millisecondsToDelay < 0) { 13715 millisecondsToDelay = 0; 13716 } 13717 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13718 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13719 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13720 } 13721 13722 if ((state != null) && !state.timeoutExtended()) { 13723 state.extendTimeout(); 13724 13725 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13726 msg.arg1 = id; 13727 msg.obj = response; 13728 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13729 } 13730 } 13731 13732 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13733 int verificationCode, UserHandle user) { 13734 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13735 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13736 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13737 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13738 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13739 13740 mContext.sendBroadcastAsUser(intent, user, 13741 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13742 } 13743 13744 private ComponentName matchComponentForVerifier(String packageName, 13745 List<ResolveInfo> receivers) { 13746 ActivityInfo targetReceiver = null; 13747 13748 final int NR = receivers.size(); 13749 for (int i = 0; i < NR; i++) { 13750 final ResolveInfo info = receivers.get(i); 13751 if (info.activityInfo == null) { 13752 continue; 13753 } 13754 13755 if (packageName.equals(info.activityInfo.packageName)) { 13756 targetReceiver = info.activityInfo; 13757 break; 13758 } 13759 } 13760 13761 if (targetReceiver == null) { 13762 return null; 13763 } 13764 13765 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13766 } 13767 13768 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13769 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13770 if (pkgInfo.verifiers.length == 0) { 13771 return null; 13772 } 13773 13774 final int N = pkgInfo.verifiers.length; 13775 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13776 for (int i = 0; i < N; i++) { 13777 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13778 13779 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13780 receivers); 13781 if (comp == null) { 13782 continue; 13783 } 13784 13785 final int verifierUid = getUidForVerifier(verifierInfo); 13786 if (verifierUid == -1) { 13787 continue; 13788 } 13789 13790 if (DEBUG_VERIFY) { 13791 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13792 + " with the correct signature"); 13793 } 13794 sufficientVerifiers.add(comp); 13795 verificationState.addSufficientVerifier(verifierUid); 13796 } 13797 13798 return sufficientVerifiers; 13799 } 13800 13801 private int getUidForVerifier(VerifierInfo verifierInfo) { 13802 synchronized (mPackages) { 13803 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13804 if (pkg == null) { 13805 return -1; 13806 } else if (pkg.mSignatures.length != 1) { 13807 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13808 + " has more than one signature; ignoring"); 13809 return -1; 13810 } 13811 13812 /* 13813 * If the public key of the package's signature does not match 13814 * our expected public key, then this is a different package and 13815 * we should skip. 13816 */ 13817 13818 final byte[] expectedPublicKey; 13819 try { 13820 final Signature verifierSig = pkg.mSignatures[0]; 13821 final PublicKey publicKey = verifierSig.getPublicKey(); 13822 expectedPublicKey = publicKey.getEncoded(); 13823 } catch (CertificateException e) { 13824 return -1; 13825 } 13826 13827 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13828 13829 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13830 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13831 + " does not have the expected public key; ignoring"); 13832 return -1; 13833 } 13834 13835 return pkg.applicationInfo.uid; 13836 } 13837 } 13838 13839 @Override 13840 public void finishPackageInstall(int token, boolean didLaunch) { 13841 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13842 13843 if (DEBUG_INSTALL) { 13844 Slog.v(TAG, "BM finishing package install for " + token); 13845 } 13846 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13847 13848 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13849 mHandler.sendMessage(msg); 13850 } 13851 13852 /** 13853 * Get the verification agent timeout. 13854 * 13855 * @return verification timeout in milliseconds 13856 */ 13857 private long getVerificationTimeout() { 13858 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13859 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13860 DEFAULT_VERIFICATION_TIMEOUT); 13861 } 13862 13863 /** 13864 * Get the default verification agent response code. 13865 * 13866 * @return default verification response code 13867 */ 13868 private int getDefaultVerificationResponse() { 13869 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13870 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13871 DEFAULT_VERIFICATION_RESPONSE); 13872 } 13873 13874 /** 13875 * Check whether or not package verification has been enabled. 13876 * 13877 * @return true if verification should be performed 13878 */ 13879 private boolean isVerificationEnabled(int userId, int installFlags) { 13880 if (!DEFAULT_VERIFY_ENABLE) { 13881 return false; 13882 } 13883 13884 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13885 13886 // Check if installing from ADB 13887 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13888 // Do not run verification in a test harness environment 13889 if (ActivityManager.isRunningInTestHarness()) { 13890 return false; 13891 } 13892 if (ensureVerifyAppsEnabled) { 13893 return true; 13894 } 13895 // Check if the developer does not want package verification for ADB installs 13896 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13897 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13898 return false; 13899 } 13900 } 13901 13902 if (ensureVerifyAppsEnabled) { 13903 return true; 13904 } 13905 13906 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13907 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13908 } 13909 13910 @Override 13911 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13912 throws RemoteException { 13913 mContext.enforceCallingOrSelfPermission( 13914 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13915 "Only intentfilter verification agents can verify applications"); 13916 13917 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13918 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13919 Binder.getCallingUid(), verificationCode, failedDomains); 13920 msg.arg1 = id; 13921 msg.obj = response; 13922 mHandler.sendMessage(msg); 13923 } 13924 13925 @Override 13926 public int getIntentVerificationStatus(String packageName, int userId) { 13927 synchronized (mPackages) { 13928 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13929 } 13930 } 13931 13932 @Override 13933 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13934 mContext.enforceCallingOrSelfPermission( 13935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13936 13937 boolean result = false; 13938 synchronized (mPackages) { 13939 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13940 } 13941 if (result) { 13942 scheduleWritePackageRestrictionsLocked(userId); 13943 } 13944 return result; 13945 } 13946 13947 @Override 13948 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13949 String packageName) { 13950 synchronized (mPackages) { 13951 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13952 } 13953 } 13954 13955 @Override 13956 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13957 if (TextUtils.isEmpty(packageName)) { 13958 return ParceledListSlice.emptyList(); 13959 } 13960 synchronized (mPackages) { 13961 PackageParser.Package pkg = mPackages.get(packageName); 13962 if (pkg == null || pkg.activities == null) { 13963 return ParceledListSlice.emptyList(); 13964 } 13965 final int count = pkg.activities.size(); 13966 ArrayList<IntentFilter> result = new ArrayList<>(); 13967 for (int n=0; n<count; n++) { 13968 PackageParser.Activity activity = pkg.activities.get(n); 13969 if (activity.intents != null && activity.intents.size() > 0) { 13970 result.addAll(activity.intents); 13971 } 13972 } 13973 return new ParceledListSlice<>(result); 13974 } 13975 } 13976 13977 @Override 13978 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13979 mContext.enforceCallingOrSelfPermission( 13980 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13981 13982 synchronized (mPackages) { 13983 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13984 if (packageName != null) { 13985 result |= updateIntentVerificationStatus(packageName, 13986 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13987 userId); 13988 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13989 packageName, userId); 13990 } 13991 return result; 13992 } 13993 } 13994 13995 @Override 13996 public String getDefaultBrowserPackageName(int userId) { 13997 synchronized (mPackages) { 13998 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13999 } 14000 } 14001 14002 /** 14003 * Get the "allow unknown sources" setting. 14004 * 14005 * @return the current "allow unknown sources" setting 14006 */ 14007 private int getUnknownSourcesSettings() { 14008 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14009 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14010 -1); 14011 } 14012 14013 @Override 14014 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14015 final int uid = Binder.getCallingUid(); 14016 // writer 14017 synchronized (mPackages) { 14018 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14019 if (targetPackageSetting == null) { 14020 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14021 } 14022 14023 PackageSetting installerPackageSetting; 14024 if (installerPackageName != null) { 14025 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14026 if (installerPackageSetting == null) { 14027 throw new IllegalArgumentException("Unknown installer package: " 14028 + installerPackageName); 14029 } 14030 } else { 14031 installerPackageSetting = null; 14032 } 14033 14034 Signature[] callerSignature; 14035 Object obj = mSettings.getUserIdLPr(uid); 14036 if (obj != null) { 14037 if (obj instanceof SharedUserSetting) { 14038 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14039 } else if (obj instanceof PackageSetting) { 14040 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14041 } else { 14042 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14043 } 14044 } else { 14045 throw new SecurityException("Unknown calling UID: " + uid); 14046 } 14047 14048 // Verify: can't set installerPackageName to a package that is 14049 // not signed with the same cert as the caller. 14050 if (installerPackageSetting != null) { 14051 if (compareSignatures(callerSignature, 14052 installerPackageSetting.signatures.mSignatures) 14053 != PackageManager.SIGNATURE_MATCH) { 14054 throw new SecurityException( 14055 "Caller does not have same cert as new installer package " 14056 + installerPackageName); 14057 } 14058 } 14059 14060 // Verify: if target already has an installer package, it must 14061 // be signed with the same cert as the caller. 14062 if (targetPackageSetting.installerPackageName != null) { 14063 PackageSetting setting = mSettings.mPackages.get( 14064 targetPackageSetting.installerPackageName); 14065 // If the currently set package isn't valid, then it's always 14066 // okay to change it. 14067 if (setting != null) { 14068 if (compareSignatures(callerSignature, 14069 setting.signatures.mSignatures) 14070 != PackageManager.SIGNATURE_MATCH) { 14071 throw new SecurityException( 14072 "Caller does not have same cert as old installer package " 14073 + targetPackageSetting.installerPackageName); 14074 } 14075 } 14076 } 14077 14078 // Okay! 14079 targetPackageSetting.installerPackageName = installerPackageName; 14080 if (installerPackageName != null) { 14081 mSettings.mInstallerPackages.add(installerPackageName); 14082 } 14083 scheduleWriteSettingsLocked(); 14084 } 14085 } 14086 14087 @Override 14088 public void setApplicationCategoryHint(String packageName, int categoryHint, 14089 String callerPackageName) { 14090 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14091 callerPackageName); 14092 synchronized (mPackages) { 14093 PackageSetting ps = mSettings.mPackages.get(packageName); 14094 if (ps == null) { 14095 throw new IllegalArgumentException("Unknown target package " + packageName); 14096 } 14097 14098 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14099 throw new IllegalArgumentException("Calling package " + callerPackageName 14100 + " is not installer for " + packageName); 14101 } 14102 14103 if (ps.categoryHint != categoryHint) { 14104 ps.categoryHint = categoryHint; 14105 scheduleWriteSettingsLocked(); 14106 } 14107 } 14108 } 14109 14110 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14111 // Queue up an async operation since the package installation may take a little while. 14112 mHandler.post(new Runnable() { 14113 public void run() { 14114 mHandler.removeCallbacks(this); 14115 // Result object to be returned 14116 PackageInstalledInfo res = new PackageInstalledInfo(); 14117 res.setReturnCode(currentStatus); 14118 res.uid = -1; 14119 res.pkg = null; 14120 res.removedInfo = null; 14121 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14122 args.doPreInstall(res.returnCode); 14123 synchronized (mInstallLock) { 14124 installPackageTracedLI(args, res); 14125 } 14126 args.doPostInstall(res.returnCode, res.uid); 14127 } 14128 14129 // A restore should be performed at this point if (a) the install 14130 // succeeded, (b) the operation is not an update, and (c) the new 14131 // package has not opted out of backup participation. 14132 final boolean update = res.removedInfo != null 14133 && res.removedInfo.removedPackage != null; 14134 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14135 boolean doRestore = !update 14136 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14137 14138 // Set up the post-install work request bookkeeping. This will be used 14139 // and cleaned up by the post-install event handling regardless of whether 14140 // there's a restore pass performed. Token values are >= 1. 14141 int token; 14142 if (mNextInstallToken < 0) mNextInstallToken = 1; 14143 token = mNextInstallToken++; 14144 14145 PostInstallData data = new PostInstallData(args, res); 14146 mRunningInstalls.put(token, data); 14147 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14148 14149 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14150 // Pass responsibility to the Backup Manager. It will perform a 14151 // restore if appropriate, then pass responsibility back to the 14152 // Package Manager to run the post-install observer callbacks 14153 // and broadcasts. 14154 IBackupManager bm = IBackupManager.Stub.asInterface( 14155 ServiceManager.getService(Context.BACKUP_SERVICE)); 14156 if (bm != null) { 14157 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14158 + " to BM for possible restore"); 14159 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14160 try { 14161 // TODO: http://b/22388012 14162 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14163 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14164 } else { 14165 doRestore = false; 14166 } 14167 } catch (RemoteException e) { 14168 // can't happen; the backup manager is local 14169 } catch (Exception e) { 14170 Slog.e(TAG, "Exception trying to enqueue restore", e); 14171 doRestore = false; 14172 } 14173 } else { 14174 Slog.e(TAG, "Backup Manager not found!"); 14175 doRestore = false; 14176 } 14177 } 14178 14179 if (!doRestore) { 14180 // No restore possible, or the Backup Manager was mysteriously not 14181 // available -- just fire the post-install work request directly. 14182 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14183 14184 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14185 14186 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14187 mHandler.sendMessage(msg); 14188 } 14189 } 14190 }); 14191 } 14192 14193 /** 14194 * Callback from PackageSettings whenever an app is first transitioned out of the 14195 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14196 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14197 * here whether the app is the target of an ongoing install, and only send the 14198 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14199 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14200 * handling. 14201 */ 14202 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14203 // Serialize this with the rest of the install-process message chain. In the 14204 // restore-at-install case, this Runnable will necessarily run before the 14205 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14206 // are coherent. In the non-restore case, the app has already completed install 14207 // and been launched through some other means, so it is not in a problematic 14208 // state for observers to see the FIRST_LAUNCH signal. 14209 mHandler.post(new Runnable() { 14210 @Override 14211 public void run() { 14212 for (int i = 0; i < mRunningInstalls.size(); i++) { 14213 final PostInstallData data = mRunningInstalls.valueAt(i); 14214 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14215 continue; 14216 } 14217 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14218 // right package; but is it for the right user? 14219 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14220 if (userId == data.res.newUsers[uIndex]) { 14221 if (DEBUG_BACKUP) { 14222 Slog.i(TAG, "Package " + pkgName 14223 + " being restored so deferring FIRST_LAUNCH"); 14224 } 14225 return; 14226 } 14227 } 14228 } 14229 } 14230 // didn't find it, so not being restored 14231 if (DEBUG_BACKUP) { 14232 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14233 } 14234 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14235 } 14236 }); 14237 } 14238 14239 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14240 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14241 installerPkg, null, userIds); 14242 } 14243 14244 private abstract class HandlerParams { 14245 private static final int MAX_RETRIES = 4; 14246 14247 /** 14248 * Number of times startCopy() has been attempted and had a non-fatal 14249 * error. 14250 */ 14251 private int mRetries = 0; 14252 14253 /** User handle for the user requesting the information or installation. */ 14254 private final UserHandle mUser; 14255 String traceMethod; 14256 int traceCookie; 14257 14258 HandlerParams(UserHandle user) { 14259 mUser = user; 14260 } 14261 14262 UserHandle getUser() { 14263 return mUser; 14264 } 14265 14266 HandlerParams setTraceMethod(String traceMethod) { 14267 this.traceMethod = traceMethod; 14268 return this; 14269 } 14270 14271 HandlerParams setTraceCookie(int traceCookie) { 14272 this.traceCookie = traceCookie; 14273 return this; 14274 } 14275 14276 final boolean startCopy() { 14277 boolean res; 14278 try { 14279 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14280 14281 if (++mRetries > MAX_RETRIES) { 14282 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14283 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14284 handleServiceError(); 14285 return false; 14286 } else { 14287 handleStartCopy(); 14288 res = true; 14289 } 14290 } catch (RemoteException e) { 14291 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14292 mHandler.sendEmptyMessage(MCS_RECONNECT); 14293 res = false; 14294 } 14295 handleReturnCode(); 14296 return res; 14297 } 14298 14299 final void serviceError() { 14300 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14301 handleServiceError(); 14302 handleReturnCode(); 14303 } 14304 14305 abstract void handleStartCopy() throws RemoteException; 14306 abstract void handleServiceError(); 14307 abstract void handleReturnCode(); 14308 } 14309 14310 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14311 for (File path : paths) { 14312 try { 14313 mcs.clearDirectory(path.getAbsolutePath()); 14314 } catch (RemoteException e) { 14315 } 14316 } 14317 } 14318 14319 static class OriginInfo { 14320 /** 14321 * Location where install is coming from, before it has been 14322 * copied/renamed into place. This could be a single monolithic APK 14323 * file, or a cluster directory. This location may be untrusted. 14324 */ 14325 final File file; 14326 final String cid; 14327 14328 /** 14329 * Flag indicating that {@link #file} or {@link #cid} has already been 14330 * staged, meaning downstream users don't need to defensively copy the 14331 * contents. 14332 */ 14333 final boolean staged; 14334 14335 /** 14336 * Flag indicating that {@link #file} or {@link #cid} is an already 14337 * installed app that is being moved. 14338 */ 14339 final boolean existing; 14340 14341 final String resolvedPath; 14342 final File resolvedFile; 14343 14344 static OriginInfo fromNothing() { 14345 return new OriginInfo(null, null, false, false); 14346 } 14347 14348 static OriginInfo fromUntrustedFile(File file) { 14349 return new OriginInfo(file, null, false, false); 14350 } 14351 14352 static OriginInfo fromExistingFile(File file) { 14353 return new OriginInfo(file, null, false, true); 14354 } 14355 14356 static OriginInfo fromStagedFile(File file) { 14357 return new OriginInfo(file, null, true, false); 14358 } 14359 14360 static OriginInfo fromStagedContainer(String cid) { 14361 return new OriginInfo(null, cid, true, false); 14362 } 14363 14364 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14365 this.file = file; 14366 this.cid = cid; 14367 this.staged = staged; 14368 this.existing = existing; 14369 14370 if (cid != null) { 14371 resolvedPath = PackageHelper.getSdDir(cid); 14372 resolvedFile = new File(resolvedPath); 14373 } else if (file != null) { 14374 resolvedPath = file.getAbsolutePath(); 14375 resolvedFile = file; 14376 } else { 14377 resolvedPath = null; 14378 resolvedFile = null; 14379 } 14380 } 14381 } 14382 14383 static class MoveInfo { 14384 final int moveId; 14385 final String fromUuid; 14386 final String toUuid; 14387 final String packageName; 14388 final String dataAppName; 14389 final int appId; 14390 final String seinfo; 14391 final int targetSdkVersion; 14392 14393 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14394 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14395 this.moveId = moveId; 14396 this.fromUuid = fromUuid; 14397 this.toUuid = toUuid; 14398 this.packageName = packageName; 14399 this.dataAppName = dataAppName; 14400 this.appId = appId; 14401 this.seinfo = seinfo; 14402 this.targetSdkVersion = targetSdkVersion; 14403 } 14404 } 14405 14406 static class VerificationInfo { 14407 /** A constant used to indicate that a uid value is not present. */ 14408 public static final int NO_UID = -1; 14409 14410 /** URI referencing where the package was downloaded from. */ 14411 final Uri originatingUri; 14412 14413 /** HTTP referrer URI associated with the originatingURI. */ 14414 final Uri referrer; 14415 14416 /** UID of the application that the install request originated from. */ 14417 final int originatingUid; 14418 14419 /** UID of application requesting the install */ 14420 final int installerUid; 14421 14422 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14423 this.originatingUri = originatingUri; 14424 this.referrer = referrer; 14425 this.originatingUid = originatingUid; 14426 this.installerUid = installerUid; 14427 } 14428 } 14429 14430 class InstallParams extends HandlerParams { 14431 final OriginInfo origin; 14432 final MoveInfo move; 14433 final IPackageInstallObserver2 observer; 14434 int installFlags; 14435 final String installerPackageName; 14436 final String volumeUuid; 14437 private InstallArgs mArgs; 14438 private int mRet; 14439 final String packageAbiOverride; 14440 final String[] grantedRuntimePermissions; 14441 final VerificationInfo verificationInfo; 14442 final Certificate[][] certificates; 14443 final int installReason; 14444 14445 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14446 int installFlags, String installerPackageName, String volumeUuid, 14447 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14448 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14449 super(user); 14450 this.origin = origin; 14451 this.move = move; 14452 this.observer = observer; 14453 this.installFlags = installFlags; 14454 this.installerPackageName = installerPackageName; 14455 this.volumeUuid = volumeUuid; 14456 this.verificationInfo = verificationInfo; 14457 this.packageAbiOverride = packageAbiOverride; 14458 this.grantedRuntimePermissions = grantedPermissions; 14459 this.certificates = certificates; 14460 this.installReason = installReason; 14461 } 14462 14463 @Override 14464 public String toString() { 14465 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14466 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14467 } 14468 14469 private int installLocationPolicy(PackageInfoLite pkgLite) { 14470 String packageName = pkgLite.packageName; 14471 int installLocation = pkgLite.installLocation; 14472 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14473 // reader 14474 synchronized (mPackages) { 14475 // Currently installed package which the new package is attempting to replace or 14476 // null if no such package is installed. 14477 PackageParser.Package installedPkg = mPackages.get(packageName); 14478 // Package which currently owns the data which the new package will own if installed. 14479 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14480 // will be null whereas dataOwnerPkg will contain information about the package 14481 // which was uninstalled while keeping its data. 14482 PackageParser.Package dataOwnerPkg = installedPkg; 14483 if (dataOwnerPkg == null) { 14484 PackageSetting ps = mSettings.mPackages.get(packageName); 14485 if (ps != null) { 14486 dataOwnerPkg = ps.pkg; 14487 } 14488 } 14489 14490 if (dataOwnerPkg != null) { 14491 // If installed, the package will get access to data left on the device by its 14492 // predecessor. As a security measure, this is permited only if this is not a 14493 // version downgrade or if the predecessor package is marked as debuggable and 14494 // a downgrade is explicitly requested. 14495 // 14496 // On debuggable platform builds, downgrades are permitted even for 14497 // non-debuggable packages to make testing easier. Debuggable platform builds do 14498 // not offer security guarantees and thus it's OK to disable some security 14499 // mechanisms to make debugging/testing easier on those builds. However, even on 14500 // debuggable builds downgrades of packages are permitted only if requested via 14501 // installFlags. This is because we aim to keep the behavior of debuggable 14502 // platform builds as close as possible to the behavior of non-debuggable 14503 // platform builds. 14504 final boolean downgradeRequested = 14505 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14506 final boolean packageDebuggable = 14507 (dataOwnerPkg.applicationInfo.flags 14508 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14509 final boolean downgradePermitted = 14510 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14511 if (!downgradePermitted) { 14512 try { 14513 checkDowngrade(dataOwnerPkg, pkgLite); 14514 } catch (PackageManagerException e) { 14515 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14516 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14517 } 14518 } 14519 } 14520 14521 if (installedPkg != null) { 14522 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14523 // Check for updated system application. 14524 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14525 if (onSd) { 14526 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14527 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14528 } 14529 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14530 } else { 14531 if (onSd) { 14532 // Install flag overrides everything. 14533 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14534 } 14535 // If current upgrade specifies particular preference 14536 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14537 // Application explicitly specified internal. 14538 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14539 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14540 // App explictly prefers external. Let policy decide 14541 } else { 14542 // Prefer previous location 14543 if (isExternal(installedPkg)) { 14544 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14545 } 14546 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14547 } 14548 } 14549 } else { 14550 // Invalid install. Return error code 14551 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14552 } 14553 } 14554 } 14555 // All the special cases have been taken care of. 14556 // Return result based on recommended install location. 14557 if (onSd) { 14558 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14559 } 14560 return pkgLite.recommendedInstallLocation; 14561 } 14562 14563 /* 14564 * Invoke remote method to get package information and install 14565 * location values. Override install location based on default 14566 * policy if needed and then create install arguments based 14567 * on the install location. 14568 */ 14569 public void handleStartCopy() throws RemoteException { 14570 int ret = PackageManager.INSTALL_SUCCEEDED; 14571 14572 // If we're already staged, we've firmly committed to an install location 14573 if (origin.staged) { 14574 if (origin.file != null) { 14575 installFlags |= PackageManager.INSTALL_INTERNAL; 14576 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14577 } else if (origin.cid != null) { 14578 installFlags |= PackageManager.INSTALL_EXTERNAL; 14579 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14580 } else { 14581 throw new IllegalStateException("Invalid stage location"); 14582 } 14583 } 14584 14585 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14586 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14587 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14588 PackageInfoLite pkgLite = null; 14589 14590 if (onInt && onSd) { 14591 // Check if both bits are set. 14592 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14593 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14594 } else if (onSd && ephemeral) { 14595 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14596 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14597 } else { 14598 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14599 packageAbiOverride); 14600 14601 if (DEBUG_EPHEMERAL && ephemeral) { 14602 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14603 } 14604 14605 /* 14606 * If we have too little free space, try to free cache 14607 * before giving up. 14608 */ 14609 if (!origin.staged && pkgLite.recommendedInstallLocation 14610 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14611 // TODO: focus freeing disk space on the target device 14612 final StorageManager storage = StorageManager.from(mContext); 14613 final long lowThreshold = storage.getStorageLowBytes( 14614 Environment.getDataDirectory()); 14615 14616 final long sizeBytes = mContainerService.calculateInstalledSize( 14617 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14618 14619 try { 14620 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14621 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14622 installFlags, packageAbiOverride); 14623 } catch (InstallerException e) { 14624 Slog.w(TAG, "Failed to free cache", e); 14625 } 14626 14627 /* 14628 * The cache free must have deleted the file we 14629 * downloaded to install. 14630 * 14631 * TODO: fix the "freeCache" call to not delete 14632 * the file we care about. 14633 */ 14634 if (pkgLite.recommendedInstallLocation 14635 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14636 pkgLite.recommendedInstallLocation 14637 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14638 } 14639 } 14640 } 14641 14642 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14643 int loc = pkgLite.recommendedInstallLocation; 14644 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14645 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14646 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14647 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14648 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14649 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14650 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14651 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14652 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14653 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14654 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14655 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14656 } else { 14657 // Override with defaults if needed. 14658 loc = installLocationPolicy(pkgLite); 14659 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14660 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14661 } else if (!onSd && !onInt) { 14662 // Override install location with flags 14663 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14664 // Set the flag to install on external media. 14665 installFlags |= PackageManager.INSTALL_EXTERNAL; 14666 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14667 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14668 if (DEBUG_EPHEMERAL) { 14669 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14670 } 14671 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14672 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14673 |PackageManager.INSTALL_INTERNAL); 14674 } else { 14675 // Make sure the flag for installing on external 14676 // media is unset 14677 installFlags |= PackageManager.INSTALL_INTERNAL; 14678 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14679 } 14680 } 14681 } 14682 } 14683 14684 final InstallArgs args = createInstallArgs(this); 14685 mArgs = args; 14686 14687 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14688 // TODO: http://b/22976637 14689 // Apps installed for "all" users use the device owner to verify the app 14690 UserHandle verifierUser = getUser(); 14691 if (verifierUser == UserHandle.ALL) { 14692 verifierUser = UserHandle.SYSTEM; 14693 } 14694 14695 /* 14696 * Determine if we have any installed package verifiers. If we 14697 * do, then we'll defer to them to verify the packages. 14698 */ 14699 final int requiredUid = mRequiredVerifierPackage == null ? -1 14700 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14701 verifierUser.getIdentifier()); 14702 if (!origin.existing && requiredUid != -1 14703 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14704 final Intent verification = new Intent( 14705 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14706 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14707 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14708 PACKAGE_MIME_TYPE); 14709 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14710 14711 // Query all live verifiers based on current user state 14712 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14713 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14714 14715 if (DEBUG_VERIFY) { 14716 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14717 + verification.toString() + " with " + pkgLite.verifiers.length 14718 + " optional verifiers"); 14719 } 14720 14721 final int verificationId = mPendingVerificationToken++; 14722 14723 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14724 14725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14726 installerPackageName); 14727 14728 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14729 installFlags); 14730 14731 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14732 pkgLite.packageName); 14733 14734 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14735 pkgLite.versionCode); 14736 14737 if (verificationInfo != null) { 14738 if (verificationInfo.originatingUri != null) { 14739 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14740 verificationInfo.originatingUri); 14741 } 14742 if (verificationInfo.referrer != null) { 14743 verification.putExtra(Intent.EXTRA_REFERRER, 14744 verificationInfo.referrer); 14745 } 14746 if (verificationInfo.originatingUid >= 0) { 14747 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14748 verificationInfo.originatingUid); 14749 } 14750 if (verificationInfo.installerUid >= 0) { 14751 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14752 verificationInfo.installerUid); 14753 } 14754 } 14755 14756 final PackageVerificationState verificationState = new PackageVerificationState( 14757 requiredUid, args); 14758 14759 mPendingVerification.append(verificationId, verificationState); 14760 14761 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14762 receivers, verificationState); 14763 14764 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14765 final long idleDuration = getVerificationTimeout(); 14766 14767 /* 14768 * If any sufficient verifiers were listed in the package 14769 * manifest, attempt to ask them. 14770 */ 14771 if (sufficientVerifiers != null) { 14772 final int N = sufficientVerifiers.size(); 14773 if (N == 0) { 14774 Slog.i(TAG, "Additional verifiers required, but none installed."); 14775 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14776 } else { 14777 for (int i = 0; i < N; i++) { 14778 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14779 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14780 verifierComponent.getPackageName(), idleDuration, 14781 verifierUser.getIdentifier(), false, "package verifier"); 14782 14783 final Intent sufficientIntent = new Intent(verification); 14784 sufficientIntent.setComponent(verifierComponent); 14785 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14786 } 14787 } 14788 } 14789 14790 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14791 mRequiredVerifierPackage, receivers); 14792 if (ret == PackageManager.INSTALL_SUCCEEDED 14793 && mRequiredVerifierPackage != null) { 14794 Trace.asyncTraceBegin( 14795 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14796 /* 14797 * Send the intent to the required verification agent, 14798 * but only start the verification timeout after the 14799 * target BroadcastReceivers have run. 14800 */ 14801 verification.setComponent(requiredVerifierComponent); 14802 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14803 mRequiredVerifierPackage, idleDuration, 14804 verifierUser.getIdentifier(), false, "package verifier"); 14805 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14806 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14807 new BroadcastReceiver() { 14808 @Override 14809 public void onReceive(Context context, Intent intent) { 14810 final Message msg = mHandler 14811 .obtainMessage(CHECK_PENDING_VERIFICATION); 14812 msg.arg1 = verificationId; 14813 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14814 } 14815 }, null, 0, null, null); 14816 14817 /* 14818 * We don't want the copy to proceed until verification 14819 * succeeds, so null out this field. 14820 */ 14821 mArgs = null; 14822 } 14823 } else { 14824 /* 14825 * No package verification is enabled, so immediately start 14826 * the remote call to initiate copy using temporary file. 14827 */ 14828 ret = args.copyApk(mContainerService, true); 14829 } 14830 } 14831 14832 mRet = ret; 14833 } 14834 14835 @Override 14836 void handleReturnCode() { 14837 // If mArgs is null, then MCS couldn't be reached. When it 14838 // reconnects, it will try again to install. At that point, this 14839 // will succeed. 14840 if (mArgs != null) { 14841 processPendingInstall(mArgs, mRet); 14842 } 14843 } 14844 14845 @Override 14846 void handleServiceError() { 14847 mArgs = createInstallArgs(this); 14848 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14849 } 14850 14851 public boolean isForwardLocked() { 14852 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14853 } 14854 } 14855 14856 /** 14857 * Used during creation of InstallArgs 14858 * 14859 * @param installFlags package installation flags 14860 * @return true if should be installed on external storage 14861 */ 14862 private static boolean installOnExternalAsec(int installFlags) { 14863 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14864 return false; 14865 } 14866 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14867 return true; 14868 } 14869 return false; 14870 } 14871 14872 /** 14873 * Used during creation of InstallArgs 14874 * 14875 * @param installFlags package installation flags 14876 * @return true if should be installed as forward locked 14877 */ 14878 private static boolean installForwardLocked(int installFlags) { 14879 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14880 } 14881 14882 private InstallArgs createInstallArgs(InstallParams params) { 14883 if (params.move != null) { 14884 return new MoveInstallArgs(params); 14885 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14886 return new AsecInstallArgs(params); 14887 } else { 14888 return new FileInstallArgs(params); 14889 } 14890 } 14891 14892 /** 14893 * Create args that describe an existing installed package. Typically used 14894 * when cleaning up old installs, or used as a move source. 14895 */ 14896 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14897 String resourcePath, String[] instructionSets) { 14898 final boolean isInAsec; 14899 if (installOnExternalAsec(installFlags)) { 14900 /* Apps on SD card are always in ASEC containers. */ 14901 isInAsec = true; 14902 } else if (installForwardLocked(installFlags) 14903 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14904 /* 14905 * Forward-locked apps are only in ASEC containers if they're the 14906 * new style 14907 */ 14908 isInAsec = true; 14909 } else { 14910 isInAsec = false; 14911 } 14912 14913 if (isInAsec) { 14914 return new AsecInstallArgs(codePath, instructionSets, 14915 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14916 } else { 14917 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14918 } 14919 } 14920 14921 static abstract class InstallArgs { 14922 /** @see InstallParams#origin */ 14923 final OriginInfo origin; 14924 /** @see InstallParams#move */ 14925 final MoveInfo move; 14926 14927 final IPackageInstallObserver2 observer; 14928 // Always refers to PackageManager flags only 14929 final int installFlags; 14930 final String installerPackageName; 14931 final String volumeUuid; 14932 final UserHandle user; 14933 final String abiOverride; 14934 final String[] installGrantPermissions; 14935 /** If non-null, drop an async trace when the install completes */ 14936 final String traceMethod; 14937 final int traceCookie; 14938 final Certificate[][] certificates; 14939 final int installReason; 14940 14941 // The list of instruction sets supported by this app. This is currently 14942 // only used during the rmdex() phase to clean up resources. We can get rid of this 14943 // if we move dex files under the common app path. 14944 /* nullable */ String[] instructionSets; 14945 14946 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14947 int installFlags, String installerPackageName, String volumeUuid, 14948 UserHandle user, String[] instructionSets, 14949 String abiOverride, String[] installGrantPermissions, 14950 String traceMethod, int traceCookie, Certificate[][] certificates, 14951 int installReason) { 14952 this.origin = origin; 14953 this.move = move; 14954 this.installFlags = installFlags; 14955 this.observer = observer; 14956 this.installerPackageName = installerPackageName; 14957 this.volumeUuid = volumeUuid; 14958 this.user = user; 14959 this.instructionSets = instructionSets; 14960 this.abiOverride = abiOverride; 14961 this.installGrantPermissions = installGrantPermissions; 14962 this.traceMethod = traceMethod; 14963 this.traceCookie = traceCookie; 14964 this.certificates = certificates; 14965 this.installReason = installReason; 14966 } 14967 14968 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14969 abstract int doPreInstall(int status); 14970 14971 /** 14972 * Rename package into final resting place. All paths on the given 14973 * scanned package should be updated to reflect the rename. 14974 */ 14975 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14976 abstract int doPostInstall(int status, int uid); 14977 14978 /** @see PackageSettingBase#codePathString */ 14979 abstract String getCodePath(); 14980 /** @see PackageSettingBase#resourcePathString */ 14981 abstract String getResourcePath(); 14982 14983 // Need installer lock especially for dex file removal. 14984 abstract void cleanUpResourcesLI(); 14985 abstract boolean doPostDeleteLI(boolean delete); 14986 14987 /** 14988 * Called before the source arguments are copied. This is used mostly 14989 * for MoveParams when it needs to read the source file to put it in the 14990 * destination. 14991 */ 14992 int doPreCopy() { 14993 return PackageManager.INSTALL_SUCCEEDED; 14994 } 14995 14996 /** 14997 * Called after the source arguments are copied. This is used mostly for 14998 * MoveParams when it needs to read the source file to put it in the 14999 * destination. 15000 */ 15001 int doPostCopy(int uid) { 15002 return PackageManager.INSTALL_SUCCEEDED; 15003 } 15004 15005 protected boolean isFwdLocked() { 15006 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15007 } 15008 15009 protected boolean isExternalAsec() { 15010 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15011 } 15012 15013 protected boolean isEphemeral() { 15014 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15015 } 15016 15017 UserHandle getUser() { 15018 return user; 15019 } 15020 } 15021 15022 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15023 if (!allCodePaths.isEmpty()) { 15024 if (instructionSets == null) { 15025 throw new IllegalStateException("instructionSet == null"); 15026 } 15027 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15028 for (String codePath : allCodePaths) { 15029 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15030 try { 15031 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15032 } catch (InstallerException ignored) { 15033 } 15034 } 15035 } 15036 } 15037 } 15038 15039 /** 15040 * Logic to handle installation of non-ASEC applications, including copying 15041 * and renaming logic. 15042 */ 15043 class FileInstallArgs extends InstallArgs { 15044 private File codeFile; 15045 private File resourceFile; 15046 15047 // Example topology: 15048 // /data/app/com.example/base.apk 15049 // /data/app/com.example/split_foo.apk 15050 // /data/app/com.example/lib/arm/libfoo.so 15051 // /data/app/com.example/lib/arm64/libfoo.so 15052 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15053 15054 /** New install */ 15055 FileInstallArgs(InstallParams params) { 15056 super(params.origin, params.move, params.observer, params.installFlags, 15057 params.installerPackageName, params.volumeUuid, 15058 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15059 params.grantedRuntimePermissions, 15060 params.traceMethod, params.traceCookie, params.certificates, 15061 params.installReason); 15062 if (isFwdLocked()) { 15063 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15064 } 15065 } 15066 15067 /** Existing install */ 15068 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15069 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15070 null, null, null, 0, null /*certificates*/, 15071 PackageManager.INSTALL_REASON_UNKNOWN); 15072 this.codeFile = (codePath != null) ? new File(codePath) : null; 15073 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15074 } 15075 15076 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15077 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15078 try { 15079 return doCopyApk(imcs, temp); 15080 } finally { 15081 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15082 } 15083 } 15084 15085 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15086 if (origin.staged) { 15087 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15088 codeFile = origin.file; 15089 resourceFile = origin.file; 15090 return PackageManager.INSTALL_SUCCEEDED; 15091 } 15092 15093 try { 15094 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15095 final File tempDir = 15096 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15097 codeFile = tempDir; 15098 resourceFile = tempDir; 15099 } catch (IOException e) { 15100 Slog.w(TAG, "Failed to create copy file: " + e); 15101 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15102 } 15103 15104 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15105 @Override 15106 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15107 if (!FileUtils.isValidExtFilename(name)) { 15108 throw new IllegalArgumentException("Invalid filename: " + name); 15109 } 15110 try { 15111 final File file = new File(codeFile, name); 15112 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15113 O_RDWR | O_CREAT, 0644); 15114 Os.chmod(file.getAbsolutePath(), 0644); 15115 return new ParcelFileDescriptor(fd); 15116 } catch (ErrnoException e) { 15117 throw new RemoteException("Failed to open: " + e.getMessage()); 15118 } 15119 } 15120 }; 15121 15122 int ret = PackageManager.INSTALL_SUCCEEDED; 15123 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15124 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15125 Slog.e(TAG, "Failed to copy package"); 15126 return ret; 15127 } 15128 15129 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15130 NativeLibraryHelper.Handle handle = null; 15131 try { 15132 handle = NativeLibraryHelper.Handle.create(codeFile); 15133 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15134 abiOverride); 15135 } catch (IOException e) { 15136 Slog.e(TAG, "Copying native libraries failed", e); 15137 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15138 } finally { 15139 IoUtils.closeQuietly(handle); 15140 } 15141 15142 return ret; 15143 } 15144 15145 int doPreInstall(int status) { 15146 if (status != PackageManager.INSTALL_SUCCEEDED) { 15147 cleanUp(); 15148 } 15149 return status; 15150 } 15151 15152 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15153 if (status != PackageManager.INSTALL_SUCCEEDED) { 15154 cleanUp(); 15155 return false; 15156 } 15157 15158 final File targetDir = codeFile.getParentFile(); 15159 final File beforeCodeFile = codeFile; 15160 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15161 15162 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15163 try { 15164 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15165 } catch (ErrnoException e) { 15166 Slog.w(TAG, "Failed to rename", e); 15167 return false; 15168 } 15169 15170 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15171 Slog.w(TAG, "Failed to restorecon"); 15172 return false; 15173 } 15174 15175 // Reflect the rename internally 15176 codeFile = afterCodeFile; 15177 resourceFile = afterCodeFile; 15178 15179 // Reflect the rename in scanned details 15180 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15181 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15182 afterCodeFile, pkg.baseCodePath)); 15183 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15184 afterCodeFile, pkg.splitCodePaths)); 15185 15186 // Reflect the rename in app info 15187 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15188 pkg.setApplicationInfoCodePath(pkg.codePath); 15189 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15190 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15191 pkg.setApplicationInfoResourcePath(pkg.codePath); 15192 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15193 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15194 15195 return true; 15196 } 15197 15198 int doPostInstall(int status, int uid) { 15199 if (status != PackageManager.INSTALL_SUCCEEDED) { 15200 cleanUp(); 15201 } 15202 return status; 15203 } 15204 15205 @Override 15206 String getCodePath() { 15207 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15208 } 15209 15210 @Override 15211 String getResourcePath() { 15212 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15213 } 15214 15215 private boolean cleanUp() { 15216 if (codeFile == null || !codeFile.exists()) { 15217 return false; 15218 } 15219 15220 removeCodePathLI(codeFile); 15221 15222 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15223 resourceFile.delete(); 15224 } 15225 15226 return true; 15227 } 15228 15229 void cleanUpResourcesLI() { 15230 // Try enumerating all code paths before deleting 15231 List<String> allCodePaths = Collections.EMPTY_LIST; 15232 if (codeFile != null && codeFile.exists()) { 15233 try { 15234 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15235 allCodePaths = pkg.getAllCodePaths(); 15236 } catch (PackageParserException e) { 15237 // Ignored; we tried our best 15238 } 15239 } 15240 15241 cleanUp(); 15242 removeDexFiles(allCodePaths, instructionSets); 15243 } 15244 15245 boolean doPostDeleteLI(boolean delete) { 15246 // XXX err, shouldn't we respect the delete flag? 15247 cleanUpResourcesLI(); 15248 return true; 15249 } 15250 } 15251 15252 private boolean isAsecExternal(String cid) { 15253 final String asecPath = PackageHelper.getSdFilesystem(cid); 15254 return !asecPath.startsWith(mAsecInternalPath); 15255 } 15256 15257 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15258 PackageManagerException { 15259 if (copyRet < 0) { 15260 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15261 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15262 throw new PackageManagerException(copyRet, message); 15263 } 15264 } 15265 } 15266 15267 /** 15268 * Extract the StorageManagerService "container ID" from the full code path of an 15269 * .apk. 15270 */ 15271 static String cidFromCodePath(String fullCodePath) { 15272 int eidx = fullCodePath.lastIndexOf("/"); 15273 String subStr1 = fullCodePath.substring(0, eidx); 15274 int sidx = subStr1.lastIndexOf("/"); 15275 return subStr1.substring(sidx+1, eidx); 15276 } 15277 15278 /** 15279 * Logic to handle installation of ASEC applications, including copying and 15280 * renaming logic. 15281 */ 15282 class AsecInstallArgs extends InstallArgs { 15283 static final String RES_FILE_NAME = "pkg.apk"; 15284 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15285 15286 String cid; 15287 String packagePath; 15288 String resourcePath; 15289 15290 /** New install */ 15291 AsecInstallArgs(InstallParams params) { 15292 super(params.origin, params.move, params.observer, params.installFlags, 15293 params.installerPackageName, params.volumeUuid, 15294 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15295 params.grantedRuntimePermissions, 15296 params.traceMethod, params.traceCookie, params.certificates, 15297 params.installReason); 15298 } 15299 15300 /** Existing install */ 15301 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15302 boolean isExternal, boolean isForwardLocked) { 15303 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15304 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15305 instructionSets, null, null, null, 0, null /*certificates*/, 15306 PackageManager.INSTALL_REASON_UNKNOWN); 15307 // Hackily pretend we're still looking at a full code path 15308 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15309 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15310 } 15311 15312 // Extract cid from fullCodePath 15313 int eidx = fullCodePath.lastIndexOf("/"); 15314 String subStr1 = fullCodePath.substring(0, eidx); 15315 int sidx = subStr1.lastIndexOf("/"); 15316 cid = subStr1.substring(sidx+1, eidx); 15317 setMountPath(subStr1); 15318 } 15319 15320 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15321 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15322 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15323 instructionSets, null, null, null, 0, null /*certificates*/, 15324 PackageManager.INSTALL_REASON_UNKNOWN); 15325 this.cid = cid; 15326 setMountPath(PackageHelper.getSdDir(cid)); 15327 } 15328 15329 void createCopyFile() { 15330 cid = mInstallerService.allocateExternalStageCidLegacy(); 15331 } 15332 15333 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15334 if (origin.staged && origin.cid != null) { 15335 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15336 cid = origin.cid; 15337 setMountPath(PackageHelper.getSdDir(cid)); 15338 return PackageManager.INSTALL_SUCCEEDED; 15339 } 15340 15341 if (temp) { 15342 createCopyFile(); 15343 } else { 15344 /* 15345 * Pre-emptively destroy the container since it's destroyed if 15346 * copying fails due to it existing anyway. 15347 */ 15348 PackageHelper.destroySdDir(cid); 15349 } 15350 15351 final String newMountPath = imcs.copyPackageToContainer( 15352 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15353 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15354 15355 if (newMountPath != null) { 15356 setMountPath(newMountPath); 15357 return PackageManager.INSTALL_SUCCEEDED; 15358 } else { 15359 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15360 } 15361 } 15362 15363 @Override 15364 String getCodePath() { 15365 return packagePath; 15366 } 15367 15368 @Override 15369 String getResourcePath() { 15370 return resourcePath; 15371 } 15372 15373 int doPreInstall(int status) { 15374 if (status != PackageManager.INSTALL_SUCCEEDED) { 15375 // Destroy container 15376 PackageHelper.destroySdDir(cid); 15377 } else { 15378 boolean mounted = PackageHelper.isContainerMounted(cid); 15379 if (!mounted) { 15380 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15381 Process.SYSTEM_UID); 15382 if (newMountPath != null) { 15383 setMountPath(newMountPath); 15384 } else { 15385 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15386 } 15387 } 15388 } 15389 return status; 15390 } 15391 15392 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15393 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15394 String newMountPath = null; 15395 if (PackageHelper.isContainerMounted(cid)) { 15396 // Unmount the container 15397 if (!PackageHelper.unMountSdDir(cid)) { 15398 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15399 return false; 15400 } 15401 } 15402 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15403 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15404 " which might be stale. Will try to clean up."); 15405 // Clean up the stale container and proceed to recreate. 15406 if (!PackageHelper.destroySdDir(newCacheId)) { 15407 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15408 return false; 15409 } 15410 // Successfully cleaned up stale container. Try to rename again. 15411 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15412 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15413 + " inspite of cleaning it up."); 15414 return false; 15415 } 15416 } 15417 if (!PackageHelper.isContainerMounted(newCacheId)) { 15418 Slog.w(TAG, "Mounting container " + newCacheId); 15419 newMountPath = PackageHelper.mountSdDir(newCacheId, 15420 getEncryptKey(), Process.SYSTEM_UID); 15421 } else { 15422 newMountPath = PackageHelper.getSdDir(newCacheId); 15423 } 15424 if (newMountPath == null) { 15425 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15426 return false; 15427 } 15428 Log.i(TAG, "Succesfully renamed " + cid + 15429 " to " + newCacheId + 15430 " at new path: " + newMountPath); 15431 cid = newCacheId; 15432 15433 final File beforeCodeFile = new File(packagePath); 15434 setMountPath(newMountPath); 15435 final File afterCodeFile = new File(packagePath); 15436 15437 // Reflect the rename in scanned details 15438 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15439 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15440 afterCodeFile, pkg.baseCodePath)); 15441 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15442 afterCodeFile, pkg.splitCodePaths)); 15443 15444 // Reflect the rename in app info 15445 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15446 pkg.setApplicationInfoCodePath(pkg.codePath); 15447 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15448 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15449 pkg.setApplicationInfoResourcePath(pkg.codePath); 15450 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15451 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15452 15453 return true; 15454 } 15455 15456 private void setMountPath(String mountPath) { 15457 final File mountFile = new File(mountPath); 15458 15459 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15460 if (monolithicFile.exists()) { 15461 packagePath = monolithicFile.getAbsolutePath(); 15462 if (isFwdLocked()) { 15463 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15464 } else { 15465 resourcePath = packagePath; 15466 } 15467 } else { 15468 packagePath = mountFile.getAbsolutePath(); 15469 resourcePath = packagePath; 15470 } 15471 } 15472 15473 int doPostInstall(int status, int uid) { 15474 if (status != PackageManager.INSTALL_SUCCEEDED) { 15475 cleanUp(); 15476 } else { 15477 final int groupOwner; 15478 final String protectedFile; 15479 if (isFwdLocked()) { 15480 groupOwner = UserHandle.getSharedAppGid(uid); 15481 protectedFile = RES_FILE_NAME; 15482 } else { 15483 groupOwner = -1; 15484 protectedFile = null; 15485 } 15486 15487 if (uid < Process.FIRST_APPLICATION_UID 15488 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15489 Slog.e(TAG, "Failed to finalize " + cid); 15490 PackageHelper.destroySdDir(cid); 15491 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15492 } 15493 15494 boolean mounted = PackageHelper.isContainerMounted(cid); 15495 if (!mounted) { 15496 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15497 } 15498 } 15499 return status; 15500 } 15501 15502 private void cleanUp() { 15503 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15504 15505 // Destroy secure container 15506 PackageHelper.destroySdDir(cid); 15507 } 15508 15509 private List<String> getAllCodePaths() { 15510 final File codeFile = new File(getCodePath()); 15511 if (codeFile != null && codeFile.exists()) { 15512 try { 15513 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15514 return pkg.getAllCodePaths(); 15515 } catch (PackageParserException e) { 15516 // Ignored; we tried our best 15517 } 15518 } 15519 return Collections.EMPTY_LIST; 15520 } 15521 15522 void cleanUpResourcesLI() { 15523 // Enumerate all code paths before deleting 15524 cleanUpResourcesLI(getAllCodePaths()); 15525 } 15526 15527 private void cleanUpResourcesLI(List<String> allCodePaths) { 15528 cleanUp(); 15529 removeDexFiles(allCodePaths, instructionSets); 15530 } 15531 15532 String getPackageName() { 15533 return getAsecPackageName(cid); 15534 } 15535 15536 boolean doPostDeleteLI(boolean delete) { 15537 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15538 final List<String> allCodePaths = getAllCodePaths(); 15539 boolean mounted = PackageHelper.isContainerMounted(cid); 15540 if (mounted) { 15541 // Unmount first 15542 if (PackageHelper.unMountSdDir(cid)) { 15543 mounted = false; 15544 } 15545 } 15546 if (!mounted && delete) { 15547 cleanUpResourcesLI(allCodePaths); 15548 } 15549 return !mounted; 15550 } 15551 15552 @Override 15553 int doPreCopy() { 15554 if (isFwdLocked()) { 15555 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15556 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15557 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15558 } 15559 } 15560 15561 return PackageManager.INSTALL_SUCCEEDED; 15562 } 15563 15564 @Override 15565 int doPostCopy(int uid) { 15566 if (isFwdLocked()) { 15567 if (uid < Process.FIRST_APPLICATION_UID 15568 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15569 RES_FILE_NAME)) { 15570 Slog.e(TAG, "Failed to finalize " + cid); 15571 PackageHelper.destroySdDir(cid); 15572 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15573 } 15574 } 15575 15576 return PackageManager.INSTALL_SUCCEEDED; 15577 } 15578 } 15579 15580 /** 15581 * Logic to handle movement of existing installed applications. 15582 */ 15583 class MoveInstallArgs extends InstallArgs { 15584 private File codeFile; 15585 private File resourceFile; 15586 15587 /** New install */ 15588 MoveInstallArgs(InstallParams params) { 15589 super(params.origin, params.move, params.observer, params.installFlags, 15590 params.installerPackageName, params.volumeUuid, 15591 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15592 params.grantedRuntimePermissions, 15593 params.traceMethod, params.traceCookie, params.certificates, 15594 params.installReason); 15595 } 15596 15597 int copyApk(IMediaContainerService imcs, boolean temp) { 15598 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15599 + move.fromUuid + " to " + move.toUuid); 15600 synchronized (mInstaller) { 15601 try { 15602 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15603 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15604 } catch (InstallerException e) { 15605 Slog.w(TAG, "Failed to move app", e); 15606 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15607 } 15608 } 15609 15610 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15611 resourceFile = codeFile; 15612 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15613 15614 return PackageManager.INSTALL_SUCCEEDED; 15615 } 15616 15617 int doPreInstall(int status) { 15618 if (status != PackageManager.INSTALL_SUCCEEDED) { 15619 cleanUp(move.toUuid); 15620 } 15621 return status; 15622 } 15623 15624 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15625 if (status != PackageManager.INSTALL_SUCCEEDED) { 15626 cleanUp(move.toUuid); 15627 return false; 15628 } 15629 15630 // Reflect the move in app info 15631 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15632 pkg.setApplicationInfoCodePath(pkg.codePath); 15633 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15634 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15635 pkg.setApplicationInfoResourcePath(pkg.codePath); 15636 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15637 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15638 15639 return true; 15640 } 15641 15642 int doPostInstall(int status, int uid) { 15643 if (status == PackageManager.INSTALL_SUCCEEDED) { 15644 cleanUp(move.fromUuid); 15645 } else { 15646 cleanUp(move.toUuid); 15647 } 15648 return status; 15649 } 15650 15651 @Override 15652 String getCodePath() { 15653 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15654 } 15655 15656 @Override 15657 String getResourcePath() { 15658 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15659 } 15660 15661 private boolean cleanUp(String volumeUuid) { 15662 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15663 move.dataAppName); 15664 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15665 final int[] userIds = sUserManager.getUserIds(); 15666 synchronized (mInstallLock) { 15667 // Clean up both app data and code 15668 // All package moves are frozen until finished 15669 for (int userId : userIds) { 15670 try { 15671 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15672 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15673 } catch (InstallerException e) { 15674 Slog.w(TAG, String.valueOf(e)); 15675 } 15676 } 15677 removeCodePathLI(codeFile); 15678 } 15679 return true; 15680 } 15681 15682 void cleanUpResourcesLI() { 15683 throw new UnsupportedOperationException(); 15684 } 15685 15686 boolean doPostDeleteLI(boolean delete) { 15687 throw new UnsupportedOperationException(); 15688 } 15689 } 15690 15691 static String getAsecPackageName(String packageCid) { 15692 int idx = packageCid.lastIndexOf("-"); 15693 if (idx == -1) { 15694 return packageCid; 15695 } 15696 return packageCid.substring(0, idx); 15697 } 15698 15699 // Utility method used to create code paths based on package name and available index. 15700 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15701 String idxStr = ""; 15702 int idx = 1; 15703 // Fall back to default value of idx=1 if prefix is not 15704 // part of oldCodePath 15705 if (oldCodePath != null) { 15706 String subStr = oldCodePath; 15707 // Drop the suffix right away 15708 if (suffix != null && subStr.endsWith(suffix)) { 15709 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15710 } 15711 // If oldCodePath already contains prefix find out the 15712 // ending index to either increment or decrement. 15713 int sidx = subStr.lastIndexOf(prefix); 15714 if (sidx != -1) { 15715 subStr = subStr.substring(sidx + prefix.length()); 15716 if (subStr != null) { 15717 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15718 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15719 } 15720 try { 15721 idx = Integer.parseInt(subStr); 15722 if (idx <= 1) { 15723 idx++; 15724 } else { 15725 idx--; 15726 } 15727 } catch(NumberFormatException e) { 15728 } 15729 } 15730 } 15731 } 15732 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15733 return prefix + idxStr; 15734 } 15735 15736 private File getNextCodePath(File targetDir, String packageName) { 15737 File result; 15738 SecureRandom random = new SecureRandom(); 15739 byte[] bytes = new byte[16]; 15740 do { 15741 random.nextBytes(bytes); 15742 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15743 result = new File(targetDir, packageName + "-" + suffix); 15744 } while (result.exists()); 15745 return result; 15746 } 15747 15748 // Utility method that returns the relative package path with respect 15749 // to the installation directory. Like say for /data/data/com.test-1.apk 15750 // string com.test-1 is returned. 15751 static String deriveCodePathName(String codePath) { 15752 if (codePath == null) { 15753 return null; 15754 } 15755 final File codeFile = new File(codePath); 15756 final String name = codeFile.getName(); 15757 if (codeFile.isDirectory()) { 15758 return name; 15759 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15760 final int lastDot = name.lastIndexOf('.'); 15761 return name.substring(0, lastDot); 15762 } else { 15763 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15764 return null; 15765 } 15766 } 15767 15768 static class PackageInstalledInfo { 15769 String name; 15770 int uid; 15771 // The set of users that originally had this package installed. 15772 int[] origUsers; 15773 // The set of users that now have this package installed. 15774 int[] newUsers; 15775 PackageParser.Package pkg; 15776 int returnCode; 15777 String returnMsg; 15778 PackageRemovedInfo removedInfo; 15779 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15780 15781 public void setError(int code, String msg) { 15782 setReturnCode(code); 15783 setReturnMessage(msg); 15784 Slog.w(TAG, msg); 15785 } 15786 15787 public void setError(String msg, PackageParserException e) { 15788 setReturnCode(e.error); 15789 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15790 Slog.w(TAG, msg, e); 15791 } 15792 15793 public void setError(String msg, PackageManagerException e) { 15794 returnCode = e.error; 15795 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15796 Slog.w(TAG, msg, e); 15797 } 15798 15799 public void setReturnCode(int returnCode) { 15800 this.returnCode = returnCode; 15801 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15802 for (int i = 0; i < childCount; i++) { 15803 addedChildPackages.valueAt(i).returnCode = returnCode; 15804 } 15805 } 15806 15807 private void setReturnMessage(String returnMsg) { 15808 this.returnMsg = returnMsg; 15809 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15810 for (int i = 0; i < childCount; i++) { 15811 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15812 } 15813 } 15814 15815 // In some error cases we want to convey more info back to the observer 15816 String origPackage; 15817 String origPermission; 15818 } 15819 15820 /* 15821 * Install a non-existing package. 15822 */ 15823 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15824 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15825 PackageInstalledInfo res, int installReason) { 15826 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15827 15828 // Remember this for later, in case we need to rollback this install 15829 String pkgName = pkg.packageName; 15830 15831 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15832 15833 synchronized(mPackages) { 15834 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15835 if (renamedPackage != null) { 15836 // A package with the same name is already installed, though 15837 // it has been renamed to an older name. The package we 15838 // are trying to install should be installed as an update to 15839 // the existing one, but that has not been requested, so bail. 15840 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15841 + " without first uninstalling package running as " 15842 + renamedPackage); 15843 return; 15844 } 15845 if (mPackages.containsKey(pkgName)) { 15846 // Don't allow installation over an existing package with the same name. 15847 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15848 + " without first uninstalling."); 15849 return; 15850 } 15851 } 15852 15853 try { 15854 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15855 System.currentTimeMillis(), user); 15856 15857 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15858 15859 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15860 prepareAppDataAfterInstallLIF(newPackage); 15861 15862 } else { 15863 // Remove package from internal structures, but keep around any 15864 // data that might have already existed 15865 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15866 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15867 } 15868 } catch (PackageManagerException e) { 15869 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15870 } 15871 15872 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15873 } 15874 15875 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15876 // Can't rotate keys during boot or if sharedUser. 15877 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15878 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15879 return false; 15880 } 15881 // app is using upgradeKeySets; make sure all are valid 15882 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15883 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15884 for (int i = 0; i < upgradeKeySets.length; i++) { 15885 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15886 Slog.wtf(TAG, "Package " 15887 + (oldPs.name != null ? oldPs.name : "<null>") 15888 + " contains upgrade-key-set reference to unknown key-set: " 15889 + upgradeKeySets[i] 15890 + " reverting to signatures check."); 15891 return false; 15892 } 15893 } 15894 return true; 15895 } 15896 15897 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15898 // Upgrade keysets are being used. Determine if new package has a superset of the 15899 // required keys. 15900 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15901 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15902 for (int i = 0; i < upgradeKeySets.length; i++) { 15903 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15904 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15905 return true; 15906 } 15907 } 15908 return false; 15909 } 15910 15911 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15912 try (DigestInputStream digestStream = 15913 new DigestInputStream(new FileInputStream(file), digest)) { 15914 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15915 } 15916 } 15917 15918 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15919 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15920 int installReason) { 15921 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15922 15923 final PackageParser.Package oldPackage; 15924 final String pkgName = pkg.packageName; 15925 final int[] allUsers; 15926 final int[] installedUsers; 15927 15928 synchronized(mPackages) { 15929 oldPackage = mPackages.get(pkgName); 15930 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15931 15932 // don't allow upgrade to target a release SDK from a pre-release SDK 15933 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15934 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15935 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15936 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15937 if (oldTargetsPreRelease 15938 && !newTargetsPreRelease 15939 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15940 Slog.w(TAG, "Can't install package targeting released sdk"); 15941 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15942 return; 15943 } 15944 15945 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15946 15947 // verify signatures are valid 15948 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15949 if (!checkUpgradeKeySetLP(ps, pkg)) { 15950 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15951 "New package not signed by keys specified by upgrade-keysets: " 15952 + pkgName); 15953 return; 15954 } 15955 } else { 15956 // default to original signature matching 15957 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15958 != PackageManager.SIGNATURE_MATCH) { 15959 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15960 "New package has a different signature: " + pkgName); 15961 return; 15962 } 15963 } 15964 15965 // don't allow a system upgrade unless the upgrade hash matches 15966 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15967 byte[] digestBytes = null; 15968 try { 15969 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15970 updateDigest(digest, new File(pkg.baseCodePath)); 15971 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15972 for (String path : pkg.splitCodePaths) { 15973 updateDigest(digest, new File(path)); 15974 } 15975 } 15976 digestBytes = digest.digest(); 15977 } catch (NoSuchAlgorithmException | IOException e) { 15978 res.setError(INSTALL_FAILED_INVALID_APK, 15979 "Could not compute hash: " + pkgName); 15980 return; 15981 } 15982 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15983 res.setError(INSTALL_FAILED_INVALID_APK, 15984 "New package fails restrict-update check: " + pkgName); 15985 return; 15986 } 15987 // retain upgrade restriction 15988 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15989 } 15990 15991 // Check for shared user id changes 15992 String invalidPackageName = 15993 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15994 if (invalidPackageName != null) { 15995 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15996 "Package " + invalidPackageName + " tried to change user " 15997 + oldPackage.mSharedUserId); 15998 return; 15999 } 16000 16001 // In case of rollback, remember per-user/profile install state 16002 allUsers = sUserManager.getUserIds(); 16003 installedUsers = ps.queryInstalledUsers(allUsers, true); 16004 16005 // don't allow an upgrade from full to ephemeral 16006 if (isInstantApp) { 16007 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16008 for (int currentUser : allUsers) { 16009 if (!ps.getInstantApp(currentUser)) { 16010 // can't downgrade from full to instant 16011 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16012 + " for user: " + currentUser); 16013 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16014 return; 16015 } 16016 } 16017 } else if (!ps.getInstantApp(user.getIdentifier())) { 16018 // can't downgrade from full to instant 16019 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16020 + " for user: " + user.getIdentifier()); 16021 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16022 return; 16023 } 16024 } 16025 } 16026 16027 // Update what is removed 16028 res.removedInfo = new PackageRemovedInfo(); 16029 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16030 res.removedInfo.removedPackage = oldPackage.packageName; 16031 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16032 res.removedInfo.isUpdate = true; 16033 res.removedInfo.origUsers = installedUsers; 16034 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 16035 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16036 for (int i = 0; i < installedUsers.length; i++) { 16037 final int userId = installedUsers[i]; 16038 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16039 } 16040 16041 final int childCount = (oldPackage.childPackages != null) 16042 ? oldPackage.childPackages.size() : 0; 16043 for (int i = 0; i < childCount; i++) { 16044 boolean childPackageUpdated = false; 16045 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16046 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16047 if (res.addedChildPackages != null) { 16048 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16049 if (childRes != null) { 16050 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16051 childRes.removedInfo.removedPackage = childPkg.packageName; 16052 childRes.removedInfo.isUpdate = true; 16053 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16054 childPackageUpdated = true; 16055 } 16056 } 16057 if (!childPackageUpdated) { 16058 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16059 childRemovedRes.removedPackage = childPkg.packageName; 16060 childRemovedRes.isUpdate = false; 16061 childRemovedRes.dataRemoved = true; 16062 synchronized (mPackages) { 16063 if (childPs != null) { 16064 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16065 } 16066 } 16067 if (res.removedInfo.removedChildPackages == null) { 16068 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16069 } 16070 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16071 } 16072 } 16073 16074 boolean sysPkg = (isSystemApp(oldPackage)); 16075 if (sysPkg) { 16076 // Set the system/privileged flags as needed 16077 final boolean privileged = 16078 (oldPackage.applicationInfo.privateFlags 16079 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16080 final int systemPolicyFlags = policyFlags 16081 | PackageParser.PARSE_IS_SYSTEM 16082 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16083 16084 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16085 user, allUsers, installerPackageName, res, installReason); 16086 } else { 16087 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16088 user, allUsers, installerPackageName, res, installReason); 16089 } 16090 } 16091 16092 public List<String> getPreviousCodePaths(String packageName) { 16093 final PackageSetting ps = mSettings.mPackages.get(packageName); 16094 final List<String> result = new ArrayList<String>(); 16095 if (ps != null && ps.oldCodePaths != null) { 16096 result.addAll(ps.oldCodePaths); 16097 } 16098 return result; 16099 } 16100 16101 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16102 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16103 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16104 int installReason) { 16105 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16106 + deletedPackage); 16107 16108 String pkgName = deletedPackage.packageName; 16109 boolean deletedPkg = true; 16110 boolean addedPkg = false; 16111 boolean updatedSettings = false; 16112 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16113 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16114 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16115 16116 final long origUpdateTime = (pkg.mExtras != null) 16117 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16118 16119 // First delete the existing package while retaining the data directory 16120 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16121 res.removedInfo, true, pkg)) { 16122 // If the existing package wasn't successfully deleted 16123 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16124 deletedPkg = false; 16125 } else { 16126 // Successfully deleted the old package; proceed with replace. 16127 16128 // If deleted package lived in a container, give users a chance to 16129 // relinquish resources before killing. 16130 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16131 if (DEBUG_INSTALL) { 16132 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16133 } 16134 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16135 final ArrayList<String> pkgList = new ArrayList<String>(1); 16136 pkgList.add(deletedPackage.applicationInfo.packageName); 16137 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16138 } 16139 16140 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16141 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16142 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16143 16144 try { 16145 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16146 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16147 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16148 installReason); 16149 16150 // Update the in-memory copy of the previous code paths. 16151 PackageSetting ps = mSettings.mPackages.get(pkgName); 16152 if (!killApp) { 16153 if (ps.oldCodePaths == null) { 16154 ps.oldCodePaths = new ArraySet<>(); 16155 } 16156 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16157 if (deletedPackage.splitCodePaths != null) { 16158 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16159 } 16160 } else { 16161 ps.oldCodePaths = null; 16162 } 16163 if (ps.childPackageNames != null) { 16164 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16165 final String childPkgName = ps.childPackageNames.get(i); 16166 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16167 childPs.oldCodePaths = ps.oldCodePaths; 16168 } 16169 } 16170 // set instant app status, but, only if it's explicitly specified 16171 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16172 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16173 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16174 prepareAppDataAfterInstallLIF(newPackage); 16175 addedPkg = true; 16176 mDexManager.notifyPackageUpdated(newPackage.packageName, 16177 newPackage.baseCodePath, newPackage.splitCodePaths); 16178 } catch (PackageManagerException e) { 16179 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16180 } 16181 } 16182 16183 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16184 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16185 16186 // Revert all internal state mutations and added folders for the failed install 16187 if (addedPkg) { 16188 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16189 res.removedInfo, true, null); 16190 } 16191 16192 // Restore the old package 16193 if (deletedPkg) { 16194 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16195 File restoreFile = new File(deletedPackage.codePath); 16196 // Parse old package 16197 boolean oldExternal = isExternal(deletedPackage); 16198 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16199 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16200 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16201 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16202 try { 16203 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16204 null); 16205 } catch (PackageManagerException e) { 16206 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16207 + e.getMessage()); 16208 return; 16209 } 16210 16211 synchronized (mPackages) { 16212 // Ensure the installer package name up to date 16213 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16214 16215 // Update permissions for restored package 16216 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16217 16218 mSettings.writeLPr(); 16219 } 16220 16221 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16222 } 16223 } else { 16224 synchronized (mPackages) { 16225 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16226 if (ps != null) { 16227 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16228 if (res.removedInfo.removedChildPackages != null) { 16229 final int childCount = res.removedInfo.removedChildPackages.size(); 16230 // Iterate in reverse as we may modify the collection 16231 for (int i = childCount - 1; i >= 0; i--) { 16232 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16233 if (res.addedChildPackages.containsKey(childPackageName)) { 16234 res.removedInfo.removedChildPackages.removeAt(i); 16235 } else { 16236 PackageRemovedInfo childInfo = res.removedInfo 16237 .removedChildPackages.valueAt(i); 16238 childInfo.removedForAllUsers = mPackages.get( 16239 childInfo.removedPackage) == null; 16240 } 16241 } 16242 } 16243 } 16244 } 16245 } 16246 } 16247 16248 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16249 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16250 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16251 int installReason) { 16252 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16253 + ", old=" + deletedPackage); 16254 16255 final boolean disabledSystem; 16256 16257 // Remove existing system package 16258 removePackageLI(deletedPackage, true); 16259 16260 synchronized (mPackages) { 16261 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16262 } 16263 if (!disabledSystem) { 16264 // We didn't need to disable the .apk as a current system package, 16265 // which means we are replacing another update that is already 16266 // installed. We need to make sure to delete the older one's .apk. 16267 res.removedInfo.args = createInstallArgsForExisting(0, 16268 deletedPackage.applicationInfo.getCodePath(), 16269 deletedPackage.applicationInfo.getResourcePath(), 16270 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16271 } else { 16272 res.removedInfo.args = null; 16273 } 16274 16275 // Successfully disabled the old package. Now proceed with re-installation 16276 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16277 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16278 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16279 16280 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16281 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16282 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16283 16284 PackageParser.Package newPackage = null; 16285 try { 16286 // Add the package to the internal data structures 16287 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16288 16289 // Set the update and install times 16290 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16291 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16292 System.currentTimeMillis()); 16293 16294 // Update the package dynamic state if succeeded 16295 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16296 // Now that the install succeeded make sure we remove data 16297 // directories for any child package the update removed. 16298 final int deletedChildCount = (deletedPackage.childPackages != null) 16299 ? deletedPackage.childPackages.size() : 0; 16300 final int newChildCount = (newPackage.childPackages != null) 16301 ? newPackage.childPackages.size() : 0; 16302 for (int i = 0; i < deletedChildCount; i++) { 16303 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16304 boolean childPackageDeleted = true; 16305 for (int j = 0; j < newChildCount; j++) { 16306 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16307 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16308 childPackageDeleted = false; 16309 break; 16310 } 16311 } 16312 if (childPackageDeleted) { 16313 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16314 deletedChildPkg.packageName); 16315 if (ps != null && res.removedInfo.removedChildPackages != null) { 16316 PackageRemovedInfo removedChildRes = res.removedInfo 16317 .removedChildPackages.get(deletedChildPkg.packageName); 16318 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16319 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16320 } 16321 } 16322 } 16323 16324 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16325 installReason); 16326 prepareAppDataAfterInstallLIF(newPackage); 16327 16328 mDexManager.notifyPackageUpdated(newPackage.packageName, 16329 newPackage.baseCodePath, newPackage.splitCodePaths); 16330 } 16331 } catch (PackageManagerException e) { 16332 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16333 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16334 } 16335 16336 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16337 // Re installation failed. Restore old information 16338 // Remove new pkg information 16339 if (newPackage != null) { 16340 removeInstalledPackageLI(newPackage, true); 16341 } 16342 // Add back the old system package 16343 try { 16344 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16345 } catch (PackageManagerException e) { 16346 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16347 } 16348 16349 synchronized (mPackages) { 16350 if (disabledSystem) { 16351 enableSystemPackageLPw(deletedPackage); 16352 } 16353 16354 // Ensure the installer package name up to date 16355 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16356 16357 // Update permissions for restored package 16358 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16359 16360 mSettings.writeLPr(); 16361 } 16362 16363 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16364 + " after failed upgrade"); 16365 } 16366 } 16367 16368 /** 16369 * Checks whether the parent or any of the child packages have a change shared 16370 * user. For a package to be a valid update the shred users of the parent and 16371 * the children should match. We may later support changing child shared users. 16372 * @param oldPkg The updated package. 16373 * @param newPkg The update package. 16374 * @return The shared user that change between the versions. 16375 */ 16376 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16377 PackageParser.Package newPkg) { 16378 // Check parent shared user 16379 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16380 return newPkg.packageName; 16381 } 16382 // Check child shared users 16383 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16384 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16385 for (int i = 0; i < newChildCount; i++) { 16386 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16387 // If this child was present, did it have the same shared user? 16388 for (int j = 0; j < oldChildCount; j++) { 16389 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16390 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16391 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16392 return newChildPkg.packageName; 16393 } 16394 } 16395 } 16396 return null; 16397 } 16398 16399 private void removeNativeBinariesLI(PackageSetting ps) { 16400 // Remove the lib path for the parent package 16401 if (ps != null) { 16402 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16403 // Remove the lib path for the child packages 16404 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16405 for (int i = 0; i < childCount; i++) { 16406 PackageSetting childPs = null; 16407 synchronized (mPackages) { 16408 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16409 } 16410 if (childPs != null) { 16411 NativeLibraryHelper.removeNativeBinariesLI(childPs 16412 .legacyNativeLibraryPathString); 16413 } 16414 } 16415 } 16416 } 16417 16418 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16419 // Enable the parent package 16420 mSettings.enableSystemPackageLPw(pkg.packageName); 16421 // Enable the child packages 16422 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16423 for (int i = 0; i < childCount; i++) { 16424 PackageParser.Package childPkg = pkg.childPackages.get(i); 16425 mSettings.enableSystemPackageLPw(childPkg.packageName); 16426 } 16427 } 16428 16429 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16430 PackageParser.Package newPkg) { 16431 // Disable the parent package (parent always replaced) 16432 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16433 // Disable the child packages 16434 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16435 for (int i = 0; i < childCount; i++) { 16436 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16437 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16438 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16439 } 16440 return disabled; 16441 } 16442 16443 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16444 String installerPackageName) { 16445 // Enable the parent package 16446 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16447 // Enable the child packages 16448 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16449 for (int i = 0; i < childCount; i++) { 16450 PackageParser.Package childPkg = pkg.childPackages.get(i); 16451 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16452 } 16453 } 16454 16455 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16456 // Collect all used permissions in the UID 16457 ArraySet<String> usedPermissions = new ArraySet<>(); 16458 final int packageCount = su.packages.size(); 16459 for (int i = 0; i < packageCount; i++) { 16460 PackageSetting ps = su.packages.valueAt(i); 16461 if (ps.pkg == null) { 16462 continue; 16463 } 16464 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16465 for (int j = 0; j < requestedPermCount; j++) { 16466 String permission = ps.pkg.requestedPermissions.get(j); 16467 BasePermission bp = mSettings.mPermissions.get(permission); 16468 if (bp != null) { 16469 usedPermissions.add(permission); 16470 } 16471 } 16472 } 16473 16474 PermissionsState permissionsState = su.getPermissionsState(); 16475 // Prune install permissions 16476 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16477 final int installPermCount = installPermStates.size(); 16478 for (int i = installPermCount - 1; i >= 0; i--) { 16479 PermissionState permissionState = installPermStates.get(i); 16480 if (!usedPermissions.contains(permissionState.getName())) { 16481 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16482 if (bp != null) { 16483 permissionsState.revokeInstallPermission(bp); 16484 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16485 PackageManager.MASK_PERMISSION_FLAGS, 0); 16486 } 16487 } 16488 } 16489 16490 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16491 16492 // Prune runtime permissions 16493 for (int userId : allUserIds) { 16494 List<PermissionState> runtimePermStates = permissionsState 16495 .getRuntimePermissionStates(userId); 16496 final int runtimePermCount = runtimePermStates.size(); 16497 for (int i = runtimePermCount - 1; i >= 0; i--) { 16498 PermissionState permissionState = runtimePermStates.get(i); 16499 if (!usedPermissions.contains(permissionState.getName())) { 16500 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16501 if (bp != null) { 16502 permissionsState.revokeRuntimePermission(bp, userId); 16503 permissionsState.updatePermissionFlags(bp, userId, 16504 PackageManager.MASK_PERMISSION_FLAGS, 0); 16505 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16506 runtimePermissionChangedUserIds, userId); 16507 } 16508 } 16509 } 16510 } 16511 16512 return runtimePermissionChangedUserIds; 16513 } 16514 16515 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16516 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16517 // Update the parent package setting 16518 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16519 res, user, installReason); 16520 // Update the child packages setting 16521 final int childCount = (newPackage.childPackages != null) 16522 ? newPackage.childPackages.size() : 0; 16523 for (int i = 0; i < childCount; i++) { 16524 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16525 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16526 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16527 childRes.origUsers, childRes, user, installReason); 16528 } 16529 } 16530 16531 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16532 String installerPackageName, int[] allUsers, int[] installedForUsers, 16533 PackageInstalledInfo res, UserHandle user, int installReason) { 16534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16535 16536 String pkgName = newPackage.packageName; 16537 synchronized (mPackages) { 16538 //write settings. the installStatus will be incomplete at this stage. 16539 //note that the new package setting would have already been 16540 //added to mPackages. It hasn't been persisted yet. 16541 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16542 // TODO: Remove this write? It's also written at the end of this method 16543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16544 mSettings.writeLPr(); 16545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16546 } 16547 16548 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16549 synchronized (mPackages) { 16550 updatePermissionsLPw(newPackage.packageName, newPackage, 16551 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16552 ? UPDATE_PERMISSIONS_ALL : 0)); 16553 // For system-bundled packages, we assume that installing an upgraded version 16554 // of the package implies that the user actually wants to run that new code, 16555 // so we enable the package. 16556 PackageSetting ps = mSettings.mPackages.get(pkgName); 16557 final int userId = user.getIdentifier(); 16558 if (ps != null) { 16559 if (isSystemApp(newPackage)) { 16560 if (DEBUG_INSTALL) { 16561 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16562 } 16563 // Enable system package for requested users 16564 if (res.origUsers != null) { 16565 for (int origUserId : res.origUsers) { 16566 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16567 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16568 origUserId, installerPackageName); 16569 } 16570 } 16571 } 16572 // Also convey the prior install/uninstall state 16573 if (allUsers != null && installedForUsers != null) { 16574 for (int currentUserId : allUsers) { 16575 final boolean installed = ArrayUtils.contains( 16576 installedForUsers, currentUserId); 16577 if (DEBUG_INSTALL) { 16578 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16579 } 16580 ps.setInstalled(installed, currentUserId); 16581 } 16582 // these install state changes will be persisted in the 16583 // upcoming call to mSettings.writeLPr(). 16584 } 16585 } 16586 // It's implied that when a user requests installation, they want the app to be 16587 // installed and enabled. 16588 if (userId != UserHandle.USER_ALL) { 16589 ps.setInstalled(true, userId); 16590 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16591 } 16592 16593 // When replacing an existing package, preserve the original install reason for all 16594 // users that had the package installed before. 16595 final Set<Integer> previousUserIds = new ArraySet<>(); 16596 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16597 final int installReasonCount = res.removedInfo.installReasons.size(); 16598 for (int i = 0; i < installReasonCount; i++) { 16599 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16600 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16601 ps.setInstallReason(previousInstallReason, previousUserId); 16602 previousUserIds.add(previousUserId); 16603 } 16604 } 16605 16606 // Set install reason for users that are having the package newly installed. 16607 if (userId == UserHandle.USER_ALL) { 16608 for (int currentUserId : sUserManager.getUserIds()) { 16609 if (!previousUserIds.contains(currentUserId)) { 16610 ps.setInstallReason(installReason, currentUserId); 16611 } 16612 } 16613 } else if (!previousUserIds.contains(userId)) { 16614 ps.setInstallReason(installReason, userId); 16615 } 16616 mSettings.writeKernelMappingLPr(ps); 16617 } 16618 res.name = pkgName; 16619 res.uid = newPackage.applicationInfo.uid; 16620 res.pkg = newPackage; 16621 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16622 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16623 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16624 //to update install status 16625 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16626 mSettings.writeLPr(); 16627 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16628 } 16629 16630 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16631 } 16632 16633 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16634 try { 16635 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16636 installPackageLI(args, res); 16637 } finally { 16638 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16639 } 16640 } 16641 16642 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16643 final int installFlags = args.installFlags; 16644 final String installerPackageName = args.installerPackageName; 16645 final String volumeUuid = args.volumeUuid; 16646 final File tmpPackageFile = new File(args.getCodePath()); 16647 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16648 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16649 || (args.volumeUuid != null)); 16650 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16651 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16652 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16653 boolean replace = false; 16654 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16655 if (args.move != null) { 16656 // moving a complete application; perform an initial scan on the new install location 16657 scanFlags |= SCAN_INITIAL; 16658 } 16659 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16660 scanFlags |= SCAN_DONT_KILL_APP; 16661 } 16662 if (instantApp) { 16663 scanFlags |= SCAN_AS_INSTANT_APP; 16664 } 16665 if (fullApp) { 16666 scanFlags |= SCAN_AS_FULL_APP; 16667 } 16668 16669 // Result object to be returned 16670 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16671 16672 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16673 16674 // Sanity check 16675 if (instantApp && (forwardLocked || onExternal)) { 16676 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16677 + " external=" + onExternal); 16678 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16679 return; 16680 } 16681 16682 // Retrieve PackageSettings and parse package 16683 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16684 | PackageParser.PARSE_ENFORCE_CODE 16685 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16686 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16687 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16688 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16689 PackageParser pp = new PackageParser(); 16690 pp.setSeparateProcesses(mSeparateProcesses); 16691 pp.setDisplayMetrics(mMetrics); 16692 pp.setCallback(mPackageParserCallback); 16693 16694 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16695 final PackageParser.Package pkg; 16696 try { 16697 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16698 } catch (PackageParserException e) { 16699 res.setError("Failed parse during installPackageLI", e); 16700 return; 16701 } finally { 16702 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16703 } 16704 16705 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16706 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16707 Slog.w(TAG, "Instant app package " + pkg.packageName 16708 + " does not target O, this will be a fatal error."); 16709 // STOPSHIP: Make this a fatal error 16710 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16711 } 16712 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16713 Slog.w(TAG, "Instant app package " + pkg.packageName 16714 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16715 // STOPSHIP: Make this a fatal error 16716 pkg.applicationInfo.targetSandboxVersion = 2; 16717 } 16718 16719 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16720 // Static shared libraries have synthetic package names 16721 renameStaticSharedLibraryPackage(pkg); 16722 16723 // No static shared libs on external storage 16724 if (onExternal) { 16725 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16726 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16727 "Packages declaring static-shared libs cannot be updated"); 16728 return; 16729 } 16730 } 16731 16732 // If we are installing a clustered package add results for the children 16733 if (pkg.childPackages != null) { 16734 synchronized (mPackages) { 16735 final int childCount = pkg.childPackages.size(); 16736 for (int i = 0; i < childCount; i++) { 16737 PackageParser.Package childPkg = pkg.childPackages.get(i); 16738 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16739 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16740 childRes.pkg = childPkg; 16741 childRes.name = childPkg.packageName; 16742 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16743 if (childPs != null) { 16744 childRes.origUsers = childPs.queryInstalledUsers( 16745 sUserManager.getUserIds(), true); 16746 } 16747 if ((mPackages.containsKey(childPkg.packageName))) { 16748 childRes.removedInfo = new PackageRemovedInfo(); 16749 childRes.removedInfo.removedPackage = childPkg.packageName; 16750 } 16751 if (res.addedChildPackages == null) { 16752 res.addedChildPackages = new ArrayMap<>(); 16753 } 16754 res.addedChildPackages.put(childPkg.packageName, childRes); 16755 } 16756 } 16757 } 16758 16759 // If package doesn't declare API override, mark that we have an install 16760 // time CPU ABI override. 16761 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16762 pkg.cpuAbiOverride = args.abiOverride; 16763 } 16764 16765 String pkgName = res.name = pkg.packageName; 16766 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16767 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16768 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16769 return; 16770 } 16771 } 16772 16773 try { 16774 // either use what we've been given or parse directly from the APK 16775 if (args.certificates != null) { 16776 try { 16777 PackageParser.populateCertificates(pkg, args.certificates); 16778 } catch (PackageParserException e) { 16779 // there was something wrong with the certificates we were given; 16780 // try to pull them from the APK 16781 PackageParser.collectCertificates(pkg, parseFlags); 16782 } 16783 } else { 16784 PackageParser.collectCertificates(pkg, parseFlags); 16785 } 16786 } catch (PackageParserException e) { 16787 res.setError("Failed collect during installPackageLI", e); 16788 return; 16789 } 16790 16791 // Get rid of all references to package scan path via parser. 16792 pp = null; 16793 String oldCodePath = null; 16794 boolean systemApp = false; 16795 synchronized (mPackages) { 16796 // Check if installing already existing package 16797 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16798 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16799 if (pkg.mOriginalPackages != null 16800 && pkg.mOriginalPackages.contains(oldName) 16801 && mPackages.containsKey(oldName)) { 16802 // This package is derived from an original package, 16803 // and this device has been updating from that original 16804 // name. We must continue using the original name, so 16805 // rename the new package here. 16806 pkg.setPackageName(oldName); 16807 pkgName = pkg.packageName; 16808 replace = true; 16809 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16810 + oldName + " pkgName=" + pkgName); 16811 } else if (mPackages.containsKey(pkgName)) { 16812 // This package, under its official name, already exists 16813 // on the device; we should replace it. 16814 replace = true; 16815 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16816 } 16817 16818 // Child packages are installed through the parent package 16819 if (pkg.parentPackage != null) { 16820 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16821 "Package " + pkg.packageName + " is child of package " 16822 + pkg.parentPackage.parentPackage + ". Child packages " 16823 + "can be updated only through the parent package."); 16824 return; 16825 } 16826 16827 if (replace) { 16828 // Prevent apps opting out from runtime permissions 16829 PackageParser.Package oldPackage = mPackages.get(pkgName); 16830 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16831 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16832 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16833 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16834 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16835 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16836 + " doesn't support runtime permissions but the old" 16837 + " target SDK " + oldTargetSdk + " does."); 16838 return; 16839 } 16840 // Prevent apps from downgrading their targetSandbox. 16841 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16842 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16843 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16844 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16845 "Package " + pkg.packageName + " new target sandbox " 16846 + newTargetSandbox + " is incompatible with the previous value of" 16847 + oldTargetSandbox + "."); 16848 return; 16849 } 16850 16851 // Prevent installing of child packages 16852 if (oldPackage.parentPackage != null) { 16853 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16854 "Package " + pkg.packageName + " is child of package " 16855 + oldPackage.parentPackage + ". Child packages " 16856 + "can be updated only through the parent package."); 16857 return; 16858 } 16859 } 16860 } 16861 16862 PackageSetting ps = mSettings.mPackages.get(pkgName); 16863 if (ps != null) { 16864 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16865 16866 // Static shared libs have same package with different versions where 16867 // we internally use a synthetic package name to allow multiple versions 16868 // of the same package, therefore we need to compare signatures against 16869 // the package setting for the latest library version. 16870 PackageSetting signatureCheckPs = ps; 16871 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16872 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16873 if (libraryEntry != null) { 16874 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16875 } 16876 } 16877 16878 // Quick sanity check that we're signed correctly if updating; 16879 // we'll check this again later when scanning, but we want to 16880 // bail early here before tripping over redefined permissions. 16881 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16882 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16883 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16884 + pkg.packageName + " upgrade keys do not match the " 16885 + "previously installed version"); 16886 return; 16887 } 16888 } else { 16889 try { 16890 verifySignaturesLP(signatureCheckPs, pkg); 16891 } catch (PackageManagerException e) { 16892 res.setError(e.error, e.getMessage()); 16893 return; 16894 } 16895 } 16896 16897 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16898 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16899 systemApp = (ps.pkg.applicationInfo.flags & 16900 ApplicationInfo.FLAG_SYSTEM) != 0; 16901 } 16902 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16903 } 16904 16905 int N = pkg.permissions.size(); 16906 for (int i = N-1; i >= 0; i--) { 16907 PackageParser.Permission perm = pkg.permissions.get(i); 16908 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16909 16910 // Don't allow anyone but the platform to define ephemeral permissions. 16911 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16912 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16913 Slog.w(TAG, "Package " + pkg.packageName 16914 + " attempting to delcare ephemeral permission " 16915 + perm.info.name + "; Removing ephemeral."); 16916 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16917 } 16918 // Check whether the newly-scanned package wants to define an already-defined perm 16919 if (bp != null) { 16920 // If the defining package is signed with our cert, it's okay. This 16921 // also includes the "updating the same package" case, of course. 16922 // "updating same package" could also involve key-rotation. 16923 final boolean sigsOk; 16924 if (bp.sourcePackage.equals(pkg.packageName) 16925 && (bp.packageSetting instanceof PackageSetting) 16926 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16927 scanFlags))) { 16928 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16929 } else { 16930 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16931 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16932 } 16933 if (!sigsOk) { 16934 // If the owning package is the system itself, we log but allow 16935 // install to proceed; we fail the install on all other permission 16936 // redefinitions. 16937 if (!bp.sourcePackage.equals("android")) { 16938 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16939 + pkg.packageName + " attempting to redeclare permission " 16940 + perm.info.name + " already owned by " + bp.sourcePackage); 16941 res.origPermission = perm.info.name; 16942 res.origPackage = bp.sourcePackage; 16943 return; 16944 } else { 16945 Slog.w(TAG, "Package " + pkg.packageName 16946 + " attempting to redeclare system permission " 16947 + perm.info.name + "; ignoring new declaration"); 16948 pkg.permissions.remove(i); 16949 } 16950 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16951 // Prevent apps to change protection level to dangerous from any other 16952 // type as this would allow a privilege escalation where an app adds a 16953 // normal/signature permission in other app's group and later redefines 16954 // it as dangerous leading to the group auto-grant. 16955 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16956 == PermissionInfo.PROTECTION_DANGEROUS) { 16957 if (bp != null && !bp.isRuntime()) { 16958 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16959 + "non-runtime permission " + perm.info.name 16960 + " to runtime; keeping old protection level"); 16961 perm.info.protectionLevel = bp.protectionLevel; 16962 } 16963 } 16964 } 16965 } 16966 } 16967 } 16968 16969 if (systemApp) { 16970 if (onExternal) { 16971 // Abort update; system app can't be replaced with app on sdcard 16972 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16973 "Cannot install updates to system apps on sdcard"); 16974 return; 16975 } else if (instantApp) { 16976 // Abort update; system app can't be replaced with an instant app 16977 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16978 "Cannot update a system app with an instant app"); 16979 return; 16980 } 16981 } 16982 16983 if (args.move != null) { 16984 // We did an in-place move, so dex is ready to roll 16985 scanFlags |= SCAN_NO_DEX; 16986 scanFlags |= SCAN_MOVE; 16987 16988 synchronized (mPackages) { 16989 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16990 if (ps == null) { 16991 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16992 "Missing settings for moved package " + pkgName); 16993 } 16994 16995 // We moved the entire application as-is, so bring over the 16996 // previously derived ABI information. 16997 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16998 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16999 } 17000 17001 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17002 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17003 scanFlags |= SCAN_NO_DEX; 17004 17005 try { 17006 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17007 args.abiOverride : pkg.cpuAbiOverride); 17008 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 17009 true /*extractLibs*/, mAppLib32InstallDir); 17010 } catch (PackageManagerException pme) { 17011 Slog.e(TAG, "Error deriving application ABI", pme); 17012 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17013 return; 17014 } 17015 17016 // Shared libraries for the package need to be updated. 17017 synchronized (mPackages) { 17018 try { 17019 updateSharedLibrariesLPr(pkg, null); 17020 } catch (PackageManagerException e) { 17021 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17022 } 17023 } 17024 17025 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17026 // Do not run PackageDexOptimizer through the local performDexOpt 17027 // method because `pkg` may not be in `mPackages` yet. 17028 // 17029 // Also, don't fail application installs if the dexopt step fails. 17030 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17031 null /* instructionSets */, false /* checkProfiles */, 17032 getCompilerFilterForReason(REASON_INSTALL), 17033 getOrCreateCompilerPackageStats(pkg), 17034 mDexManager.isUsedByOtherApps(pkg.packageName)); 17035 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17036 17037 // Notify BackgroundDexOptService that the package has been changed. 17038 // If this is an update of a package which used to fail to compile, 17039 // BDOS will remove it from its blacklist. 17040 // TODO: Layering violation 17041 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17042 } 17043 17044 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17045 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17046 return; 17047 } 17048 17049 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17050 17051 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17052 "installPackageLI")) { 17053 if (replace) { 17054 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17055 // Static libs have a synthetic package name containing the version 17056 // and cannot be updated as an update would get a new package name, 17057 // unless this is the exact same version code which is useful for 17058 // development. 17059 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17060 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17061 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17062 + "static-shared libs cannot be updated"); 17063 return; 17064 } 17065 } 17066 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17067 installerPackageName, res, args.installReason); 17068 } else { 17069 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17070 args.user, installerPackageName, volumeUuid, res, args.installReason); 17071 } 17072 } 17073 17074 synchronized (mPackages) { 17075 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17076 if (ps != null) { 17077 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17078 ps.setUpdateAvailable(false /*updateAvailable*/); 17079 } 17080 17081 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17082 for (int i = 0; i < childCount; i++) { 17083 PackageParser.Package childPkg = pkg.childPackages.get(i); 17084 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17085 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17086 if (childPs != null) { 17087 childRes.newUsers = childPs.queryInstalledUsers( 17088 sUserManager.getUserIds(), true); 17089 } 17090 } 17091 17092 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17093 updateSequenceNumberLP(pkgName, res.newUsers); 17094 updateInstantAppInstallerLocked(pkgName); 17095 } 17096 } 17097 } 17098 17099 private void startIntentFilterVerifications(int userId, boolean replacing, 17100 PackageParser.Package pkg) { 17101 if (mIntentFilterVerifierComponent == null) { 17102 Slog.w(TAG, "No IntentFilter verification will not be done as " 17103 + "there is no IntentFilterVerifier available!"); 17104 return; 17105 } 17106 17107 final int verifierUid = getPackageUid( 17108 mIntentFilterVerifierComponent.getPackageName(), 17109 MATCH_DEBUG_TRIAGED_MISSING, 17110 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17111 17112 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17113 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17114 mHandler.sendMessage(msg); 17115 17116 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17117 for (int i = 0; i < childCount; i++) { 17118 PackageParser.Package childPkg = pkg.childPackages.get(i); 17119 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17120 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17121 mHandler.sendMessage(msg); 17122 } 17123 } 17124 17125 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17126 PackageParser.Package pkg) { 17127 int size = pkg.activities.size(); 17128 if (size == 0) { 17129 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17130 "No activity, so no need to verify any IntentFilter!"); 17131 return; 17132 } 17133 17134 final boolean hasDomainURLs = hasDomainURLs(pkg); 17135 if (!hasDomainURLs) { 17136 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17137 "No domain URLs, so no need to verify any IntentFilter!"); 17138 return; 17139 } 17140 17141 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17142 + " if any IntentFilter from the " + size 17143 + " Activities needs verification ..."); 17144 17145 int count = 0; 17146 final String packageName = pkg.packageName; 17147 17148 synchronized (mPackages) { 17149 // If this is a new install and we see that we've already run verification for this 17150 // package, we have nothing to do: it means the state was restored from backup. 17151 if (!replacing) { 17152 IntentFilterVerificationInfo ivi = 17153 mSettings.getIntentFilterVerificationLPr(packageName); 17154 if (ivi != null) { 17155 if (DEBUG_DOMAIN_VERIFICATION) { 17156 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17157 + ivi.getStatusString()); 17158 } 17159 return; 17160 } 17161 } 17162 17163 // If any filters need to be verified, then all need to be. 17164 boolean needToVerify = false; 17165 for (PackageParser.Activity a : pkg.activities) { 17166 for (ActivityIntentInfo filter : a.intents) { 17167 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17168 if (DEBUG_DOMAIN_VERIFICATION) { 17169 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17170 } 17171 needToVerify = true; 17172 break; 17173 } 17174 } 17175 } 17176 17177 if (needToVerify) { 17178 final int verificationId = mIntentFilterVerificationToken++; 17179 for (PackageParser.Activity a : pkg.activities) { 17180 for (ActivityIntentInfo filter : a.intents) { 17181 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17182 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17183 "Verification needed for IntentFilter:" + filter.toString()); 17184 mIntentFilterVerifier.addOneIntentFilterVerification( 17185 verifierUid, userId, verificationId, filter, packageName); 17186 count++; 17187 } 17188 } 17189 } 17190 } 17191 } 17192 17193 if (count > 0) { 17194 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17195 + " IntentFilter verification" + (count > 1 ? "s" : "") 17196 + " for userId:" + userId); 17197 mIntentFilterVerifier.startVerifications(userId); 17198 } else { 17199 if (DEBUG_DOMAIN_VERIFICATION) { 17200 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17201 } 17202 } 17203 } 17204 17205 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17206 final ComponentName cn = filter.activity.getComponentName(); 17207 final String packageName = cn.getPackageName(); 17208 17209 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17210 packageName); 17211 if (ivi == null) { 17212 return true; 17213 } 17214 int status = ivi.getStatus(); 17215 switch (status) { 17216 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17217 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17218 return true; 17219 17220 default: 17221 // Nothing to do 17222 return false; 17223 } 17224 } 17225 17226 private static boolean isMultiArch(ApplicationInfo info) { 17227 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17228 } 17229 17230 private static boolean isExternal(PackageParser.Package pkg) { 17231 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17232 } 17233 17234 private static boolean isExternal(PackageSetting ps) { 17235 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17236 } 17237 17238 private static boolean isSystemApp(PackageParser.Package pkg) { 17239 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17240 } 17241 17242 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17243 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17244 } 17245 17246 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17247 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17248 } 17249 17250 private static boolean isSystemApp(PackageSetting ps) { 17251 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17252 } 17253 17254 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17255 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17256 } 17257 17258 private int packageFlagsToInstallFlags(PackageSetting ps) { 17259 int installFlags = 0; 17260 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17261 // This existing package was an external ASEC install when we have 17262 // the external flag without a UUID 17263 installFlags |= PackageManager.INSTALL_EXTERNAL; 17264 } 17265 if (ps.isForwardLocked()) { 17266 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17267 } 17268 return installFlags; 17269 } 17270 17271 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17272 if (isExternal(pkg)) { 17273 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17274 return StorageManager.UUID_PRIMARY_PHYSICAL; 17275 } else { 17276 return pkg.volumeUuid; 17277 } 17278 } else { 17279 return StorageManager.UUID_PRIVATE_INTERNAL; 17280 } 17281 } 17282 17283 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17284 if (isExternal(pkg)) { 17285 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17286 return mSettings.getExternalVersion(); 17287 } else { 17288 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17289 } 17290 } else { 17291 return mSettings.getInternalVersion(); 17292 } 17293 } 17294 17295 private void deleteTempPackageFiles() { 17296 final FilenameFilter filter = new FilenameFilter() { 17297 public boolean accept(File dir, String name) { 17298 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17299 } 17300 }; 17301 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17302 file.delete(); 17303 } 17304 } 17305 17306 @Override 17307 public void deletePackageAsUser(String packageName, int versionCode, 17308 IPackageDeleteObserver observer, int userId, int flags) { 17309 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17310 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17311 } 17312 17313 @Override 17314 public void deletePackageVersioned(VersionedPackage versionedPackage, 17315 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17316 mContext.enforceCallingOrSelfPermission( 17317 android.Manifest.permission.DELETE_PACKAGES, null); 17318 Preconditions.checkNotNull(versionedPackage); 17319 Preconditions.checkNotNull(observer); 17320 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17321 PackageManager.VERSION_CODE_HIGHEST, 17322 Integer.MAX_VALUE, "versionCode must be >= -1"); 17323 17324 final String packageName = versionedPackage.getPackageName(); 17325 // TODO: We will change version code to long, so in the new API it is long 17326 final int versionCode = (int) versionedPackage.getVersionCode(); 17327 final String internalPackageName; 17328 synchronized (mPackages) { 17329 // Normalize package name to handle renamed packages and static libs 17330 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17331 // TODO: We will change version code to long, so in the new API it is long 17332 (int) versionedPackage.getVersionCode()); 17333 } 17334 17335 final int uid = Binder.getCallingUid(); 17336 if (!isOrphaned(internalPackageName) 17337 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17338 try { 17339 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17340 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17341 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17342 observer.onUserActionRequired(intent); 17343 } catch (RemoteException re) { 17344 } 17345 return; 17346 } 17347 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17348 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17349 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17350 mContext.enforceCallingOrSelfPermission( 17351 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17352 "deletePackage for user " + userId); 17353 } 17354 17355 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17356 try { 17357 observer.onPackageDeleted(packageName, 17358 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17359 } catch (RemoteException re) { 17360 } 17361 return; 17362 } 17363 17364 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17365 try { 17366 observer.onPackageDeleted(packageName, 17367 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17368 } catch (RemoteException re) { 17369 } 17370 return; 17371 } 17372 17373 if (DEBUG_REMOVE) { 17374 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17375 + " deleteAllUsers: " + deleteAllUsers + " version=" 17376 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17377 ? "VERSION_CODE_HIGHEST" : versionCode)); 17378 } 17379 // Queue up an async operation since the package deletion may take a little while. 17380 mHandler.post(new Runnable() { 17381 public void run() { 17382 mHandler.removeCallbacks(this); 17383 int returnCode; 17384 if (!deleteAllUsers) { 17385 returnCode = deletePackageX(internalPackageName, versionCode, 17386 userId, deleteFlags); 17387 } else { 17388 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17389 internalPackageName, users); 17390 // If nobody is blocking uninstall, proceed with delete for all users 17391 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17392 returnCode = deletePackageX(internalPackageName, versionCode, 17393 userId, deleteFlags); 17394 } else { 17395 // Otherwise uninstall individually for users with blockUninstalls=false 17396 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17397 for (int userId : users) { 17398 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17399 returnCode = deletePackageX(internalPackageName, versionCode, 17400 userId, userFlags); 17401 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17402 Slog.w(TAG, "Package delete failed for user " + userId 17403 + ", returnCode " + returnCode); 17404 } 17405 } 17406 } 17407 // The app has only been marked uninstalled for certain users. 17408 // We still need to report that delete was blocked 17409 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17410 } 17411 } 17412 try { 17413 observer.onPackageDeleted(packageName, returnCode, null); 17414 } catch (RemoteException e) { 17415 Log.i(TAG, "Observer no longer exists."); 17416 } //end catch 17417 } //end run 17418 }); 17419 } 17420 17421 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17422 if (pkg.staticSharedLibName != null) { 17423 return pkg.manifestPackageName; 17424 } 17425 return pkg.packageName; 17426 } 17427 17428 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17429 // Handle renamed packages 17430 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17431 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17432 17433 // Is this a static library? 17434 SparseArray<SharedLibraryEntry> versionedLib = 17435 mStaticLibsByDeclaringPackage.get(packageName); 17436 if (versionedLib == null || versionedLib.size() <= 0) { 17437 return packageName; 17438 } 17439 17440 // Figure out which lib versions the caller can see 17441 SparseIntArray versionsCallerCanSee = null; 17442 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17443 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17444 && callingAppId != Process.ROOT_UID) { 17445 versionsCallerCanSee = new SparseIntArray(); 17446 String libName = versionedLib.valueAt(0).info.getName(); 17447 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17448 if (uidPackages != null) { 17449 for (String uidPackage : uidPackages) { 17450 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17451 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17452 if (libIdx >= 0) { 17453 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17454 versionsCallerCanSee.append(libVersion, libVersion); 17455 } 17456 } 17457 } 17458 } 17459 17460 // Caller can see nothing - done 17461 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17462 return packageName; 17463 } 17464 17465 // Find the version the caller can see and the app version code 17466 SharedLibraryEntry highestVersion = null; 17467 final int versionCount = versionedLib.size(); 17468 for (int i = 0; i < versionCount; i++) { 17469 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17470 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17471 libEntry.info.getVersion()) < 0) { 17472 continue; 17473 } 17474 // TODO: We will change version code to long, so in the new API it is long 17475 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17476 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17477 if (libVersionCode == versionCode) { 17478 return libEntry.apk; 17479 } 17480 } else if (highestVersion == null) { 17481 highestVersion = libEntry; 17482 } else if (libVersionCode > highestVersion.info 17483 .getDeclaringPackage().getVersionCode()) { 17484 highestVersion = libEntry; 17485 } 17486 } 17487 17488 if (highestVersion != null) { 17489 return highestVersion.apk; 17490 } 17491 17492 return packageName; 17493 } 17494 17495 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17496 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17497 || callingUid == Process.SYSTEM_UID) { 17498 return true; 17499 } 17500 final int callingUserId = UserHandle.getUserId(callingUid); 17501 // If the caller installed the pkgName, then allow it to silently uninstall. 17502 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17503 return true; 17504 } 17505 17506 // Allow package verifier to silently uninstall. 17507 if (mRequiredVerifierPackage != null && 17508 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17509 return true; 17510 } 17511 17512 // Allow package uninstaller to silently uninstall. 17513 if (mRequiredUninstallerPackage != null && 17514 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17515 return true; 17516 } 17517 17518 // Allow storage manager to silently uninstall. 17519 if (mStorageManagerPackage != null && 17520 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17521 return true; 17522 } 17523 return false; 17524 } 17525 17526 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17527 int[] result = EMPTY_INT_ARRAY; 17528 for (int userId : userIds) { 17529 if (getBlockUninstallForUser(packageName, userId)) { 17530 result = ArrayUtils.appendInt(result, userId); 17531 } 17532 } 17533 return result; 17534 } 17535 17536 @Override 17537 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17538 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17539 } 17540 17541 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17542 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17543 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17544 try { 17545 if (dpm != null) { 17546 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17547 /* callingUserOnly =*/ false); 17548 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17549 : deviceOwnerComponentName.getPackageName(); 17550 // Does the package contains the device owner? 17551 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17552 // this check is probably not needed, since DO should be registered as a device 17553 // admin on some user too. (Original bug for this: b/17657954) 17554 if (packageName.equals(deviceOwnerPackageName)) { 17555 return true; 17556 } 17557 // Does it contain a device admin for any user? 17558 int[] users; 17559 if (userId == UserHandle.USER_ALL) { 17560 users = sUserManager.getUserIds(); 17561 } else { 17562 users = new int[]{userId}; 17563 } 17564 for (int i = 0; i < users.length; ++i) { 17565 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17566 return true; 17567 } 17568 } 17569 } 17570 } catch (RemoteException e) { 17571 } 17572 return false; 17573 } 17574 17575 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17576 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17577 } 17578 17579 /** 17580 * This method is an internal method that could be get invoked either 17581 * to delete an installed package or to clean up a failed installation. 17582 * After deleting an installed package, a broadcast is sent to notify any 17583 * listeners that the package has been removed. For cleaning up a failed 17584 * installation, the broadcast is not necessary since the package's 17585 * installation wouldn't have sent the initial broadcast either 17586 * The key steps in deleting a package are 17587 * deleting the package information in internal structures like mPackages, 17588 * deleting the packages base directories through installd 17589 * updating mSettings to reflect current status 17590 * persisting settings for later use 17591 * sending a broadcast if necessary 17592 */ 17593 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17594 final PackageRemovedInfo info = new PackageRemovedInfo(); 17595 final boolean res; 17596 17597 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17598 ? UserHandle.USER_ALL : userId; 17599 17600 if (isPackageDeviceAdmin(packageName, removeUser)) { 17601 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17602 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17603 } 17604 17605 PackageSetting uninstalledPs = null; 17606 PackageParser.Package pkg = null; 17607 17608 // for the uninstall-updates case and restricted profiles, remember the per- 17609 // user handle installed state 17610 int[] allUsers; 17611 synchronized (mPackages) { 17612 uninstalledPs = mSettings.mPackages.get(packageName); 17613 if (uninstalledPs == null) { 17614 Slog.w(TAG, "Not removing non-existent package " + packageName); 17615 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17616 } 17617 17618 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17619 && uninstalledPs.versionCode != versionCode) { 17620 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17621 + uninstalledPs.versionCode + " != " + versionCode); 17622 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17623 } 17624 17625 // Static shared libs can be declared by any package, so let us not 17626 // allow removing a package if it provides a lib others depend on. 17627 pkg = mPackages.get(packageName); 17628 if (pkg != null && pkg.staticSharedLibName != null) { 17629 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17630 pkg.staticSharedLibVersion); 17631 if (libEntry != null) { 17632 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17633 libEntry.info, 0, userId); 17634 if (!ArrayUtils.isEmpty(libClientPackages)) { 17635 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17636 + " hosting lib " + libEntry.info.getName() + " version " 17637 + libEntry.info.getVersion() + " used by " + libClientPackages); 17638 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17639 } 17640 } 17641 } 17642 17643 allUsers = sUserManager.getUserIds(); 17644 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17645 } 17646 17647 final int freezeUser; 17648 if (isUpdatedSystemApp(uninstalledPs) 17649 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17650 // We're downgrading a system app, which will apply to all users, so 17651 // freeze them all during the downgrade 17652 freezeUser = UserHandle.USER_ALL; 17653 } else { 17654 freezeUser = removeUser; 17655 } 17656 17657 synchronized (mInstallLock) { 17658 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17659 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17660 deleteFlags, "deletePackageX")) { 17661 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17662 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17663 } 17664 synchronized (mPackages) { 17665 if (res) { 17666 if (pkg != null) { 17667 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17668 } 17669 updateSequenceNumberLP(packageName, info.removedUsers); 17670 updateInstantAppInstallerLocked(packageName); 17671 } 17672 } 17673 } 17674 17675 if (res) { 17676 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17677 info.sendPackageRemovedBroadcasts(killApp); 17678 info.sendSystemPackageUpdatedBroadcasts(); 17679 info.sendSystemPackageAppearedBroadcasts(); 17680 } 17681 // Force a gc here. 17682 Runtime.getRuntime().gc(); 17683 // Delete the resources here after sending the broadcast to let 17684 // other processes clean up before deleting resources. 17685 if (info.args != null) { 17686 synchronized (mInstallLock) { 17687 info.args.doPostDeleteLI(true); 17688 } 17689 } 17690 17691 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17692 } 17693 17694 class PackageRemovedInfo { 17695 String removedPackage; 17696 int uid = -1; 17697 int removedAppId = -1; 17698 int[] origUsers; 17699 int[] removedUsers = null; 17700 int[] broadcastUsers = null; 17701 SparseArray<Integer> installReasons; 17702 boolean isRemovedPackageSystemUpdate = false; 17703 boolean isUpdate; 17704 boolean dataRemoved; 17705 boolean removedForAllUsers; 17706 boolean isStaticSharedLib; 17707 // Clean up resources deleted packages. 17708 InstallArgs args = null; 17709 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17710 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17711 17712 void sendPackageRemovedBroadcasts(boolean killApp) { 17713 sendPackageRemovedBroadcastInternal(killApp); 17714 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17715 for (int i = 0; i < childCount; i++) { 17716 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17717 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17718 } 17719 } 17720 17721 void sendSystemPackageUpdatedBroadcasts() { 17722 if (isRemovedPackageSystemUpdate) { 17723 sendSystemPackageUpdatedBroadcastsInternal(); 17724 final int childCount = (removedChildPackages != null) 17725 ? removedChildPackages.size() : 0; 17726 for (int i = 0; i < childCount; i++) { 17727 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17728 if (childInfo.isRemovedPackageSystemUpdate) { 17729 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17730 } 17731 } 17732 } 17733 } 17734 17735 void sendSystemPackageAppearedBroadcasts() { 17736 final int packageCount = (appearedChildPackages != null) 17737 ? appearedChildPackages.size() : 0; 17738 for (int i = 0; i < packageCount; i++) { 17739 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17740 sendPackageAddedForNewUsers(installedInfo.name, true, 17741 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17742 } 17743 } 17744 17745 private void sendSystemPackageUpdatedBroadcastsInternal() { 17746 Bundle extras = new Bundle(2); 17747 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17748 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17749 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17750 extras, 0, null, null, null); 17751 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17752 extras, 0, null, null, null); 17753 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17754 null, 0, removedPackage, null, null); 17755 } 17756 17757 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17758 // Don't send static shared library removal broadcasts as these 17759 // libs are visible only the the apps that depend on them an one 17760 // cannot remove the library if it has a dependency. 17761 if (isStaticSharedLib) { 17762 return; 17763 } 17764 Bundle extras = new Bundle(2); 17765 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17766 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17767 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17768 if (isUpdate || isRemovedPackageSystemUpdate) { 17769 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17770 } 17771 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17772 if (removedPackage != null) { 17773 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17774 extras, 0, null, null, broadcastUsers); 17775 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17776 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17777 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17778 null, null, broadcastUsers); 17779 } 17780 } 17781 if (removedAppId >= 0) { 17782 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17783 broadcastUsers); 17784 } 17785 } 17786 } 17787 17788 /* 17789 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17790 * flag is not set, the data directory is removed as well. 17791 * make sure this flag is set for partially installed apps. If not its meaningless to 17792 * delete a partially installed application. 17793 */ 17794 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17795 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17796 String packageName = ps.name; 17797 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17798 // Retrieve object to delete permissions for shared user later on 17799 final PackageParser.Package deletedPkg; 17800 final PackageSetting deletedPs; 17801 // reader 17802 synchronized (mPackages) { 17803 deletedPkg = mPackages.get(packageName); 17804 deletedPs = mSettings.mPackages.get(packageName); 17805 if (outInfo != null) { 17806 outInfo.removedPackage = packageName; 17807 outInfo.isStaticSharedLib = deletedPkg != null 17808 && deletedPkg.staticSharedLibName != null; 17809 outInfo.removedUsers = deletedPs != null 17810 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17811 : null; 17812 if (outInfo.removedUsers == null) { 17813 outInfo.broadcastUsers = null; 17814 } else { 17815 outInfo.broadcastUsers = EMPTY_INT_ARRAY; 17816 int[] allUsers = outInfo.removedUsers; 17817 for (int i = allUsers.length - 1; i >= 0; --i) { 17818 final int userId = allUsers[i]; 17819 if (deletedPs.getInstantApp(userId)) { 17820 continue; 17821 } 17822 outInfo.broadcastUsers = 17823 ArrayUtils.appendInt(outInfo.broadcastUsers, userId); 17824 } 17825 } 17826 } 17827 } 17828 17829 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17830 17831 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17832 final PackageParser.Package resolvedPkg; 17833 if (deletedPkg != null) { 17834 resolvedPkg = deletedPkg; 17835 } else { 17836 // We don't have a parsed package when it lives on an ejected 17837 // adopted storage device, so fake something together 17838 resolvedPkg = new PackageParser.Package(ps.name); 17839 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17840 } 17841 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17842 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17843 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17844 if (outInfo != null) { 17845 outInfo.dataRemoved = true; 17846 } 17847 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17848 } 17849 17850 int removedAppId = -1; 17851 17852 // writer 17853 synchronized (mPackages) { 17854 boolean installedStateChanged = false; 17855 if (deletedPs != null) { 17856 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17857 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17858 clearDefaultBrowserIfNeeded(packageName); 17859 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17860 removedAppId = mSettings.removePackageLPw(packageName); 17861 if (outInfo != null) { 17862 outInfo.removedAppId = removedAppId; 17863 } 17864 updatePermissionsLPw(deletedPs.name, null, 0); 17865 if (deletedPs.sharedUser != null) { 17866 // Remove permissions associated with package. Since runtime 17867 // permissions are per user we have to kill the removed package 17868 // or packages running under the shared user of the removed 17869 // package if revoking the permissions requested only by the removed 17870 // package is successful and this causes a change in gids. 17871 for (int userId : UserManagerService.getInstance().getUserIds()) { 17872 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17873 userId); 17874 if (userIdToKill == UserHandle.USER_ALL 17875 || userIdToKill >= UserHandle.USER_SYSTEM) { 17876 // If gids changed for this user, kill all affected packages. 17877 mHandler.post(new Runnable() { 17878 @Override 17879 public void run() { 17880 // This has to happen with no lock held. 17881 killApplication(deletedPs.name, deletedPs.appId, 17882 KILL_APP_REASON_GIDS_CHANGED); 17883 } 17884 }); 17885 break; 17886 } 17887 } 17888 } 17889 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17890 } 17891 // make sure to preserve per-user disabled state if this removal was just 17892 // a downgrade of a system app to the factory package 17893 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17894 if (DEBUG_REMOVE) { 17895 Slog.d(TAG, "Propagating install state across downgrade"); 17896 } 17897 for (int userId : allUserHandles) { 17898 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17899 if (DEBUG_REMOVE) { 17900 Slog.d(TAG, " user " + userId + " => " + installed); 17901 } 17902 if (installed != ps.getInstalled(userId)) { 17903 installedStateChanged = true; 17904 } 17905 ps.setInstalled(installed, userId); 17906 } 17907 } 17908 } 17909 // can downgrade to reader 17910 if (writeSettings) { 17911 // Save settings now 17912 mSettings.writeLPr(); 17913 } 17914 if (installedStateChanged) { 17915 mSettings.writeKernelMappingLPr(ps); 17916 } 17917 } 17918 if (removedAppId != -1) { 17919 // A user ID was deleted here. Go through all users and remove it 17920 // from KeyStore. 17921 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17922 } 17923 } 17924 17925 static boolean locationIsPrivileged(File path) { 17926 try { 17927 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17928 .getCanonicalPath(); 17929 return path.getCanonicalPath().startsWith(privilegedAppDir); 17930 } catch (IOException e) { 17931 Slog.e(TAG, "Unable to access code path " + path); 17932 } 17933 return false; 17934 } 17935 17936 /* 17937 * Tries to delete system package. 17938 */ 17939 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17940 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17941 boolean writeSettings) { 17942 if (deletedPs.parentPackageName != null) { 17943 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17944 return false; 17945 } 17946 17947 final boolean applyUserRestrictions 17948 = (allUserHandles != null) && (outInfo.origUsers != null); 17949 final PackageSetting disabledPs; 17950 // Confirm if the system package has been updated 17951 // An updated system app can be deleted. This will also have to restore 17952 // the system pkg from system partition 17953 // reader 17954 synchronized (mPackages) { 17955 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17956 } 17957 17958 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17959 + " disabledPs=" + disabledPs); 17960 17961 if (disabledPs == null) { 17962 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17963 return false; 17964 } else if (DEBUG_REMOVE) { 17965 Slog.d(TAG, "Deleting system pkg from data partition"); 17966 } 17967 17968 if (DEBUG_REMOVE) { 17969 if (applyUserRestrictions) { 17970 Slog.d(TAG, "Remembering install states:"); 17971 for (int userId : allUserHandles) { 17972 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17973 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17974 } 17975 } 17976 } 17977 17978 // Delete the updated package 17979 outInfo.isRemovedPackageSystemUpdate = true; 17980 if (outInfo.removedChildPackages != null) { 17981 final int childCount = (deletedPs.childPackageNames != null) 17982 ? deletedPs.childPackageNames.size() : 0; 17983 for (int i = 0; i < childCount; i++) { 17984 String childPackageName = deletedPs.childPackageNames.get(i); 17985 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17986 .contains(childPackageName)) { 17987 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17988 childPackageName); 17989 if (childInfo != null) { 17990 childInfo.isRemovedPackageSystemUpdate = true; 17991 } 17992 } 17993 } 17994 } 17995 17996 if (disabledPs.versionCode < deletedPs.versionCode) { 17997 // Delete data for downgrades 17998 flags &= ~PackageManager.DELETE_KEEP_DATA; 17999 } else { 18000 // Preserve data by setting flag 18001 flags |= PackageManager.DELETE_KEEP_DATA; 18002 } 18003 18004 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18005 outInfo, writeSettings, disabledPs.pkg); 18006 if (!ret) { 18007 return false; 18008 } 18009 18010 // writer 18011 synchronized (mPackages) { 18012 // Reinstate the old system package 18013 enableSystemPackageLPw(disabledPs.pkg); 18014 // Remove any native libraries from the upgraded package. 18015 removeNativeBinariesLI(deletedPs); 18016 } 18017 18018 // Install the system package 18019 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18020 int parseFlags = mDefParseFlags 18021 | PackageParser.PARSE_MUST_BE_APK 18022 | PackageParser.PARSE_IS_SYSTEM 18023 | PackageParser.PARSE_IS_SYSTEM_DIR; 18024 if (locationIsPrivileged(disabledPs.codePath)) { 18025 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18026 } 18027 18028 final PackageParser.Package newPkg; 18029 try { 18030 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18031 0 /* currentTime */, null); 18032 } catch (PackageManagerException e) { 18033 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18034 + e.getMessage()); 18035 return false; 18036 } 18037 18038 try { 18039 // update shared libraries for the newly re-installed system package 18040 updateSharedLibrariesLPr(newPkg, null); 18041 } catch (PackageManagerException e) { 18042 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18043 } 18044 18045 prepareAppDataAfterInstallLIF(newPkg); 18046 18047 // writer 18048 synchronized (mPackages) { 18049 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18050 18051 // Propagate the permissions state as we do not want to drop on the floor 18052 // runtime permissions. The update permissions method below will take 18053 // care of removing obsolete permissions and grant install permissions. 18054 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18055 updatePermissionsLPw(newPkg.packageName, newPkg, 18056 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18057 18058 if (applyUserRestrictions) { 18059 boolean installedStateChanged = false; 18060 if (DEBUG_REMOVE) { 18061 Slog.d(TAG, "Propagating install state across reinstall"); 18062 } 18063 for (int userId : allUserHandles) { 18064 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18065 if (DEBUG_REMOVE) { 18066 Slog.d(TAG, " user " + userId + " => " + installed); 18067 } 18068 if (installed != ps.getInstalled(userId)) { 18069 installedStateChanged = true; 18070 } 18071 ps.setInstalled(installed, userId); 18072 18073 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18074 } 18075 // Regardless of writeSettings we need to ensure that this restriction 18076 // state propagation is persisted 18077 mSettings.writeAllUsersPackageRestrictionsLPr(); 18078 if (installedStateChanged) { 18079 mSettings.writeKernelMappingLPr(ps); 18080 } 18081 } 18082 // can downgrade to reader here 18083 if (writeSettings) { 18084 mSettings.writeLPr(); 18085 } 18086 } 18087 return true; 18088 } 18089 18090 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18091 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18092 PackageRemovedInfo outInfo, boolean writeSettings, 18093 PackageParser.Package replacingPackage) { 18094 synchronized (mPackages) { 18095 if (outInfo != null) { 18096 outInfo.uid = ps.appId; 18097 } 18098 18099 if (outInfo != null && outInfo.removedChildPackages != null) { 18100 final int childCount = (ps.childPackageNames != null) 18101 ? ps.childPackageNames.size() : 0; 18102 for (int i = 0; i < childCount; i++) { 18103 String childPackageName = ps.childPackageNames.get(i); 18104 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18105 if (childPs == null) { 18106 return false; 18107 } 18108 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18109 childPackageName); 18110 if (childInfo != null) { 18111 childInfo.uid = childPs.appId; 18112 } 18113 } 18114 } 18115 } 18116 18117 // Delete package data from internal structures and also remove data if flag is set 18118 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18119 18120 // Delete the child packages data 18121 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18122 for (int i = 0; i < childCount; i++) { 18123 PackageSetting childPs; 18124 synchronized (mPackages) { 18125 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18126 } 18127 if (childPs != null) { 18128 PackageRemovedInfo childOutInfo = (outInfo != null 18129 && outInfo.removedChildPackages != null) 18130 ? outInfo.removedChildPackages.get(childPs.name) : null; 18131 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18132 && (replacingPackage != null 18133 && !replacingPackage.hasChildPackage(childPs.name)) 18134 ? flags & ~DELETE_KEEP_DATA : flags; 18135 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18136 deleteFlags, writeSettings); 18137 } 18138 } 18139 18140 // Delete application code and resources only for parent packages 18141 if (ps.parentPackageName == null) { 18142 if (deleteCodeAndResources && (outInfo != null)) { 18143 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18144 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18145 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18146 } 18147 } 18148 18149 return true; 18150 } 18151 18152 @Override 18153 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18154 int userId) { 18155 mContext.enforceCallingOrSelfPermission( 18156 android.Manifest.permission.DELETE_PACKAGES, null); 18157 synchronized (mPackages) { 18158 PackageSetting ps = mSettings.mPackages.get(packageName); 18159 if (ps == null) { 18160 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18161 return false; 18162 } 18163 // Cannot block uninstall of static shared libs as they are 18164 // considered a part of the using app (emulating static linking). 18165 // Also static libs are installed always on internal storage. 18166 PackageParser.Package pkg = mPackages.get(packageName); 18167 if (pkg != null && pkg.staticSharedLibName != null) { 18168 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18169 + " providing static shared library: " + pkg.staticSharedLibName); 18170 return false; 18171 } 18172 if (!ps.getInstalled(userId)) { 18173 // Can't block uninstall for an app that is not installed or enabled. 18174 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18175 return false; 18176 } 18177 ps.setBlockUninstall(blockUninstall, userId); 18178 mSettings.writePackageRestrictionsLPr(userId); 18179 } 18180 return true; 18181 } 18182 18183 @Override 18184 public boolean getBlockUninstallForUser(String packageName, int userId) { 18185 synchronized (mPackages) { 18186 PackageSetting ps = mSettings.mPackages.get(packageName); 18187 if (ps == null) { 18188 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18189 return false; 18190 } 18191 return ps.getBlockUninstall(userId); 18192 } 18193 } 18194 18195 @Override 18196 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18197 int callingUid = Binder.getCallingUid(); 18198 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18199 throw new SecurityException( 18200 "setRequiredForSystemUser can only be run by the system or root"); 18201 } 18202 synchronized (mPackages) { 18203 PackageSetting ps = mSettings.mPackages.get(packageName); 18204 if (ps == null) { 18205 Log.w(TAG, "Package doesn't exist: " + packageName); 18206 return false; 18207 } 18208 if (systemUserApp) { 18209 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18210 } else { 18211 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18212 } 18213 mSettings.writeLPr(); 18214 } 18215 return true; 18216 } 18217 18218 /* 18219 * This method handles package deletion in general 18220 */ 18221 private boolean deletePackageLIF(String packageName, UserHandle user, 18222 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18223 PackageRemovedInfo outInfo, boolean writeSettings, 18224 PackageParser.Package replacingPackage) { 18225 if (packageName == null) { 18226 Slog.w(TAG, "Attempt to delete null packageName."); 18227 return false; 18228 } 18229 18230 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18231 18232 PackageSetting ps; 18233 synchronized (mPackages) { 18234 ps = mSettings.mPackages.get(packageName); 18235 if (ps == null) { 18236 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18237 return false; 18238 } 18239 18240 if (ps.parentPackageName != null && (!isSystemApp(ps) 18241 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18242 if (DEBUG_REMOVE) { 18243 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18244 + ((user == null) ? UserHandle.USER_ALL : user)); 18245 } 18246 final int removedUserId = (user != null) ? user.getIdentifier() 18247 : UserHandle.USER_ALL; 18248 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18249 return false; 18250 } 18251 markPackageUninstalledForUserLPw(ps, user); 18252 scheduleWritePackageRestrictionsLocked(user); 18253 return true; 18254 } 18255 } 18256 18257 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18258 && user.getIdentifier() != UserHandle.USER_ALL)) { 18259 // The caller is asking that the package only be deleted for a single 18260 // user. To do this, we just mark its uninstalled state and delete 18261 // its data. If this is a system app, we only allow this to happen if 18262 // they have set the special DELETE_SYSTEM_APP which requests different 18263 // semantics than normal for uninstalling system apps. 18264 markPackageUninstalledForUserLPw(ps, user); 18265 18266 if (!isSystemApp(ps)) { 18267 // Do not uninstall the APK if an app should be cached 18268 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18269 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18270 // Other user still have this package installed, so all 18271 // we need to do is clear this user's data and save that 18272 // it is uninstalled. 18273 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18274 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18275 return false; 18276 } 18277 scheduleWritePackageRestrictionsLocked(user); 18278 return true; 18279 } else { 18280 // We need to set it back to 'installed' so the uninstall 18281 // broadcasts will be sent correctly. 18282 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18283 ps.setInstalled(true, user.getIdentifier()); 18284 mSettings.writeKernelMappingLPr(ps); 18285 } 18286 } else { 18287 // This is a system app, so we assume that the 18288 // other users still have this package installed, so all 18289 // we need to do is clear this user's data and save that 18290 // it is uninstalled. 18291 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18292 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18293 return false; 18294 } 18295 scheduleWritePackageRestrictionsLocked(user); 18296 return true; 18297 } 18298 } 18299 18300 // If we are deleting a composite package for all users, keep track 18301 // of result for each child. 18302 if (ps.childPackageNames != null && outInfo != null) { 18303 synchronized (mPackages) { 18304 final int childCount = ps.childPackageNames.size(); 18305 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18306 for (int i = 0; i < childCount; i++) { 18307 String childPackageName = ps.childPackageNames.get(i); 18308 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18309 childInfo.removedPackage = childPackageName; 18310 outInfo.removedChildPackages.put(childPackageName, childInfo); 18311 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18312 if (childPs != null) { 18313 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18314 } 18315 } 18316 } 18317 } 18318 18319 boolean ret = false; 18320 if (isSystemApp(ps)) { 18321 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18322 // When an updated system application is deleted we delete the existing resources 18323 // as well and fall back to existing code in system partition 18324 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18325 } else { 18326 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18327 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18328 outInfo, writeSettings, replacingPackage); 18329 } 18330 18331 // Take a note whether we deleted the package for all users 18332 if (outInfo != null) { 18333 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18334 if (outInfo.removedChildPackages != null) { 18335 synchronized (mPackages) { 18336 final int childCount = outInfo.removedChildPackages.size(); 18337 for (int i = 0; i < childCount; i++) { 18338 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18339 if (childInfo != null) { 18340 childInfo.removedForAllUsers = mPackages.get( 18341 childInfo.removedPackage) == null; 18342 } 18343 } 18344 } 18345 } 18346 // If we uninstalled an update to a system app there may be some 18347 // child packages that appeared as they are declared in the system 18348 // app but were not declared in the update. 18349 if (isSystemApp(ps)) { 18350 synchronized (mPackages) { 18351 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18352 final int childCount = (updatedPs.childPackageNames != null) 18353 ? updatedPs.childPackageNames.size() : 0; 18354 for (int i = 0; i < childCount; i++) { 18355 String childPackageName = updatedPs.childPackageNames.get(i); 18356 if (outInfo.removedChildPackages == null 18357 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18358 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18359 if (childPs == null) { 18360 continue; 18361 } 18362 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18363 installRes.name = childPackageName; 18364 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18365 installRes.pkg = mPackages.get(childPackageName); 18366 installRes.uid = childPs.pkg.applicationInfo.uid; 18367 if (outInfo.appearedChildPackages == null) { 18368 outInfo.appearedChildPackages = new ArrayMap<>(); 18369 } 18370 outInfo.appearedChildPackages.put(childPackageName, installRes); 18371 } 18372 } 18373 } 18374 } 18375 } 18376 18377 return ret; 18378 } 18379 18380 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18381 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18382 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18383 for (int nextUserId : userIds) { 18384 if (DEBUG_REMOVE) { 18385 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18386 } 18387 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18388 false /*installed*/, 18389 true /*stopped*/, 18390 true /*notLaunched*/, 18391 false /*hidden*/, 18392 false /*suspended*/, 18393 false /*instantApp*/, 18394 null /*lastDisableAppCaller*/, 18395 null /*enabledComponents*/, 18396 null /*disabledComponents*/, 18397 false /*blockUninstall*/, 18398 ps.readUserState(nextUserId).domainVerificationStatus, 18399 0, PackageManager.INSTALL_REASON_UNKNOWN); 18400 } 18401 mSettings.writeKernelMappingLPr(ps); 18402 } 18403 18404 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18405 PackageRemovedInfo outInfo) { 18406 final PackageParser.Package pkg; 18407 synchronized (mPackages) { 18408 pkg = mPackages.get(ps.name); 18409 } 18410 18411 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18412 : new int[] {userId}; 18413 for (int nextUserId : userIds) { 18414 if (DEBUG_REMOVE) { 18415 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18416 + nextUserId); 18417 } 18418 18419 destroyAppDataLIF(pkg, userId, 18420 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18421 destroyAppProfilesLIF(pkg, userId); 18422 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18423 schedulePackageCleaning(ps.name, nextUserId, false); 18424 synchronized (mPackages) { 18425 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18426 scheduleWritePackageRestrictionsLocked(nextUserId); 18427 } 18428 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18429 } 18430 } 18431 18432 if (outInfo != null) { 18433 outInfo.removedPackage = ps.name; 18434 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18435 outInfo.removedAppId = ps.appId; 18436 outInfo.removedUsers = userIds; 18437 } 18438 18439 return true; 18440 } 18441 18442 private final class ClearStorageConnection implements ServiceConnection { 18443 IMediaContainerService mContainerService; 18444 18445 @Override 18446 public void onServiceConnected(ComponentName name, IBinder service) { 18447 synchronized (this) { 18448 mContainerService = IMediaContainerService.Stub 18449 .asInterface(Binder.allowBlocking(service)); 18450 notifyAll(); 18451 } 18452 } 18453 18454 @Override 18455 public void onServiceDisconnected(ComponentName name) { 18456 } 18457 } 18458 18459 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18460 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18461 18462 final boolean mounted; 18463 if (Environment.isExternalStorageEmulated()) { 18464 mounted = true; 18465 } else { 18466 final String status = Environment.getExternalStorageState(); 18467 18468 mounted = status.equals(Environment.MEDIA_MOUNTED) 18469 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18470 } 18471 18472 if (!mounted) { 18473 return; 18474 } 18475 18476 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18477 int[] users; 18478 if (userId == UserHandle.USER_ALL) { 18479 users = sUserManager.getUserIds(); 18480 } else { 18481 users = new int[] { userId }; 18482 } 18483 final ClearStorageConnection conn = new ClearStorageConnection(); 18484 if (mContext.bindServiceAsUser( 18485 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18486 try { 18487 for (int curUser : users) { 18488 long timeout = SystemClock.uptimeMillis() + 5000; 18489 synchronized (conn) { 18490 long now; 18491 while (conn.mContainerService == null && 18492 (now = SystemClock.uptimeMillis()) < timeout) { 18493 try { 18494 conn.wait(timeout - now); 18495 } catch (InterruptedException e) { 18496 } 18497 } 18498 } 18499 if (conn.mContainerService == null) { 18500 return; 18501 } 18502 18503 final UserEnvironment userEnv = new UserEnvironment(curUser); 18504 clearDirectory(conn.mContainerService, 18505 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18506 if (allData) { 18507 clearDirectory(conn.mContainerService, 18508 userEnv.buildExternalStorageAppDataDirs(packageName)); 18509 clearDirectory(conn.mContainerService, 18510 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18511 } 18512 } 18513 } finally { 18514 mContext.unbindService(conn); 18515 } 18516 } 18517 } 18518 18519 @Override 18520 public void clearApplicationProfileData(String packageName) { 18521 enforceSystemOrRoot("Only the system can clear all profile data"); 18522 18523 final PackageParser.Package pkg; 18524 synchronized (mPackages) { 18525 pkg = mPackages.get(packageName); 18526 } 18527 18528 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18529 synchronized (mInstallLock) { 18530 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18531 } 18532 } 18533 } 18534 18535 @Override 18536 public void clearApplicationUserData(final String packageName, 18537 final IPackageDataObserver observer, final int userId) { 18538 mContext.enforceCallingOrSelfPermission( 18539 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18540 18541 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18542 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18543 18544 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18545 throw new SecurityException("Cannot clear data for a protected package: " 18546 + packageName); 18547 } 18548 // Queue up an async operation since the package deletion may take a little while. 18549 mHandler.post(new Runnable() { 18550 public void run() { 18551 mHandler.removeCallbacks(this); 18552 final boolean succeeded; 18553 try (PackageFreezer freezer = freezePackage(packageName, 18554 "clearApplicationUserData")) { 18555 synchronized (mInstallLock) { 18556 succeeded = clearApplicationUserDataLIF(packageName, userId); 18557 } 18558 clearExternalStorageDataSync(packageName, userId, true); 18559 synchronized (mPackages) { 18560 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18561 packageName, userId); 18562 } 18563 } 18564 if (succeeded) { 18565 // invoke DeviceStorageMonitor's update method to clear any notifications 18566 DeviceStorageMonitorInternal dsm = LocalServices 18567 .getService(DeviceStorageMonitorInternal.class); 18568 if (dsm != null) { 18569 dsm.checkMemory(); 18570 } 18571 } 18572 if(observer != null) { 18573 try { 18574 observer.onRemoveCompleted(packageName, succeeded); 18575 } catch (RemoteException e) { 18576 Log.i(TAG, "Observer no longer exists."); 18577 } 18578 } //end if observer 18579 } //end run 18580 }); 18581 } 18582 18583 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18584 if (packageName == null) { 18585 Slog.w(TAG, "Attempt to delete null packageName."); 18586 return false; 18587 } 18588 18589 // Try finding details about the requested package 18590 PackageParser.Package pkg; 18591 synchronized (mPackages) { 18592 pkg = mPackages.get(packageName); 18593 if (pkg == null) { 18594 final PackageSetting ps = mSettings.mPackages.get(packageName); 18595 if (ps != null) { 18596 pkg = ps.pkg; 18597 } 18598 } 18599 18600 if (pkg == null) { 18601 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18602 return false; 18603 } 18604 18605 PackageSetting ps = (PackageSetting) pkg.mExtras; 18606 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18607 } 18608 18609 clearAppDataLIF(pkg, userId, 18610 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18611 18612 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18613 removeKeystoreDataIfNeeded(userId, appId); 18614 18615 UserManagerInternal umInternal = getUserManagerInternal(); 18616 final int flags; 18617 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18618 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18619 } else if (umInternal.isUserRunning(userId)) { 18620 flags = StorageManager.FLAG_STORAGE_DE; 18621 } else { 18622 flags = 0; 18623 } 18624 prepareAppDataContentsLIF(pkg, userId, flags); 18625 18626 return true; 18627 } 18628 18629 /** 18630 * Reverts user permission state changes (permissions and flags) in 18631 * all packages for a given user. 18632 * 18633 * @param userId The device user for which to do a reset. 18634 */ 18635 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18636 final int packageCount = mPackages.size(); 18637 for (int i = 0; i < packageCount; i++) { 18638 PackageParser.Package pkg = mPackages.valueAt(i); 18639 PackageSetting ps = (PackageSetting) pkg.mExtras; 18640 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18641 } 18642 } 18643 18644 private void resetNetworkPolicies(int userId) { 18645 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18646 } 18647 18648 /** 18649 * Reverts user permission state changes (permissions and flags). 18650 * 18651 * @param ps The package for which to reset. 18652 * @param userId The device user for which to do a reset. 18653 */ 18654 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18655 final PackageSetting ps, final int userId) { 18656 if (ps.pkg == null) { 18657 return; 18658 } 18659 18660 // These are flags that can change base on user actions. 18661 final int userSettableMask = FLAG_PERMISSION_USER_SET 18662 | FLAG_PERMISSION_USER_FIXED 18663 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18664 | FLAG_PERMISSION_REVIEW_REQUIRED; 18665 18666 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18667 | FLAG_PERMISSION_POLICY_FIXED; 18668 18669 boolean writeInstallPermissions = false; 18670 boolean writeRuntimePermissions = false; 18671 18672 final int permissionCount = ps.pkg.requestedPermissions.size(); 18673 for (int i = 0; i < permissionCount; i++) { 18674 String permission = ps.pkg.requestedPermissions.get(i); 18675 18676 BasePermission bp = mSettings.mPermissions.get(permission); 18677 if (bp == null) { 18678 continue; 18679 } 18680 18681 // If shared user we just reset the state to which only this app contributed. 18682 if (ps.sharedUser != null) { 18683 boolean used = false; 18684 final int packageCount = ps.sharedUser.packages.size(); 18685 for (int j = 0; j < packageCount; j++) { 18686 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18687 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18688 && pkg.pkg.requestedPermissions.contains(permission)) { 18689 used = true; 18690 break; 18691 } 18692 } 18693 if (used) { 18694 continue; 18695 } 18696 } 18697 18698 PermissionsState permissionsState = ps.getPermissionsState(); 18699 18700 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18701 18702 // Always clear the user settable flags. 18703 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18704 bp.name) != null; 18705 // If permission review is enabled and this is a legacy app, mark the 18706 // permission as requiring a review as this is the initial state. 18707 int flags = 0; 18708 if (mPermissionReviewRequired 18709 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18710 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18711 } 18712 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18713 if (hasInstallState) { 18714 writeInstallPermissions = true; 18715 } else { 18716 writeRuntimePermissions = true; 18717 } 18718 } 18719 18720 // Below is only runtime permission handling. 18721 if (!bp.isRuntime()) { 18722 continue; 18723 } 18724 18725 // Never clobber system or policy. 18726 if ((oldFlags & policyOrSystemFlags) != 0) { 18727 continue; 18728 } 18729 18730 // If this permission was granted by default, make sure it is. 18731 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18732 if (permissionsState.grantRuntimePermission(bp, userId) 18733 != PERMISSION_OPERATION_FAILURE) { 18734 writeRuntimePermissions = true; 18735 } 18736 // If permission review is enabled the permissions for a legacy apps 18737 // are represented as constantly granted runtime ones, so don't revoke. 18738 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18739 // Otherwise, reset the permission. 18740 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18741 switch (revokeResult) { 18742 case PERMISSION_OPERATION_SUCCESS: 18743 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18744 writeRuntimePermissions = true; 18745 final int appId = ps.appId; 18746 mHandler.post(new Runnable() { 18747 @Override 18748 public void run() { 18749 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18750 } 18751 }); 18752 } break; 18753 } 18754 } 18755 } 18756 18757 // Synchronously write as we are taking permissions away. 18758 if (writeRuntimePermissions) { 18759 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18760 } 18761 18762 // Synchronously write as we are taking permissions away. 18763 if (writeInstallPermissions) { 18764 mSettings.writeLPr(); 18765 } 18766 } 18767 18768 /** 18769 * Remove entries from the keystore daemon. Will only remove it if the 18770 * {@code appId} is valid. 18771 */ 18772 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18773 if (appId < 0) { 18774 return; 18775 } 18776 18777 final KeyStore keyStore = KeyStore.getInstance(); 18778 if (keyStore != null) { 18779 if (userId == UserHandle.USER_ALL) { 18780 for (final int individual : sUserManager.getUserIds()) { 18781 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18782 } 18783 } else { 18784 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18785 } 18786 } else { 18787 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18788 } 18789 } 18790 18791 @Override 18792 public void deleteApplicationCacheFiles(final String packageName, 18793 final IPackageDataObserver observer) { 18794 final int userId = UserHandle.getCallingUserId(); 18795 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18796 } 18797 18798 @Override 18799 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18800 final IPackageDataObserver observer) { 18801 mContext.enforceCallingOrSelfPermission( 18802 android.Manifest.permission.DELETE_CACHE_FILES, null); 18803 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18804 /* requireFullPermission= */ true, /* checkShell= */ false, 18805 "delete application cache files"); 18806 18807 final PackageParser.Package pkg; 18808 synchronized (mPackages) { 18809 pkg = mPackages.get(packageName); 18810 } 18811 18812 // Queue up an async operation since the package deletion may take a little while. 18813 mHandler.post(new Runnable() { 18814 public void run() { 18815 synchronized (mInstallLock) { 18816 final int flags = StorageManager.FLAG_STORAGE_DE 18817 | StorageManager.FLAG_STORAGE_CE; 18818 // We're only clearing cache files, so we don't care if the 18819 // app is unfrozen and still able to run 18820 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18821 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18822 } 18823 clearExternalStorageDataSync(packageName, userId, false); 18824 if (observer != null) { 18825 try { 18826 observer.onRemoveCompleted(packageName, true); 18827 } catch (RemoteException e) { 18828 Log.i(TAG, "Observer no longer exists."); 18829 } 18830 } 18831 } 18832 }); 18833 } 18834 18835 @Override 18836 public void getPackageSizeInfo(final String packageName, int userHandle, 18837 final IPackageStatsObserver observer) { 18838 throw new UnsupportedOperationException( 18839 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18840 } 18841 18842 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18843 final PackageSetting ps; 18844 synchronized (mPackages) { 18845 ps = mSettings.mPackages.get(packageName); 18846 if (ps == null) { 18847 Slog.w(TAG, "Failed to find settings for " + packageName); 18848 return false; 18849 } 18850 } 18851 18852 final String[] packageNames = { packageName }; 18853 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18854 final String[] codePaths = { ps.codePathString }; 18855 18856 try { 18857 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18858 ps.appId, ceDataInodes, codePaths, stats); 18859 18860 // For now, ignore code size of packages on system partition 18861 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18862 stats.codeSize = 0; 18863 } 18864 18865 // External clients expect these to be tracked separately 18866 stats.dataSize -= stats.cacheSize; 18867 18868 } catch (InstallerException e) { 18869 Slog.w(TAG, String.valueOf(e)); 18870 return false; 18871 } 18872 18873 return true; 18874 } 18875 18876 private int getUidTargetSdkVersionLockedLPr(int uid) { 18877 Object obj = mSettings.getUserIdLPr(uid); 18878 if (obj instanceof SharedUserSetting) { 18879 final SharedUserSetting sus = (SharedUserSetting) obj; 18880 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18881 final Iterator<PackageSetting> it = sus.packages.iterator(); 18882 while (it.hasNext()) { 18883 final PackageSetting ps = it.next(); 18884 if (ps.pkg != null) { 18885 int v = ps.pkg.applicationInfo.targetSdkVersion; 18886 if (v < vers) vers = v; 18887 } 18888 } 18889 return vers; 18890 } else if (obj instanceof PackageSetting) { 18891 final PackageSetting ps = (PackageSetting) obj; 18892 if (ps.pkg != null) { 18893 return ps.pkg.applicationInfo.targetSdkVersion; 18894 } 18895 } 18896 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18897 } 18898 18899 @Override 18900 public void addPreferredActivity(IntentFilter filter, int match, 18901 ComponentName[] set, ComponentName activity, int userId) { 18902 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18903 "Adding preferred"); 18904 } 18905 18906 private void addPreferredActivityInternal(IntentFilter filter, int match, 18907 ComponentName[] set, ComponentName activity, boolean always, int userId, 18908 String opname) { 18909 // writer 18910 int callingUid = Binder.getCallingUid(); 18911 enforceCrossUserPermission(callingUid, userId, 18912 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18913 if (filter.countActions() == 0) { 18914 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18915 return; 18916 } 18917 synchronized (mPackages) { 18918 if (mContext.checkCallingOrSelfPermission( 18919 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18920 != PackageManager.PERMISSION_GRANTED) { 18921 if (getUidTargetSdkVersionLockedLPr(callingUid) 18922 < Build.VERSION_CODES.FROYO) { 18923 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18924 + callingUid); 18925 return; 18926 } 18927 mContext.enforceCallingOrSelfPermission( 18928 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18929 } 18930 18931 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18932 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18933 + userId + ":"); 18934 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18935 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18936 scheduleWritePackageRestrictionsLocked(userId); 18937 postPreferredActivityChangedBroadcast(userId); 18938 } 18939 } 18940 18941 private void postPreferredActivityChangedBroadcast(int userId) { 18942 mHandler.post(() -> { 18943 final IActivityManager am = ActivityManager.getService(); 18944 if (am == null) { 18945 return; 18946 } 18947 18948 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18949 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18950 try { 18951 am.broadcastIntent(null, intent, null, null, 18952 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18953 null, false, false, userId); 18954 } catch (RemoteException e) { 18955 } 18956 }); 18957 } 18958 18959 @Override 18960 public void replacePreferredActivity(IntentFilter filter, int match, 18961 ComponentName[] set, ComponentName activity, int userId) { 18962 if (filter.countActions() != 1) { 18963 throw new IllegalArgumentException( 18964 "replacePreferredActivity expects filter to have only 1 action."); 18965 } 18966 if (filter.countDataAuthorities() != 0 18967 || filter.countDataPaths() != 0 18968 || filter.countDataSchemes() > 1 18969 || filter.countDataTypes() != 0) { 18970 throw new IllegalArgumentException( 18971 "replacePreferredActivity expects filter to have no data authorities, " + 18972 "paths, or types; and at most one scheme."); 18973 } 18974 18975 final int callingUid = Binder.getCallingUid(); 18976 enforceCrossUserPermission(callingUid, userId, 18977 true /* requireFullPermission */, false /* checkShell */, 18978 "replace preferred activity"); 18979 synchronized (mPackages) { 18980 if (mContext.checkCallingOrSelfPermission( 18981 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18982 != PackageManager.PERMISSION_GRANTED) { 18983 if (getUidTargetSdkVersionLockedLPr(callingUid) 18984 < Build.VERSION_CODES.FROYO) { 18985 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18986 + Binder.getCallingUid()); 18987 return; 18988 } 18989 mContext.enforceCallingOrSelfPermission( 18990 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18991 } 18992 18993 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18994 if (pir != null) { 18995 // Get all of the existing entries that exactly match this filter. 18996 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18997 if (existing != null && existing.size() == 1) { 18998 PreferredActivity cur = existing.get(0); 18999 if (DEBUG_PREFERRED) { 19000 Slog.i(TAG, "Checking replace of preferred:"); 19001 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19002 if (!cur.mPref.mAlways) { 19003 Slog.i(TAG, " -- CUR; not mAlways!"); 19004 } else { 19005 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19006 Slog.i(TAG, " -- CUR: mSet=" 19007 + Arrays.toString(cur.mPref.mSetComponents)); 19008 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19009 Slog.i(TAG, " -- NEW: mMatch=" 19010 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19011 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19012 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19013 } 19014 } 19015 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19016 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19017 && cur.mPref.sameSet(set)) { 19018 // Setting the preferred activity to what it happens to be already 19019 if (DEBUG_PREFERRED) { 19020 Slog.i(TAG, "Replacing with same preferred activity " 19021 + cur.mPref.mShortComponent + " for user " 19022 + userId + ":"); 19023 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19024 } 19025 return; 19026 } 19027 } 19028 19029 if (existing != null) { 19030 if (DEBUG_PREFERRED) { 19031 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19032 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19033 } 19034 for (int i = 0; i < existing.size(); i++) { 19035 PreferredActivity pa = existing.get(i); 19036 if (DEBUG_PREFERRED) { 19037 Slog.i(TAG, "Removing existing preferred activity " 19038 + pa.mPref.mComponent + ":"); 19039 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19040 } 19041 pir.removeFilter(pa); 19042 } 19043 } 19044 } 19045 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19046 "Replacing preferred"); 19047 } 19048 } 19049 19050 @Override 19051 public void clearPackagePreferredActivities(String packageName) { 19052 final int uid = Binder.getCallingUid(); 19053 // writer 19054 synchronized (mPackages) { 19055 PackageParser.Package pkg = mPackages.get(packageName); 19056 if (pkg == null || pkg.applicationInfo.uid != uid) { 19057 if (mContext.checkCallingOrSelfPermission( 19058 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19059 != PackageManager.PERMISSION_GRANTED) { 19060 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 19061 < Build.VERSION_CODES.FROYO) { 19062 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19063 + Binder.getCallingUid()); 19064 return; 19065 } 19066 mContext.enforceCallingOrSelfPermission( 19067 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19068 } 19069 } 19070 19071 int user = UserHandle.getCallingUserId(); 19072 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19073 scheduleWritePackageRestrictionsLocked(user); 19074 } 19075 } 19076 } 19077 19078 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19079 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19080 ArrayList<PreferredActivity> removed = null; 19081 boolean changed = false; 19082 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19083 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19084 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19085 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19086 continue; 19087 } 19088 Iterator<PreferredActivity> it = pir.filterIterator(); 19089 while (it.hasNext()) { 19090 PreferredActivity pa = it.next(); 19091 // Mark entry for removal only if it matches the package name 19092 // and the entry is of type "always". 19093 if (packageName == null || 19094 (pa.mPref.mComponent.getPackageName().equals(packageName) 19095 && pa.mPref.mAlways)) { 19096 if (removed == null) { 19097 removed = new ArrayList<PreferredActivity>(); 19098 } 19099 removed.add(pa); 19100 } 19101 } 19102 if (removed != null) { 19103 for (int j=0; j<removed.size(); j++) { 19104 PreferredActivity pa = removed.get(j); 19105 pir.removeFilter(pa); 19106 } 19107 changed = true; 19108 } 19109 } 19110 if (changed) { 19111 postPreferredActivityChangedBroadcast(userId); 19112 } 19113 return changed; 19114 } 19115 19116 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19117 private void clearIntentFilterVerificationsLPw(int userId) { 19118 final int packageCount = mPackages.size(); 19119 for (int i = 0; i < packageCount; i++) { 19120 PackageParser.Package pkg = mPackages.valueAt(i); 19121 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19122 } 19123 } 19124 19125 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19126 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19127 if (userId == UserHandle.USER_ALL) { 19128 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19129 sUserManager.getUserIds())) { 19130 for (int oneUserId : sUserManager.getUserIds()) { 19131 scheduleWritePackageRestrictionsLocked(oneUserId); 19132 } 19133 } 19134 } else { 19135 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19136 scheduleWritePackageRestrictionsLocked(userId); 19137 } 19138 } 19139 } 19140 19141 void clearDefaultBrowserIfNeeded(String packageName) { 19142 for (int oneUserId : sUserManager.getUserIds()) { 19143 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19144 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19145 if (packageName.equals(defaultBrowserPackageName)) { 19146 setDefaultBrowserPackageName(null, oneUserId); 19147 } 19148 } 19149 } 19150 19151 @Override 19152 public void resetApplicationPreferences(int userId) { 19153 mContext.enforceCallingOrSelfPermission( 19154 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19155 final long identity = Binder.clearCallingIdentity(); 19156 // writer 19157 try { 19158 synchronized (mPackages) { 19159 clearPackagePreferredActivitiesLPw(null, userId); 19160 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19161 // TODO: We have to reset the default SMS and Phone. This requires 19162 // significant refactoring to keep all default apps in the package 19163 // manager (cleaner but more work) or have the services provide 19164 // callbacks to the package manager to request a default app reset. 19165 applyFactoryDefaultBrowserLPw(userId); 19166 clearIntentFilterVerificationsLPw(userId); 19167 primeDomainVerificationsLPw(userId); 19168 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19169 scheduleWritePackageRestrictionsLocked(userId); 19170 } 19171 resetNetworkPolicies(userId); 19172 } finally { 19173 Binder.restoreCallingIdentity(identity); 19174 } 19175 } 19176 19177 @Override 19178 public int getPreferredActivities(List<IntentFilter> outFilters, 19179 List<ComponentName> outActivities, String packageName) { 19180 19181 int num = 0; 19182 final int userId = UserHandle.getCallingUserId(); 19183 // reader 19184 synchronized (mPackages) { 19185 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19186 if (pir != null) { 19187 final Iterator<PreferredActivity> it = pir.filterIterator(); 19188 while (it.hasNext()) { 19189 final PreferredActivity pa = it.next(); 19190 if (packageName == null 19191 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19192 && pa.mPref.mAlways)) { 19193 if (outFilters != null) { 19194 outFilters.add(new IntentFilter(pa)); 19195 } 19196 if (outActivities != null) { 19197 outActivities.add(pa.mPref.mComponent); 19198 } 19199 } 19200 } 19201 } 19202 } 19203 19204 return num; 19205 } 19206 19207 @Override 19208 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19209 int userId) { 19210 int callingUid = Binder.getCallingUid(); 19211 if (callingUid != Process.SYSTEM_UID) { 19212 throw new SecurityException( 19213 "addPersistentPreferredActivity can only be run by the system"); 19214 } 19215 if (filter.countActions() == 0) { 19216 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19217 return; 19218 } 19219 synchronized (mPackages) { 19220 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19221 ":"); 19222 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19223 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19224 new PersistentPreferredActivity(filter, activity)); 19225 scheduleWritePackageRestrictionsLocked(userId); 19226 postPreferredActivityChangedBroadcast(userId); 19227 } 19228 } 19229 19230 @Override 19231 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19232 int callingUid = Binder.getCallingUid(); 19233 if (callingUid != Process.SYSTEM_UID) { 19234 throw new SecurityException( 19235 "clearPackagePersistentPreferredActivities can only be run by the system"); 19236 } 19237 ArrayList<PersistentPreferredActivity> removed = null; 19238 boolean changed = false; 19239 synchronized (mPackages) { 19240 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19241 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19242 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19243 .valueAt(i); 19244 if (userId != thisUserId) { 19245 continue; 19246 } 19247 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19248 while (it.hasNext()) { 19249 PersistentPreferredActivity ppa = it.next(); 19250 // Mark entry for removal only if it matches the package name. 19251 if (ppa.mComponent.getPackageName().equals(packageName)) { 19252 if (removed == null) { 19253 removed = new ArrayList<PersistentPreferredActivity>(); 19254 } 19255 removed.add(ppa); 19256 } 19257 } 19258 if (removed != null) { 19259 for (int j=0; j<removed.size(); j++) { 19260 PersistentPreferredActivity ppa = removed.get(j); 19261 ppir.removeFilter(ppa); 19262 } 19263 changed = true; 19264 } 19265 } 19266 19267 if (changed) { 19268 scheduleWritePackageRestrictionsLocked(userId); 19269 postPreferredActivityChangedBroadcast(userId); 19270 } 19271 } 19272 } 19273 19274 /** 19275 * Common machinery for picking apart a restored XML blob and passing 19276 * it to a caller-supplied functor to be applied to the running system. 19277 */ 19278 private void restoreFromXml(XmlPullParser parser, int userId, 19279 String expectedStartTag, BlobXmlRestorer functor) 19280 throws IOException, XmlPullParserException { 19281 int type; 19282 while ((type = parser.next()) != XmlPullParser.START_TAG 19283 && type != XmlPullParser.END_DOCUMENT) { 19284 } 19285 if (type != XmlPullParser.START_TAG) { 19286 // oops didn't find a start tag?! 19287 if (DEBUG_BACKUP) { 19288 Slog.e(TAG, "Didn't find start tag during restore"); 19289 } 19290 return; 19291 } 19292Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19293 // this is supposed to be TAG_PREFERRED_BACKUP 19294 if (!expectedStartTag.equals(parser.getName())) { 19295 if (DEBUG_BACKUP) { 19296 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19297 } 19298 return; 19299 } 19300 19301 // skip interfering stuff, then we're aligned with the backing implementation 19302 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19303Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19304 functor.apply(parser, userId); 19305 } 19306 19307 private interface BlobXmlRestorer { 19308 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19309 } 19310 19311 /** 19312 * Non-Binder method, support for the backup/restore mechanism: write the 19313 * full set of preferred activities in its canonical XML format. Returns the 19314 * XML output as a byte array, or null if there is none. 19315 */ 19316 @Override 19317 public byte[] getPreferredActivityBackup(int userId) { 19318 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19319 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19320 } 19321 19322 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19323 try { 19324 final XmlSerializer serializer = new FastXmlSerializer(); 19325 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19326 serializer.startDocument(null, true); 19327 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19328 19329 synchronized (mPackages) { 19330 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19331 } 19332 19333 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19334 serializer.endDocument(); 19335 serializer.flush(); 19336 } catch (Exception e) { 19337 if (DEBUG_BACKUP) { 19338 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19339 } 19340 return null; 19341 } 19342 19343 return dataStream.toByteArray(); 19344 } 19345 19346 @Override 19347 public void restorePreferredActivities(byte[] backup, int userId) { 19348 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19349 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19350 } 19351 19352 try { 19353 final XmlPullParser parser = Xml.newPullParser(); 19354 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19355 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19356 new BlobXmlRestorer() { 19357 @Override 19358 public void apply(XmlPullParser parser, int userId) 19359 throws XmlPullParserException, IOException { 19360 synchronized (mPackages) { 19361 mSettings.readPreferredActivitiesLPw(parser, userId); 19362 } 19363 } 19364 } ); 19365 } catch (Exception e) { 19366 if (DEBUG_BACKUP) { 19367 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19368 } 19369 } 19370 } 19371 19372 /** 19373 * Non-Binder method, support for the backup/restore mechanism: write the 19374 * default browser (etc) settings in its canonical XML format. Returns the default 19375 * browser XML representation as a byte array, or null if there is none. 19376 */ 19377 @Override 19378 public byte[] getDefaultAppsBackup(int userId) { 19379 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19380 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19381 } 19382 19383 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19384 try { 19385 final XmlSerializer serializer = new FastXmlSerializer(); 19386 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19387 serializer.startDocument(null, true); 19388 serializer.startTag(null, TAG_DEFAULT_APPS); 19389 19390 synchronized (mPackages) { 19391 mSettings.writeDefaultAppsLPr(serializer, userId); 19392 } 19393 19394 serializer.endTag(null, TAG_DEFAULT_APPS); 19395 serializer.endDocument(); 19396 serializer.flush(); 19397 } catch (Exception e) { 19398 if (DEBUG_BACKUP) { 19399 Slog.e(TAG, "Unable to write default apps for backup", e); 19400 } 19401 return null; 19402 } 19403 19404 return dataStream.toByteArray(); 19405 } 19406 19407 @Override 19408 public void restoreDefaultApps(byte[] backup, int userId) { 19409 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19410 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19411 } 19412 19413 try { 19414 final XmlPullParser parser = Xml.newPullParser(); 19415 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19416 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19417 new BlobXmlRestorer() { 19418 @Override 19419 public void apply(XmlPullParser parser, int userId) 19420 throws XmlPullParserException, IOException { 19421 synchronized (mPackages) { 19422 mSettings.readDefaultAppsLPw(parser, userId); 19423 } 19424 } 19425 } ); 19426 } catch (Exception e) { 19427 if (DEBUG_BACKUP) { 19428 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19429 } 19430 } 19431 } 19432 19433 @Override 19434 public byte[] getIntentFilterVerificationBackup(int userId) { 19435 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19436 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19437 } 19438 19439 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19440 try { 19441 final XmlSerializer serializer = new FastXmlSerializer(); 19442 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19443 serializer.startDocument(null, true); 19444 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19445 19446 synchronized (mPackages) { 19447 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19448 } 19449 19450 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19451 serializer.endDocument(); 19452 serializer.flush(); 19453 } catch (Exception e) { 19454 if (DEBUG_BACKUP) { 19455 Slog.e(TAG, "Unable to write default apps for backup", e); 19456 } 19457 return null; 19458 } 19459 19460 return dataStream.toByteArray(); 19461 } 19462 19463 @Override 19464 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19465 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19466 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19467 } 19468 19469 try { 19470 final XmlPullParser parser = Xml.newPullParser(); 19471 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19472 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19473 new BlobXmlRestorer() { 19474 @Override 19475 public void apply(XmlPullParser parser, int userId) 19476 throws XmlPullParserException, IOException { 19477 synchronized (mPackages) { 19478 mSettings.readAllDomainVerificationsLPr(parser, userId); 19479 mSettings.writeLPr(); 19480 } 19481 } 19482 } ); 19483 } catch (Exception e) { 19484 if (DEBUG_BACKUP) { 19485 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19486 } 19487 } 19488 } 19489 19490 @Override 19491 public byte[] getPermissionGrantBackup(int userId) { 19492 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19493 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19494 } 19495 19496 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19497 try { 19498 final XmlSerializer serializer = new FastXmlSerializer(); 19499 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19500 serializer.startDocument(null, true); 19501 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19502 19503 synchronized (mPackages) { 19504 serializeRuntimePermissionGrantsLPr(serializer, userId); 19505 } 19506 19507 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19508 serializer.endDocument(); 19509 serializer.flush(); 19510 } catch (Exception e) { 19511 if (DEBUG_BACKUP) { 19512 Slog.e(TAG, "Unable to write default apps for backup", e); 19513 } 19514 return null; 19515 } 19516 19517 return dataStream.toByteArray(); 19518 } 19519 19520 @Override 19521 public void restorePermissionGrants(byte[] backup, int userId) { 19522 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19523 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19524 } 19525 19526 try { 19527 final XmlPullParser parser = Xml.newPullParser(); 19528 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19529 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19530 new BlobXmlRestorer() { 19531 @Override 19532 public void apply(XmlPullParser parser, int userId) 19533 throws XmlPullParserException, IOException { 19534 synchronized (mPackages) { 19535 processRestoredPermissionGrantsLPr(parser, userId); 19536 } 19537 } 19538 } ); 19539 } catch (Exception e) { 19540 if (DEBUG_BACKUP) { 19541 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19542 } 19543 } 19544 } 19545 19546 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19547 throws IOException { 19548 serializer.startTag(null, TAG_ALL_GRANTS); 19549 19550 final int N = mSettings.mPackages.size(); 19551 for (int i = 0; i < N; i++) { 19552 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19553 boolean pkgGrantsKnown = false; 19554 19555 PermissionsState packagePerms = ps.getPermissionsState(); 19556 19557 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19558 final int grantFlags = state.getFlags(); 19559 // only look at grants that are not system/policy fixed 19560 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19561 final boolean isGranted = state.isGranted(); 19562 // And only back up the user-twiddled state bits 19563 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19564 final String packageName = mSettings.mPackages.keyAt(i); 19565 if (!pkgGrantsKnown) { 19566 serializer.startTag(null, TAG_GRANT); 19567 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19568 pkgGrantsKnown = true; 19569 } 19570 19571 final boolean userSet = 19572 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19573 final boolean userFixed = 19574 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19575 final boolean revoke = 19576 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19577 19578 serializer.startTag(null, TAG_PERMISSION); 19579 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19580 if (isGranted) { 19581 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19582 } 19583 if (userSet) { 19584 serializer.attribute(null, ATTR_USER_SET, "true"); 19585 } 19586 if (userFixed) { 19587 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19588 } 19589 if (revoke) { 19590 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19591 } 19592 serializer.endTag(null, TAG_PERMISSION); 19593 } 19594 } 19595 } 19596 19597 if (pkgGrantsKnown) { 19598 serializer.endTag(null, TAG_GRANT); 19599 } 19600 } 19601 19602 serializer.endTag(null, TAG_ALL_GRANTS); 19603 } 19604 19605 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19606 throws XmlPullParserException, IOException { 19607 String pkgName = null; 19608 int outerDepth = parser.getDepth(); 19609 int type; 19610 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19611 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19612 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19613 continue; 19614 } 19615 19616 final String tagName = parser.getName(); 19617 if (tagName.equals(TAG_GRANT)) { 19618 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19619 if (DEBUG_BACKUP) { 19620 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19621 } 19622 } else if (tagName.equals(TAG_PERMISSION)) { 19623 19624 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19625 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19626 19627 int newFlagSet = 0; 19628 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19629 newFlagSet |= FLAG_PERMISSION_USER_SET; 19630 } 19631 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19632 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19633 } 19634 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19635 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19636 } 19637 if (DEBUG_BACKUP) { 19638 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19639 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19640 } 19641 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19642 if (ps != null) { 19643 // Already installed so we apply the grant immediately 19644 if (DEBUG_BACKUP) { 19645 Slog.v(TAG, " + already installed; applying"); 19646 } 19647 PermissionsState perms = ps.getPermissionsState(); 19648 BasePermission bp = mSettings.mPermissions.get(permName); 19649 if (bp != null) { 19650 if (isGranted) { 19651 perms.grantRuntimePermission(bp, userId); 19652 } 19653 if (newFlagSet != 0) { 19654 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19655 } 19656 } 19657 } else { 19658 // Need to wait for post-restore install to apply the grant 19659 if (DEBUG_BACKUP) { 19660 Slog.v(TAG, " - not yet installed; saving for later"); 19661 } 19662 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19663 isGranted, newFlagSet, userId); 19664 } 19665 } else { 19666 PackageManagerService.reportSettingsProblem(Log.WARN, 19667 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19668 XmlUtils.skipCurrentTag(parser); 19669 } 19670 } 19671 19672 scheduleWriteSettingsLocked(); 19673 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19674 } 19675 19676 @Override 19677 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19678 int sourceUserId, int targetUserId, int flags) { 19679 mContext.enforceCallingOrSelfPermission( 19680 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19681 int callingUid = Binder.getCallingUid(); 19682 enforceOwnerRights(ownerPackage, callingUid); 19683 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19684 if (intentFilter.countActions() == 0) { 19685 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19686 return; 19687 } 19688 synchronized (mPackages) { 19689 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19690 ownerPackage, targetUserId, flags); 19691 CrossProfileIntentResolver resolver = 19692 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19693 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19694 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19695 if (existing != null) { 19696 int size = existing.size(); 19697 for (int i = 0; i < size; i++) { 19698 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19699 return; 19700 } 19701 } 19702 } 19703 resolver.addFilter(newFilter); 19704 scheduleWritePackageRestrictionsLocked(sourceUserId); 19705 } 19706 } 19707 19708 @Override 19709 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19710 mContext.enforceCallingOrSelfPermission( 19711 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19712 int callingUid = Binder.getCallingUid(); 19713 enforceOwnerRights(ownerPackage, callingUid); 19714 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19715 synchronized (mPackages) { 19716 CrossProfileIntentResolver resolver = 19717 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19718 ArraySet<CrossProfileIntentFilter> set = 19719 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19720 for (CrossProfileIntentFilter filter : set) { 19721 if (filter.getOwnerPackage().equals(ownerPackage)) { 19722 resolver.removeFilter(filter); 19723 } 19724 } 19725 scheduleWritePackageRestrictionsLocked(sourceUserId); 19726 } 19727 } 19728 19729 // Enforcing that callingUid is owning pkg on userId 19730 private void enforceOwnerRights(String pkg, int callingUid) { 19731 // The system owns everything. 19732 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19733 return; 19734 } 19735 int callingUserId = UserHandle.getUserId(callingUid); 19736 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19737 if (pi == null) { 19738 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19739 + callingUserId); 19740 } 19741 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19742 throw new SecurityException("Calling uid " + callingUid 19743 + " does not own package " + pkg); 19744 } 19745 } 19746 19747 @Override 19748 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19749 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19750 } 19751 19752 /** 19753 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19754 * then reports the most likely home activity or null if there are more than one. 19755 */ 19756 public ComponentName getDefaultHomeActivity(int userId) { 19757 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19758 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19759 if (cn != null) { 19760 return cn; 19761 } 19762 19763 // Find the launcher with the highest priority and return that component if there are no 19764 // other home activity with the same priority. 19765 int lastPriority = Integer.MIN_VALUE; 19766 ComponentName lastComponent = null; 19767 final int size = allHomeCandidates.size(); 19768 for (int i = 0; i < size; i++) { 19769 final ResolveInfo ri = allHomeCandidates.get(i); 19770 if (ri.priority > lastPriority) { 19771 lastComponent = ri.activityInfo.getComponentName(); 19772 lastPriority = ri.priority; 19773 } else if (ri.priority == lastPriority) { 19774 // Two components found with same priority. 19775 lastComponent = null; 19776 } 19777 } 19778 return lastComponent; 19779 } 19780 19781 private Intent getHomeIntent() { 19782 Intent intent = new Intent(Intent.ACTION_MAIN); 19783 intent.addCategory(Intent.CATEGORY_HOME); 19784 intent.addCategory(Intent.CATEGORY_DEFAULT); 19785 return intent; 19786 } 19787 19788 private IntentFilter getHomeFilter() { 19789 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19790 filter.addCategory(Intent.CATEGORY_HOME); 19791 filter.addCategory(Intent.CATEGORY_DEFAULT); 19792 return filter; 19793 } 19794 19795 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19796 int userId) { 19797 Intent intent = getHomeIntent(); 19798 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19799 PackageManager.GET_META_DATA, userId); 19800 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19801 true, false, false, userId); 19802 19803 allHomeCandidates.clear(); 19804 if (list != null) { 19805 for (ResolveInfo ri : list) { 19806 allHomeCandidates.add(ri); 19807 } 19808 } 19809 return (preferred == null || preferred.activityInfo == null) 19810 ? null 19811 : new ComponentName(preferred.activityInfo.packageName, 19812 preferred.activityInfo.name); 19813 } 19814 19815 @Override 19816 public void setHomeActivity(ComponentName comp, int userId) { 19817 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19818 getHomeActivitiesAsUser(homeActivities, userId); 19819 19820 boolean found = false; 19821 19822 final int size = homeActivities.size(); 19823 final ComponentName[] set = new ComponentName[size]; 19824 for (int i = 0; i < size; i++) { 19825 final ResolveInfo candidate = homeActivities.get(i); 19826 final ActivityInfo info = candidate.activityInfo; 19827 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19828 set[i] = activityName; 19829 if (!found && activityName.equals(comp)) { 19830 found = true; 19831 } 19832 } 19833 if (!found) { 19834 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19835 + userId); 19836 } 19837 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19838 set, comp, userId); 19839 } 19840 19841 private @Nullable String getSetupWizardPackageName() { 19842 final Intent intent = new Intent(Intent.ACTION_MAIN); 19843 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19844 19845 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19846 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19847 | MATCH_DISABLED_COMPONENTS, 19848 UserHandle.myUserId()); 19849 if (matches.size() == 1) { 19850 return matches.get(0).getComponentInfo().packageName; 19851 } else { 19852 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19853 + ": matches=" + matches); 19854 return null; 19855 } 19856 } 19857 19858 private @Nullable String getStorageManagerPackageName() { 19859 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19860 19861 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19862 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19863 | MATCH_DISABLED_COMPONENTS, 19864 UserHandle.myUserId()); 19865 if (matches.size() == 1) { 19866 return matches.get(0).getComponentInfo().packageName; 19867 } else { 19868 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19869 + matches.size() + ": matches=" + matches); 19870 return null; 19871 } 19872 } 19873 19874 @Override 19875 public void setApplicationEnabledSetting(String appPackageName, 19876 int newState, int flags, int userId, String callingPackage) { 19877 if (!sUserManager.exists(userId)) return; 19878 if (callingPackage == null) { 19879 callingPackage = Integer.toString(Binder.getCallingUid()); 19880 } 19881 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19882 } 19883 19884 @Override 19885 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19886 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19887 synchronized (mPackages) { 19888 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19889 if (pkgSetting != null) { 19890 pkgSetting.setUpdateAvailable(updateAvailable); 19891 } 19892 } 19893 } 19894 19895 @Override 19896 public void setComponentEnabledSetting(ComponentName componentName, 19897 int newState, int flags, int userId) { 19898 if (!sUserManager.exists(userId)) return; 19899 setEnabledSetting(componentName.getPackageName(), 19900 componentName.getClassName(), newState, flags, userId, null); 19901 } 19902 19903 private void setEnabledSetting(final String packageName, String className, int newState, 19904 final int flags, int userId, String callingPackage) { 19905 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19906 || newState == COMPONENT_ENABLED_STATE_ENABLED 19907 || newState == COMPONENT_ENABLED_STATE_DISABLED 19908 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19909 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19910 throw new IllegalArgumentException("Invalid new component state: " 19911 + newState); 19912 } 19913 PackageSetting pkgSetting; 19914 final int uid = Binder.getCallingUid(); 19915 final int permission; 19916 if (uid == Process.SYSTEM_UID) { 19917 permission = PackageManager.PERMISSION_GRANTED; 19918 } else { 19919 permission = mContext.checkCallingOrSelfPermission( 19920 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19921 } 19922 enforceCrossUserPermission(uid, userId, 19923 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19924 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19925 boolean sendNow = false; 19926 boolean isApp = (className == null); 19927 String componentName = isApp ? packageName : className; 19928 int packageUid = -1; 19929 ArrayList<String> components; 19930 19931 // writer 19932 synchronized (mPackages) { 19933 pkgSetting = mSettings.mPackages.get(packageName); 19934 if (pkgSetting == null) { 19935 if (className == null) { 19936 throw new IllegalArgumentException("Unknown package: " + packageName); 19937 } 19938 throw new IllegalArgumentException( 19939 "Unknown component: " + packageName + "/" + className); 19940 } 19941 } 19942 19943 // Limit who can change which apps 19944 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19945 // Don't allow apps that don't have permission to modify other apps 19946 if (!allowedByPermission) { 19947 throw new SecurityException( 19948 "Permission Denial: attempt to change component state from pid=" 19949 + Binder.getCallingPid() 19950 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19951 } 19952 // Don't allow changing protected packages. 19953 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19954 throw new SecurityException("Cannot disable a protected package: " + packageName); 19955 } 19956 } 19957 19958 synchronized (mPackages) { 19959 if (uid == Process.SHELL_UID 19960 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19961 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19962 // unless it is a test package. 19963 int oldState = pkgSetting.getEnabled(userId); 19964 if (className == null 19965 && 19966 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19967 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19968 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19969 && 19970 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19971 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19972 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19973 // ok 19974 } else { 19975 throw new SecurityException( 19976 "Shell cannot change component state for " + packageName + "/" 19977 + className + " to " + newState); 19978 } 19979 } 19980 if (className == null) { 19981 // We're dealing with an application/package level state change 19982 if (pkgSetting.getEnabled(userId) == newState) { 19983 // Nothing to do 19984 return; 19985 } 19986 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19987 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19988 // Don't care about who enables an app. 19989 callingPackage = null; 19990 } 19991 pkgSetting.setEnabled(newState, userId, callingPackage); 19992 // pkgSetting.pkg.mSetEnabled = newState; 19993 } else { 19994 // We're dealing with a component level state change 19995 // First, verify that this is a valid class name. 19996 PackageParser.Package pkg = pkgSetting.pkg; 19997 if (pkg == null || !pkg.hasComponentClassName(className)) { 19998 if (pkg != null && 19999 pkg.applicationInfo.targetSdkVersion >= 20000 Build.VERSION_CODES.JELLY_BEAN) { 20001 throw new IllegalArgumentException("Component class " + className 20002 + " does not exist in " + packageName); 20003 } else { 20004 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20005 + className + " does not exist in " + packageName); 20006 } 20007 } 20008 switch (newState) { 20009 case COMPONENT_ENABLED_STATE_ENABLED: 20010 if (!pkgSetting.enableComponentLPw(className, userId)) { 20011 return; 20012 } 20013 break; 20014 case COMPONENT_ENABLED_STATE_DISABLED: 20015 if (!pkgSetting.disableComponentLPw(className, userId)) { 20016 return; 20017 } 20018 break; 20019 case COMPONENT_ENABLED_STATE_DEFAULT: 20020 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20021 return; 20022 } 20023 break; 20024 default: 20025 Slog.e(TAG, "Invalid new component state: " + newState); 20026 return; 20027 } 20028 } 20029 scheduleWritePackageRestrictionsLocked(userId); 20030 updateSequenceNumberLP(packageName, new int[] { userId }); 20031 final long callingId = Binder.clearCallingIdentity(); 20032 try { 20033 updateInstantAppInstallerLocked(packageName); 20034 } finally { 20035 Binder.restoreCallingIdentity(callingId); 20036 } 20037 components = mPendingBroadcasts.get(userId, packageName); 20038 final boolean newPackage = components == null; 20039 if (newPackage) { 20040 components = new ArrayList<String>(); 20041 } 20042 if (!components.contains(componentName)) { 20043 components.add(componentName); 20044 } 20045 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20046 sendNow = true; 20047 // Purge entry from pending broadcast list if another one exists already 20048 // since we are sending one right away. 20049 mPendingBroadcasts.remove(userId, packageName); 20050 } else { 20051 if (newPackage) { 20052 mPendingBroadcasts.put(userId, packageName, components); 20053 } 20054 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20055 // Schedule a message 20056 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20057 } 20058 } 20059 } 20060 20061 long callingId = Binder.clearCallingIdentity(); 20062 try { 20063 if (sendNow) { 20064 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20065 sendPackageChangedBroadcast(packageName, 20066 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20067 } 20068 } finally { 20069 Binder.restoreCallingIdentity(callingId); 20070 } 20071 } 20072 20073 @Override 20074 public void flushPackageRestrictionsAsUser(int userId) { 20075 if (!sUserManager.exists(userId)) { 20076 return; 20077 } 20078 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20079 false /* checkShell */, "flushPackageRestrictions"); 20080 synchronized (mPackages) { 20081 mSettings.writePackageRestrictionsLPr(userId); 20082 mDirtyUsers.remove(userId); 20083 if (mDirtyUsers.isEmpty()) { 20084 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20085 } 20086 } 20087 } 20088 20089 private void sendPackageChangedBroadcast(String packageName, 20090 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20091 if (DEBUG_INSTALL) 20092 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20093 + componentNames); 20094 Bundle extras = new Bundle(4); 20095 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20096 String nameList[] = new String[componentNames.size()]; 20097 componentNames.toArray(nameList); 20098 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20099 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20100 extras.putInt(Intent.EXTRA_UID, packageUid); 20101 // If this is not reporting a change of the overall package, then only send it 20102 // to registered receivers. We don't want to launch a swath of apps for every 20103 // little component state change. 20104 final int flags = !componentNames.contains(packageName) 20105 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20106 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20107 new int[] {UserHandle.getUserId(packageUid)}); 20108 } 20109 20110 @Override 20111 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20112 if (!sUserManager.exists(userId)) return; 20113 final int uid = Binder.getCallingUid(); 20114 final int permission = mContext.checkCallingOrSelfPermission( 20115 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20116 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20117 enforceCrossUserPermission(uid, userId, 20118 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20119 // writer 20120 synchronized (mPackages) { 20121 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20122 allowedByPermission, uid, userId)) { 20123 scheduleWritePackageRestrictionsLocked(userId); 20124 } 20125 } 20126 } 20127 20128 @Override 20129 public String getInstallerPackageName(String packageName) { 20130 // reader 20131 synchronized (mPackages) { 20132 return mSettings.getInstallerPackageNameLPr(packageName); 20133 } 20134 } 20135 20136 public boolean isOrphaned(String packageName) { 20137 // reader 20138 synchronized (mPackages) { 20139 return mSettings.isOrphaned(packageName); 20140 } 20141 } 20142 20143 @Override 20144 public int getApplicationEnabledSetting(String packageName, int userId) { 20145 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20146 int uid = Binder.getCallingUid(); 20147 enforceCrossUserPermission(uid, userId, 20148 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20149 // reader 20150 synchronized (mPackages) { 20151 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20152 } 20153 } 20154 20155 @Override 20156 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20157 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20158 int uid = Binder.getCallingUid(); 20159 enforceCrossUserPermission(uid, userId, 20160 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20161 // reader 20162 synchronized (mPackages) { 20163 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20164 } 20165 } 20166 20167 @Override 20168 public void enterSafeMode() { 20169 enforceSystemOrRoot("Only the system can request entering safe mode"); 20170 20171 if (!mSystemReady) { 20172 mSafeMode = true; 20173 } 20174 } 20175 20176 @Override 20177 public void systemReady() { 20178 mSystemReady = true; 20179 20180 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20181 // disabled after already being started. 20182 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20183 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20184 20185 // Read the compatibilty setting when the system is ready. 20186 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20187 mContext.getContentResolver(), 20188 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20189 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20190 if (DEBUG_SETTINGS) { 20191 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20192 } 20193 20194 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20195 20196 synchronized (mPackages) { 20197 // Verify that all of the preferred activity components actually 20198 // exist. It is possible for applications to be updated and at 20199 // that point remove a previously declared activity component that 20200 // had been set as a preferred activity. We try to clean this up 20201 // the next time we encounter that preferred activity, but it is 20202 // possible for the user flow to never be able to return to that 20203 // situation so here we do a sanity check to make sure we haven't 20204 // left any junk around. 20205 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20206 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20207 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20208 removed.clear(); 20209 for (PreferredActivity pa : pir.filterSet()) { 20210 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20211 removed.add(pa); 20212 } 20213 } 20214 if (removed.size() > 0) { 20215 for (int r=0; r<removed.size(); r++) { 20216 PreferredActivity pa = removed.get(r); 20217 Slog.w(TAG, "Removing dangling preferred activity: " 20218 + pa.mPref.mComponent); 20219 pir.removeFilter(pa); 20220 } 20221 mSettings.writePackageRestrictionsLPr( 20222 mSettings.mPreferredActivities.keyAt(i)); 20223 } 20224 } 20225 20226 for (int userId : UserManagerService.getInstance().getUserIds()) { 20227 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20228 grantPermissionsUserIds = ArrayUtils.appendInt( 20229 grantPermissionsUserIds, userId); 20230 } 20231 } 20232 } 20233 sUserManager.systemReady(); 20234 20235 // If we upgraded grant all default permissions before kicking off. 20236 for (int userId : grantPermissionsUserIds) { 20237 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20238 } 20239 20240 // If we did not grant default permissions, we preload from this the 20241 // default permission exceptions lazily to ensure we don't hit the 20242 // disk on a new user creation. 20243 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20244 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20245 } 20246 20247 // Kick off any messages waiting for system ready 20248 if (mPostSystemReadyMessages != null) { 20249 for (Message msg : mPostSystemReadyMessages) { 20250 msg.sendToTarget(); 20251 } 20252 mPostSystemReadyMessages = null; 20253 } 20254 20255 // Watch for external volumes that come and go over time 20256 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20257 storage.registerListener(mStorageListener); 20258 20259 mInstallerService.systemReady(); 20260 mPackageDexOptimizer.systemReady(); 20261 20262 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20263 StorageManagerInternal.class); 20264 StorageManagerInternal.addExternalStoragePolicy( 20265 new StorageManagerInternal.ExternalStorageMountPolicy() { 20266 @Override 20267 public int getMountMode(int uid, String packageName) { 20268 if (Process.isIsolated(uid)) { 20269 return Zygote.MOUNT_EXTERNAL_NONE; 20270 } 20271 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20272 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20273 } 20274 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20275 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20276 } 20277 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20278 return Zygote.MOUNT_EXTERNAL_READ; 20279 } 20280 return Zygote.MOUNT_EXTERNAL_WRITE; 20281 } 20282 20283 @Override 20284 public boolean hasExternalStorage(int uid, String packageName) { 20285 return true; 20286 } 20287 }); 20288 20289 // Now that we're mostly running, clean up stale users and apps 20290 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20291 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20292 20293 if (mPrivappPermissionsViolations != null) { 20294 Slog.wtf(TAG,"Signature|privileged permissions not in " 20295 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20296 mPrivappPermissionsViolations = null; 20297 } 20298 } 20299 20300 public void waitForAppDataPrepared() { 20301 if (mPrepareAppDataFuture == null) { 20302 return; 20303 } 20304 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20305 mPrepareAppDataFuture = null; 20306 } 20307 20308 @Override 20309 public boolean isSafeMode() { 20310 return mSafeMode; 20311 } 20312 20313 @Override 20314 public boolean hasSystemUidErrors() { 20315 return mHasSystemUidErrors; 20316 } 20317 20318 static String arrayToString(int[] array) { 20319 StringBuffer buf = new StringBuffer(128); 20320 buf.append('['); 20321 if (array != null) { 20322 for (int i=0; i<array.length; i++) { 20323 if (i > 0) buf.append(", "); 20324 buf.append(array[i]); 20325 } 20326 } 20327 buf.append(']'); 20328 return buf.toString(); 20329 } 20330 20331 static class DumpState { 20332 public static final int DUMP_LIBS = 1 << 0; 20333 public static final int DUMP_FEATURES = 1 << 1; 20334 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20335 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20336 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20337 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20338 public static final int DUMP_PERMISSIONS = 1 << 6; 20339 public static final int DUMP_PACKAGES = 1 << 7; 20340 public static final int DUMP_SHARED_USERS = 1 << 8; 20341 public static final int DUMP_MESSAGES = 1 << 9; 20342 public static final int DUMP_PROVIDERS = 1 << 10; 20343 public static final int DUMP_VERIFIERS = 1 << 11; 20344 public static final int DUMP_PREFERRED = 1 << 12; 20345 public static final int DUMP_PREFERRED_XML = 1 << 13; 20346 public static final int DUMP_KEYSETS = 1 << 14; 20347 public static final int DUMP_VERSION = 1 << 15; 20348 public static final int DUMP_INSTALLS = 1 << 16; 20349 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20350 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20351 public static final int DUMP_FROZEN = 1 << 19; 20352 public static final int DUMP_DEXOPT = 1 << 20; 20353 public static final int DUMP_COMPILER_STATS = 1 << 21; 20354 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20355 20356 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20357 20358 private int mTypes; 20359 20360 private int mOptions; 20361 20362 private boolean mTitlePrinted; 20363 20364 private SharedUserSetting mSharedUser; 20365 20366 public boolean isDumping(int type) { 20367 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20368 return true; 20369 } 20370 20371 return (mTypes & type) != 0; 20372 } 20373 20374 public void setDump(int type) { 20375 mTypes |= type; 20376 } 20377 20378 public boolean isOptionEnabled(int option) { 20379 return (mOptions & option) != 0; 20380 } 20381 20382 public void setOptionEnabled(int option) { 20383 mOptions |= option; 20384 } 20385 20386 public boolean onTitlePrinted() { 20387 final boolean printed = mTitlePrinted; 20388 mTitlePrinted = true; 20389 return printed; 20390 } 20391 20392 public boolean getTitlePrinted() { 20393 return mTitlePrinted; 20394 } 20395 20396 public void setTitlePrinted(boolean enabled) { 20397 mTitlePrinted = enabled; 20398 } 20399 20400 public SharedUserSetting getSharedUser() { 20401 return mSharedUser; 20402 } 20403 20404 public void setSharedUser(SharedUserSetting user) { 20405 mSharedUser = user; 20406 } 20407 } 20408 20409 @Override 20410 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20411 FileDescriptor err, String[] args, ShellCallback callback, 20412 ResultReceiver resultReceiver) { 20413 (new PackageManagerShellCommand(this)).exec( 20414 this, in, out, err, args, callback, resultReceiver); 20415 } 20416 20417 @Override 20418 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20419 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20420 20421 DumpState dumpState = new DumpState(); 20422 boolean fullPreferred = false; 20423 boolean checkin = false; 20424 20425 String packageName = null; 20426 ArraySet<String> permissionNames = null; 20427 20428 int opti = 0; 20429 while (opti < args.length) { 20430 String opt = args[opti]; 20431 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20432 break; 20433 } 20434 opti++; 20435 20436 if ("-a".equals(opt)) { 20437 // Right now we only know how to print all. 20438 } else if ("-h".equals(opt)) { 20439 pw.println("Package manager dump options:"); 20440 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20441 pw.println(" --checkin: dump for a checkin"); 20442 pw.println(" -f: print details of intent filters"); 20443 pw.println(" -h: print this help"); 20444 pw.println(" cmd may be one of:"); 20445 pw.println(" l[ibraries]: list known shared libraries"); 20446 pw.println(" f[eatures]: list device features"); 20447 pw.println(" k[eysets]: print known keysets"); 20448 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20449 pw.println(" perm[issions]: dump permissions"); 20450 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20451 pw.println(" pref[erred]: print preferred package settings"); 20452 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20453 pw.println(" prov[iders]: dump content providers"); 20454 pw.println(" p[ackages]: dump installed packages"); 20455 pw.println(" s[hared-users]: dump shared user IDs"); 20456 pw.println(" m[essages]: print collected runtime messages"); 20457 pw.println(" v[erifiers]: print package verifier info"); 20458 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20459 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20460 pw.println(" version: print database version info"); 20461 pw.println(" write: write current settings now"); 20462 pw.println(" installs: details about install sessions"); 20463 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20464 pw.println(" dexopt: dump dexopt state"); 20465 pw.println(" compiler-stats: dump compiler statistics"); 20466 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20467 pw.println(" <package.name>: info about given package"); 20468 return; 20469 } else if ("--checkin".equals(opt)) { 20470 checkin = true; 20471 } else if ("-f".equals(opt)) { 20472 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20473 } else if ("--proto".equals(opt)) { 20474 dumpProto(fd); 20475 return; 20476 } else { 20477 pw.println("Unknown argument: " + opt + "; use -h for help"); 20478 } 20479 } 20480 20481 // Is the caller requesting to dump a particular piece of data? 20482 if (opti < args.length) { 20483 String cmd = args[opti]; 20484 opti++; 20485 // Is this a package name? 20486 if ("android".equals(cmd) || cmd.contains(".")) { 20487 packageName = cmd; 20488 // When dumping a single package, we always dump all of its 20489 // filter information since the amount of data will be reasonable. 20490 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20491 } else if ("check-permission".equals(cmd)) { 20492 if (opti >= args.length) { 20493 pw.println("Error: check-permission missing permission argument"); 20494 return; 20495 } 20496 String perm = args[opti]; 20497 opti++; 20498 if (opti >= args.length) { 20499 pw.println("Error: check-permission missing package argument"); 20500 return; 20501 } 20502 20503 String pkg = args[opti]; 20504 opti++; 20505 int user = UserHandle.getUserId(Binder.getCallingUid()); 20506 if (opti < args.length) { 20507 try { 20508 user = Integer.parseInt(args[opti]); 20509 } catch (NumberFormatException e) { 20510 pw.println("Error: check-permission user argument is not a number: " 20511 + args[opti]); 20512 return; 20513 } 20514 } 20515 20516 // Normalize package name to handle renamed packages and static libs 20517 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20518 20519 pw.println(checkPermission(perm, pkg, user)); 20520 return; 20521 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20522 dumpState.setDump(DumpState.DUMP_LIBS); 20523 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20524 dumpState.setDump(DumpState.DUMP_FEATURES); 20525 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20526 if (opti >= args.length) { 20527 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20528 | DumpState.DUMP_SERVICE_RESOLVERS 20529 | DumpState.DUMP_RECEIVER_RESOLVERS 20530 | DumpState.DUMP_CONTENT_RESOLVERS); 20531 } else { 20532 while (opti < args.length) { 20533 String name = args[opti]; 20534 if ("a".equals(name) || "activity".equals(name)) { 20535 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20536 } else if ("s".equals(name) || "service".equals(name)) { 20537 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20538 } else if ("r".equals(name) || "receiver".equals(name)) { 20539 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20540 } else if ("c".equals(name) || "content".equals(name)) { 20541 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20542 } else { 20543 pw.println("Error: unknown resolver table type: " + name); 20544 return; 20545 } 20546 opti++; 20547 } 20548 } 20549 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20550 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20551 } else if ("permission".equals(cmd)) { 20552 if (opti >= args.length) { 20553 pw.println("Error: permission requires permission name"); 20554 return; 20555 } 20556 permissionNames = new ArraySet<>(); 20557 while (opti < args.length) { 20558 permissionNames.add(args[opti]); 20559 opti++; 20560 } 20561 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20562 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20563 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20564 dumpState.setDump(DumpState.DUMP_PREFERRED); 20565 } else if ("preferred-xml".equals(cmd)) { 20566 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20567 if (opti < args.length && "--full".equals(args[opti])) { 20568 fullPreferred = true; 20569 opti++; 20570 } 20571 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20572 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20573 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20574 dumpState.setDump(DumpState.DUMP_PACKAGES); 20575 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20576 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20577 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20578 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20579 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20580 dumpState.setDump(DumpState.DUMP_MESSAGES); 20581 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20582 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20583 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20584 || "intent-filter-verifiers".equals(cmd)) { 20585 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20586 } else if ("version".equals(cmd)) { 20587 dumpState.setDump(DumpState.DUMP_VERSION); 20588 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20589 dumpState.setDump(DumpState.DUMP_KEYSETS); 20590 } else if ("installs".equals(cmd)) { 20591 dumpState.setDump(DumpState.DUMP_INSTALLS); 20592 } else if ("frozen".equals(cmd)) { 20593 dumpState.setDump(DumpState.DUMP_FROZEN); 20594 } else if ("dexopt".equals(cmd)) { 20595 dumpState.setDump(DumpState.DUMP_DEXOPT); 20596 } else if ("compiler-stats".equals(cmd)) { 20597 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20598 } else if ("enabled-overlays".equals(cmd)) { 20599 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20600 } else if ("write".equals(cmd)) { 20601 synchronized (mPackages) { 20602 mSettings.writeLPr(); 20603 pw.println("Settings written."); 20604 return; 20605 } 20606 } 20607 } 20608 20609 if (checkin) { 20610 pw.println("vers,1"); 20611 } 20612 20613 // reader 20614 synchronized (mPackages) { 20615 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20616 if (!checkin) { 20617 if (dumpState.onTitlePrinted()) 20618 pw.println(); 20619 pw.println("Database versions:"); 20620 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20621 } 20622 } 20623 20624 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20625 if (!checkin) { 20626 if (dumpState.onTitlePrinted()) 20627 pw.println(); 20628 pw.println("Verifiers:"); 20629 pw.print(" Required: "); 20630 pw.print(mRequiredVerifierPackage); 20631 pw.print(" (uid="); 20632 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20633 UserHandle.USER_SYSTEM)); 20634 pw.println(")"); 20635 } else if (mRequiredVerifierPackage != null) { 20636 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20637 pw.print(","); 20638 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20639 UserHandle.USER_SYSTEM)); 20640 } 20641 } 20642 20643 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20644 packageName == null) { 20645 if (mIntentFilterVerifierComponent != null) { 20646 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20647 if (!checkin) { 20648 if (dumpState.onTitlePrinted()) 20649 pw.println(); 20650 pw.println("Intent Filter Verifier:"); 20651 pw.print(" Using: "); 20652 pw.print(verifierPackageName); 20653 pw.print(" (uid="); 20654 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20655 UserHandle.USER_SYSTEM)); 20656 pw.println(")"); 20657 } else if (verifierPackageName != null) { 20658 pw.print("ifv,"); pw.print(verifierPackageName); 20659 pw.print(","); 20660 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20661 UserHandle.USER_SYSTEM)); 20662 } 20663 } else { 20664 pw.println(); 20665 pw.println("No Intent Filter Verifier available!"); 20666 } 20667 } 20668 20669 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20670 boolean printedHeader = false; 20671 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20672 while (it.hasNext()) { 20673 String libName = it.next(); 20674 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20675 if (versionedLib == null) { 20676 continue; 20677 } 20678 final int versionCount = versionedLib.size(); 20679 for (int i = 0; i < versionCount; i++) { 20680 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20681 if (!checkin) { 20682 if (!printedHeader) { 20683 if (dumpState.onTitlePrinted()) 20684 pw.println(); 20685 pw.println("Libraries:"); 20686 printedHeader = true; 20687 } 20688 pw.print(" "); 20689 } else { 20690 pw.print("lib,"); 20691 } 20692 pw.print(libEntry.info.getName()); 20693 if (libEntry.info.isStatic()) { 20694 pw.print(" version=" + libEntry.info.getVersion()); 20695 } 20696 if (!checkin) { 20697 pw.print(" -> "); 20698 } 20699 if (libEntry.path != null) { 20700 pw.print(" (jar) "); 20701 pw.print(libEntry.path); 20702 } else { 20703 pw.print(" (apk) "); 20704 pw.print(libEntry.apk); 20705 } 20706 pw.println(); 20707 } 20708 } 20709 } 20710 20711 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20712 if (dumpState.onTitlePrinted()) 20713 pw.println(); 20714 if (!checkin) { 20715 pw.println("Features:"); 20716 } 20717 20718 synchronized (mAvailableFeatures) { 20719 for (FeatureInfo feat : mAvailableFeatures.values()) { 20720 if (checkin) { 20721 pw.print("feat,"); 20722 pw.print(feat.name); 20723 pw.print(","); 20724 pw.println(feat.version); 20725 } else { 20726 pw.print(" "); 20727 pw.print(feat.name); 20728 if (feat.version > 0) { 20729 pw.print(" version="); 20730 pw.print(feat.version); 20731 } 20732 pw.println(); 20733 } 20734 } 20735 } 20736 } 20737 20738 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20739 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20740 : "Activity Resolver Table:", " ", packageName, 20741 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20742 dumpState.setTitlePrinted(true); 20743 } 20744 } 20745 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20746 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20747 : "Receiver Resolver Table:", " ", packageName, 20748 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20749 dumpState.setTitlePrinted(true); 20750 } 20751 } 20752 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20753 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20754 : "Service Resolver Table:", " ", packageName, 20755 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20756 dumpState.setTitlePrinted(true); 20757 } 20758 } 20759 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20760 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20761 : "Provider Resolver Table:", " ", packageName, 20762 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20763 dumpState.setTitlePrinted(true); 20764 } 20765 } 20766 20767 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20768 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20769 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20770 int user = mSettings.mPreferredActivities.keyAt(i); 20771 if (pir.dump(pw, 20772 dumpState.getTitlePrinted() 20773 ? "\nPreferred Activities User " + user + ":" 20774 : "Preferred Activities User " + user + ":", " ", 20775 packageName, true, false)) { 20776 dumpState.setTitlePrinted(true); 20777 } 20778 } 20779 } 20780 20781 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20782 pw.flush(); 20783 FileOutputStream fout = new FileOutputStream(fd); 20784 BufferedOutputStream str = new BufferedOutputStream(fout); 20785 XmlSerializer serializer = new FastXmlSerializer(); 20786 try { 20787 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20788 serializer.startDocument(null, true); 20789 serializer.setFeature( 20790 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20791 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20792 serializer.endDocument(); 20793 serializer.flush(); 20794 } catch (IllegalArgumentException e) { 20795 pw.println("Failed writing: " + e); 20796 } catch (IllegalStateException e) { 20797 pw.println("Failed writing: " + e); 20798 } catch (IOException e) { 20799 pw.println("Failed writing: " + e); 20800 } 20801 } 20802 20803 if (!checkin 20804 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20805 && packageName == null) { 20806 pw.println(); 20807 int count = mSettings.mPackages.size(); 20808 if (count == 0) { 20809 pw.println("No applications!"); 20810 pw.println(); 20811 } else { 20812 final String prefix = " "; 20813 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20814 if (allPackageSettings.size() == 0) { 20815 pw.println("No domain preferred apps!"); 20816 pw.println(); 20817 } else { 20818 pw.println("App verification status:"); 20819 pw.println(); 20820 count = 0; 20821 for (PackageSetting ps : allPackageSettings) { 20822 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20823 if (ivi == null || ivi.getPackageName() == null) continue; 20824 pw.println(prefix + "Package: " + ivi.getPackageName()); 20825 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20826 pw.println(prefix + "Status: " + ivi.getStatusString()); 20827 pw.println(); 20828 count++; 20829 } 20830 if (count == 0) { 20831 pw.println(prefix + "No app verification established."); 20832 pw.println(); 20833 } 20834 for (int userId : sUserManager.getUserIds()) { 20835 pw.println("App linkages for user " + userId + ":"); 20836 pw.println(); 20837 count = 0; 20838 for (PackageSetting ps : allPackageSettings) { 20839 final long status = ps.getDomainVerificationStatusForUser(userId); 20840 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20841 && !DEBUG_DOMAIN_VERIFICATION) { 20842 continue; 20843 } 20844 pw.println(prefix + "Package: " + ps.name); 20845 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20846 String statusStr = IntentFilterVerificationInfo. 20847 getStatusStringFromValue(status); 20848 pw.println(prefix + "Status: " + statusStr); 20849 pw.println(); 20850 count++; 20851 } 20852 if (count == 0) { 20853 pw.println(prefix + "No configured app linkages."); 20854 pw.println(); 20855 } 20856 } 20857 } 20858 } 20859 } 20860 20861 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20862 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20863 if (packageName == null && permissionNames == null) { 20864 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20865 if (iperm == 0) { 20866 if (dumpState.onTitlePrinted()) 20867 pw.println(); 20868 pw.println("AppOp Permissions:"); 20869 } 20870 pw.print(" AppOp Permission "); 20871 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20872 pw.println(":"); 20873 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20874 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20875 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20876 } 20877 } 20878 } 20879 } 20880 20881 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20882 boolean printedSomething = false; 20883 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20884 if (packageName != null && !packageName.equals(p.info.packageName)) { 20885 continue; 20886 } 20887 if (!printedSomething) { 20888 if (dumpState.onTitlePrinted()) 20889 pw.println(); 20890 pw.println("Registered ContentProviders:"); 20891 printedSomething = true; 20892 } 20893 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20894 pw.print(" "); pw.println(p.toString()); 20895 } 20896 printedSomething = false; 20897 for (Map.Entry<String, PackageParser.Provider> entry : 20898 mProvidersByAuthority.entrySet()) { 20899 PackageParser.Provider p = entry.getValue(); 20900 if (packageName != null && !packageName.equals(p.info.packageName)) { 20901 continue; 20902 } 20903 if (!printedSomething) { 20904 if (dumpState.onTitlePrinted()) 20905 pw.println(); 20906 pw.println("ContentProvider Authorities:"); 20907 printedSomething = true; 20908 } 20909 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20910 pw.print(" "); pw.println(p.toString()); 20911 if (p.info != null && p.info.applicationInfo != null) { 20912 final String appInfo = p.info.applicationInfo.toString(); 20913 pw.print(" applicationInfo="); pw.println(appInfo); 20914 } 20915 } 20916 } 20917 20918 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20919 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20920 } 20921 20922 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20923 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20924 } 20925 20926 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20927 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20928 } 20929 20930 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20931 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20932 } 20933 20934 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20935 // XXX should handle packageName != null by dumping only install data that 20936 // the given package is involved with. 20937 if (dumpState.onTitlePrinted()) pw.println(); 20938 20939 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20940 ipw.println(); 20941 ipw.println("Frozen packages:"); 20942 ipw.increaseIndent(); 20943 if (mFrozenPackages.size() == 0) { 20944 ipw.println("(none)"); 20945 } else { 20946 for (int i = 0; i < mFrozenPackages.size(); i++) { 20947 ipw.println(mFrozenPackages.valueAt(i)); 20948 } 20949 } 20950 ipw.decreaseIndent(); 20951 } 20952 20953 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20954 if (dumpState.onTitlePrinted()) pw.println(); 20955 dumpDexoptStateLPr(pw, packageName); 20956 } 20957 20958 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20959 if (dumpState.onTitlePrinted()) pw.println(); 20960 dumpCompilerStatsLPr(pw, packageName); 20961 } 20962 20963 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20964 if (dumpState.onTitlePrinted()) pw.println(); 20965 dumpEnabledOverlaysLPr(pw); 20966 } 20967 20968 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20969 if (dumpState.onTitlePrinted()) pw.println(); 20970 mSettings.dumpReadMessagesLPr(pw, dumpState); 20971 20972 pw.println(); 20973 pw.println("Package warning messages:"); 20974 BufferedReader in = null; 20975 String line = null; 20976 try { 20977 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20978 while ((line = in.readLine()) != null) { 20979 if (line.contains("ignored: updated version")) continue; 20980 pw.println(line); 20981 } 20982 } catch (IOException ignored) { 20983 } finally { 20984 IoUtils.closeQuietly(in); 20985 } 20986 } 20987 20988 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20989 BufferedReader in = null; 20990 String line = null; 20991 try { 20992 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20993 while ((line = in.readLine()) != null) { 20994 if (line.contains("ignored: updated version")) continue; 20995 pw.print("msg,"); 20996 pw.println(line); 20997 } 20998 } catch (IOException ignored) { 20999 } finally { 21000 IoUtils.closeQuietly(in); 21001 } 21002 } 21003 } 21004 21005 // PackageInstaller should be called outside of mPackages lock 21006 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21007 // XXX should handle packageName != null by dumping only install data that 21008 // the given package is involved with. 21009 if (dumpState.onTitlePrinted()) pw.println(); 21010 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21011 } 21012 } 21013 21014 private void dumpProto(FileDescriptor fd) { 21015 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21016 21017 synchronized (mPackages) { 21018 final long requiredVerifierPackageToken = 21019 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21020 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21021 proto.write( 21022 PackageServiceDumpProto.PackageShortProto.UID, 21023 getPackageUid( 21024 mRequiredVerifierPackage, 21025 MATCH_DEBUG_TRIAGED_MISSING, 21026 UserHandle.USER_SYSTEM)); 21027 proto.end(requiredVerifierPackageToken); 21028 21029 if (mIntentFilterVerifierComponent != null) { 21030 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21031 final long verifierPackageToken = 21032 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21033 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21034 proto.write( 21035 PackageServiceDumpProto.PackageShortProto.UID, 21036 getPackageUid( 21037 verifierPackageName, 21038 MATCH_DEBUG_TRIAGED_MISSING, 21039 UserHandle.USER_SYSTEM)); 21040 proto.end(verifierPackageToken); 21041 } 21042 21043 dumpSharedLibrariesProto(proto); 21044 dumpFeaturesProto(proto); 21045 mSettings.dumpPackagesProto(proto); 21046 mSettings.dumpSharedUsersProto(proto); 21047 dumpMessagesProto(proto); 21048 } 21049 proto.flush(); 21050 } 21051 21052 private void dumpMessagesProto(ProtoOutputStream proto) { 21053 BufferedReader in = null; 21054 String line = null; 21055 try { 21056 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21057 while ((line = in.readLine()) != null) { 21058 if (line.contains("ignored: updated version")) continue; 21059 proto.write(PackageServiceDumpProto.MESSAGES, line); 21060 } 21061 } catch (IOException ignored) { 21062 } finally { 21063 IoUtils.closeQuietly(in); 21064 } 21065 } 21066 21067 private void dumpFeaturesProto(ProtoOutputStream proto) { 21068 synchronized (mAvailableFeatures) { 21069 final int count = mAvailableFeatures.size(); 21070 for (int i = 0; i < count; i++) { 21071 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21072 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21073 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21074 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21075 proto.end(featureToken); 21076 } 21077 } 21078 } 21079 21080 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21081 final int count = mSharedLibraries.size(); 21082 for (int i = 0; i < count; i++) { 21083 final String libName = mSharedLibraries.keyAt(i); 21084 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21085 if (versionedLib == null) { 21086 continue; 21087 } 21088 final int versionCount = versionedLib.size(); 21089 for (int j = 0; j < versionCount; j++) { 21090 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21091 final long sharedLibraryToken = 21092 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21093 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21094 final boolean isJar = (libEntry.path != null); 21095 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21096 if (isJar) { 21097 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21098 } else { 21099 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21100 } 21101 proto.end(sharedLibraryToken); 21102 } 21103 } 21104 } 21105 21106 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21107 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21108 ipw.println(); 21109 ipw.println("Dexopt state:"); 21110 ipw.increaseIndent(); 21111 Collection<PackageParser.Package> packages = null; 21112 if (packageName != null) { 21113 PackageParser.Package targetPackage = mPackages.get(packageName); 21114 if (targetPackage != null) { 21115 packages = Collections.singletonList(targetPackage); 21116 } else { 21117 ipw.println("Unable to find package: " + packageName); 21118 return; 21119 } 21120 } else { 21121 packages = mPackages.values(); 21122 } 21123 21124 for (PackageParser.Package pkg : packages) { 21125 ipw.println("[" + pkg.packageName + "]"); 21126 ipw.increaseIndent(); 21127 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21128 ipw.decreaseIndent(); 21129 } 21130 } 21131 21132 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21133 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21134 ipw.println(); 21135 ipw.println("Compiler stats:"); 21136 ipw.increaseIndent(); 21137 Collection<PackageParser.Package> packages = null; 21138 if (packageName != null) { 21139 PackageParser.Package targetPackage = mPackages.get(packageName); 21140 if (targetPackage != null) { 21141 packages = Collections.singletonList(targetPackage); 21142 } else { 21143 ipw.println("Unable to find package: " + packageName); 21144 return; 21145 } 21146 } else { 21147 packages = mPackages.values(); 21148 } 21149 21150 for (PackageParser.Package pkg : packages) { 21151 ipw.println("[" + pkg.packageName + "]"); 21152 ipw.increaseIndent(); 21153 21154 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21155 if (stats == null) { 21156 ipw.println("(No recorded stats)"); 21157 } else { 21158 stats.dump(ipw); 21159 } 21160 ipw.decreaseIndent(); 21161 } 21162 } 21163 21164 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21165 pw.println("Enabled overlay paths:"); 21166 final int N = mEnabledOverlayPaths.size(); 21167 for (int i = 0; i < N; i++) { 21168 final int userId = mEnabledOverlayPaths.keyAt(i); 21169 pw.println(String.format(" User %d:", userId)); 21170 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21171 mEnabledOverlayPaths.valueAt(i); 21172 final int M = userSpecificOverlays.size(); 21173 for (int j = 0; j < M; j++) { 21174 final String targetPackageName = userSpecificOverlays.keyAt(j); 21175 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21176 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21177 } 21178 } 21179 } 21180 21181 private String dumpDomainString(String packageName) { 21182 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21183 .getList(); 21184 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21185 21186 ArraySet<String> result = new ArraySet<>(); 21187 if (iviList.size() > 0) { 21188 for (IntentFilterVerificationInfo ivi : iviList) { 21189 for (String host : ivi.getDomains()) { 21190 result.add(host); 21191 } 21192 } 21193 } 21194 if (filters != null && filters.size() > 0) { 21195 for (IntentFilter filter : filters) { 21196 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21197 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21198 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21199 result.addAll(filter.getHostsList()); 21200 } 21201 } 21202 } 21203 21204 StringBuilder sb = new StringBuilder(result.size() * 16); 21205 for (String domain : result) { 21206 if (sb.length() > 0) sb.append(" "); 21207 sb.append(domain); 21208 } 21209 return sb.toString(); 21210 } 21211 21212 // ------- apps on sdcard specific code ------- 21213 static final boolean DEBUG_SD_INSTALL = false; 21214 21215 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21216 21217 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21218 21219 private boolean mMediaMounted = false; 21220 21221 static String getEncryptKey() { 21222 try { 21223 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21224 SD_ENCRYPTION_KEYSTORE_NAME); 21225 if (sdEncKey == null) { 21226 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21227 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21228 if (sdEncKey == null) { 21229 Slog.e(TAG, "Failed to create encryption keys"); 21230 return null; 21231 } 21232 } 21233 return sdEncKey; 21234 } catch (NoSuchAlgorithmException nsae) { 21235 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21236 return null; 21237 } catch (IOException ioe) { 21238 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21239 return null; 21240 } 21241 } 21242 21243 /* 21244 * Update media status on PackageManager. 21245 */ 21246 @Override 21247 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21248 int callingUid = Binder.getCallingUid(); 21249 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21250 throw new SecurityException("Media status can only be updated by the system"); 21251 } 21252 // reader; this apparently protects mMediaMounted, but should probably 21253 // be a different lock in that case. 21254 synchronized (mPackages) { 21255 Log.i(TAG, "Updating external media status from " 21256 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21257 + (mediaStatus ? "mounted" : "unmounted")); 21258 if (DEBUG_SD_INSTALL) 21259 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21260 + ", mMediaMounted=" + mMediaMounted); 21261 if (mediaStatus == mMediaMounted) { 21262 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21263 : 0, -1); 21264 mHandler.sendMessage(msg); 21265 return; 21266 } 21267 mMediaMounted = mediaStatus; 21268 } 21269 // Queue up an async operation since the package installation may take a 21270 // little while. 21271 mHandler.post(new Runnable() { 21272 public void run() { 21273 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21274 } 21275 }); 21276 } 21277 21278 /** 21279 * Called by StorageManagerService when the initial ASECs to scan are available. 21280 * Should block until all the ASEC containers are finished being scanned. 21281 */ 21282 public void scanAvailableAsecs() { 21283 updateExternalMediaStatusInner(true, false, false); 21284 } 21285 21286 /* 21287 * Collect information of applications on external media, map them against 21288 * existing containers and update information based on current mount status. 21289 * Please note that we always have to report status if reportStatus has been 21290 * set to true especially when unloading packages. 21291 */ 21292 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21293 boolean externalStorage) { 21294 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21295 int[] uidArr = EmptyArray.INT; 21296 21297 final String[] list = PackageHelper.getSecureContainerList(); 21298 if (ArrayUtils.isEmpty(list)) { 21299 Log.i(TAG, "No secure containers found"); 21300 } else { 21301 // Process list of secure containers and categorize them 21302 // as active or stale based on their package internal state. 21303 21304 // reader 21305 synchronized (mPackages) { 21306 for (String cid : list) { 21307 // Leave stages untouched for now; installer service owns them 21308 if (PackageInstallerService.isStageName(cid)) continue; 21309 21310 if (DEBUG_SD_INSTALL) 21311 Log.i(TAG, "Processing container " + cid); 21312 String pkgName = getAsecPackageName(cid); 21313 if (pkgName == null) { 21314 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21315 continue; 21316 } 21317 if (DEBUG_SD_INSTALL) 21318 Log.i(TAG, "Looking for pkg : " + pkgName); 21319 21320 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21321 if (ps == null) { 21322 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21323 continue; 21324 } 21325 21326 /* 21327 * Skip packages that are not external if we're unmounting 21328 * external storage. 21329 */ 21330 if (externalStorage && !isMounted && !isExternal(ps)) { 21331 continue; 21332 } 21333 21334 final AsecInstallArgs args = new AsecInstallArgs(cid, 21335 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21336 // The package status is changed only if the code path 21337 // matches between settings and the container id. 21338 if (ps.codePathString != null 21339 && ps.codePathString.startsWith(args.getCodePath())) { 21340 if (DEBUG_SD_INSTALL) { 21341 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21342 + " at code path: " + ps.codePathString); 21343 } 21344 21345 // We do have a valid package installed on sdcard 21346 processCids.put(args, ps.codePathString); 21347 final int uid = ps.appId; 21348 if (uid != -1) { 21349 uidArr = ArrayUtils.appendInt(uidArr, uid); 21350 } 21351 } else { 21352 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21353 + ps.codePathString); 21354 } 21355 } 21356 } 21357 21358 Arrays.sort(uidArr); 21359 } 21360 21361 // Process packages with valid entries. 21362 if (isMounted) { 21363 if (DEBUG_SD_INSTALL) 21364 Log.i(TAG, "Loading packages"); 21365 loadMediaPackages(processCids, uidArr, externalStorage); 21366 startCleaningPackages(); 21367 mInstallerService.onSecureContainersAvailable(); 21368 } else { 21369 if (DEBUG_SD_INSTALL) 21370 Log.i(TAG, "Unloading packages"); 21371 unloadMediaPackages(processCids, uidArr, reportStatus); 21372 } 21373 } 21374 21375 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21376 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21377 final int size = infos.size(); 21378 final String[] packageNames = new String[size]; 21379 final int[] packageUids = new int[size]; 21380 for (int i = 0; i < size; i++) { 21381 final ApplicationInfo info = infos.get(i); 21382 packageNames[i] = info.packageName; 21383 packageUids[i] = info.uid; 21384 } 21385 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21386 finishedReceiver); 21387 } 21388 21389 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21390 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21391 sendResourcesChangedBroadcast(mediaStatus, replacing, 21392 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21393 } 21394 21395 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21396 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21397 int size = pkgList.length; 21398 if (size > 0) { 21399 // Send broadcasts here 21400 Bundle extras = new Bundle(); 21401 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21402 if (uidArr != null) { 21403 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21404 } 21405 if (replacing) { 21406 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21407 } 21408 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21409 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21410 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21411 } 21412 } 21413 21414 /* 21415 * Look at potentially valid container ids from processCids If package 21416 * information doesn't match the one on record or package scanning fails, 21417 * the cid is added to list of removeCids. We currently don't delete stale 21418 * containers. 21419 */ 21420 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21421 boolean externalStorage) { 21422 ArrayList<String> pkgList = new ArrayList<String>(); 21423 Set<AsecInstallArgs> keys = processCids.keySet(); 21424 21425 for (AsecInstallArgs args : keys) { 21426 String codePath = processCids.get(args); 21427 if (DEBUG_SD_INSTALL) 21428 Log.i(TAG, "Loading container : " + args.cid); 21429 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21430 try { 21431 // Make sure there are no container errors first. 21432 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21433 Slog.e(TAG, "Failed to mount cid : " + args.cid 21434 + " when installing from sdcard"); 21435 continue; 21436 } 21437 // Check code path here. 21438 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21439 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21440 + " does not match one in settings " + codePath); 21441 continue; 21442 } 21443 // Parse package 21444 int parseFlags = mDefParseFlags; 21445 if (args.isExternalAsec()) { 21446 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21447 } 21448 if (args.isFwdLocked()) { 21449 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21450 } 21451 21452 synchronized (mInstallLock) { 21453 PackageParser.Package pkg = null; 21454 try { 21455 // Sadly we don't know the package name yet to freeze it 21456 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21457 SCAN_IGNORE_FROZEN, 0, null); 21458 } catch (PackageManagerException e) { 21459 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21460 } 21461 // Scan the package 21462 if (pkg != null) { 21463 /* 21464 * TODO why is the lock being held? doPostInstall is 21465 * called in other places without the lock. This needs 21466 * to be straightened out. 21467 */ 21468 // writer 21469 synchronized (mPackages) { 21470 retCode = PackageManager.INSTALL_SUCCEEDED; 21471 pkgList.add(pkg.packageName); 21472 // Post process args 21473 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21474 pkg.applicationInfo.uid); 21475 } 21476 } else { 21477 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21478 } 21479 } 21480 21481 } finally { 21482 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21483 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21484 } 21485 } 21486 } 21487 // writer 21488 synchronized (mPackages) { 21489 // If the platform SDK has changed since the last time we booted, 21490 // we need to re-grant app permission to catch any new ones that 21491 // appear. This is really a hack, and means that apps can in some 21492 // cases get permissions that the user didn't initially explicitly 21493 // allow... it would be nice to have some better way to handle 21494 // this situation. 21495 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21496 : mSettings.getInternalVersion(); 21497 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21498 : StorageManager.UUID_PRIVATE_INTERNAL; 21499 21500 int updateFlags = UPDATE_PERMISSIONS_ALL; 21501 if (ver.sdkVersion != mSdkVersion) { 21502 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21503 + mSdkVersion + "; regranting permissions for external"); 21504 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21505 } 21506 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21507 21508 // Yay, everything is now upgraded 21509 ver.forceCurrent(); 21510 21511 // can downgrade to reader 21512 // Persist settings 21513 mSettings.writeLPr(); 21514 } 21515 // Send a broadcast to let everyone know we are done processing 21516 if (pkgList.size() > 0) { 21517 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21518 } 21519 } 21520 21521 /* 21522 * Utility method to unload a list of specified containers 21523 */ 21524 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21525 // Just unmount all valid containers. 21526 for (AsecInstallArgs arg : cidArgs) { 21527 synchronized (mInstallLock) { 21528 arg.doPostDeleteLI(false); 21529 } 21530 } 21531 } 21532 21533 /* 21534 * Unload packages mounted on external media. This involves deleting package 21535 * data from internal structures, sending broadcasts about disabled packages, 21536 * gc'ing to free up references, unmounting all secure containers 21537 * corresponding to packages on external media, and posting a 21538 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21539 * that we always have to post this message if status has been requested no 21540 * matter what. 21541 */ 21542 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21543 final boolean reportStatus) { 21544 if (DEBUG_SD_INSTALL) 21545 Log.i(TAG, "unloading media packages"); 21546 ArrayList<String> pkgList = new ArrayList<String>(); 21547 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21548 final Set<AsecInstallArgs> keys = processCids.keySet(); 21549 for (AsecInstallArgs args : keys) { 21550 String pkgName = args.getPackageName(); 21551 if (DEBUG_SD_INSTALL) 21552 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21553 // Delete package internally 21554 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21555 synchronized (mInstallLock) { 21556 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21557 final boolean res; 21558 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21559 "unloadMediaPackages")) { 21560 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21561 null); 21562 } 21563 if (res) { 21564 pkgList.add(pkgName); 21565 } else { 21566 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21567 failedList.add(args); 21568 } 21569 } 21570 } 21571 21572 // reader 21573 synchronized (mPackages) { 21574 // We didn't update the settings after removing each package; 21575 // write them now for all packages. 21576 mSettings.writeLPr(); 21577 } 21578 21579 // We have to absolutely send UPDATED_MEDIA_STATUS only 21580 // after confirming that all the receivers processed the ordered 21581 // broadcast when packages get disabled, force a gc to clean things up. 21582 // and unload all the containers. 21583 if (pkgList.size() > 0) { 21584 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21585 new IIntentReceiver.Stub() { 21586 public void performReceive(Intent intent, int resultCode, String data, 21587 Bundle extras, boolean ordered, boolean sticky, 21588 int sendingUser) throws RemoteException { 21589 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21590 reportStatus ? 1 : 0, 1, keys); 21591 mHandler.sendMessage(msg); 21592 } 21593 }); 21594 } else { 21595 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21596 keys); 21597 mHandler.sendMessage(msg); 21598 } 21599 } 21600 21601 private void loadPrivatePackages(final VolumeInfo vol) { 21602 mHandler.post(new Runnable() { 21603 @Override 21604 public void run() { 21605 loadPrivatePackagesInner(vol); 21606 } 21607 }); 21608 } 21609 21610 private void loadPrivatePackagesInner(VolumeInfo vol) { 21611 final String volumeUuid = vol.fsUuid; 21612 if (TextUtils.isEmpty(volumeUuid)) { 21613 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21614 return; 21615 } 21616 21617 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21618 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21619 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21620 21621 final VersionInfo ver; 21622 final List<PackageSetting> packages; 21623 synchronized (mPackages) { 21624 ver = mSettings.findOrCreateVersion(volumeUuid); 21625 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21626 } 21627 21628 for (PackageSetting ps : packages) { 21629 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21630 synchronized (mInstallLock) { 21631 final PackageParser.Package pkg; 21632 try { 21633 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21634 loaded.add(pkg.applicationInfo); 21635 21636 } catch (PackageManagerException e) { 21637 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21638 } 21639 21640 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21641 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21642 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21643 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21644 } 21645 } 21646 } 21647 21648 // Reconcile app data for all started/unlocked users 21649 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21650 final UserManager um = mContext.getSystemService(UserManager.class); 21651 UserManagerInternal umInternal = getUserManagerInternal(); 21652 for (UserInfo user : um.getUsers()) { 21653 final int flags; 21654 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21655 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21656 } else if (umInternal.isUserRunning(user.id)) { 21657 flags = StorageManager.FLAG_STORAGE_DE; 21658 } else { 21659 continue; 21660 } 21661 21662 try { 21663 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21664 synchronized (mInstallLock) { 21665 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21666 } 21667 } catch (IllegalStateException e) { 21668 // Device was probably ejected, and we'll process that event momentarily 21669 Slog.w(TAG, "Failed to prepare storage: " + e); 21670 } 21671 } 21672 21673 synchronized (mPackages) { 21674 int updateFlags = UPDATE_PERMISSIONS_ALL; 21675 if (ver.sdkVersion != mSdkVersion) { 21676 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21677 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21678 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21679 } 21680 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21681 21682 // Yay, everything is now upgraded 21683 ver.forceCurrent(); 21684 21685 mSettings.writeLPr(); 21686 } 21687 21688 for (PackageFreezer freezer : freezers) { 21689 freezer.close(); 21690 } 21691 21692 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21693 sendResourcesChangedBroadcast(true, false, loaded, null); 21694 } 21695 21696 private void unloadPrivatePackages(final VolumeInfo vol) { 21697 mHandler.post(new Runnable() { 21698 @Override 21699 public void run() { 21700 unloadPrivatePackagesInner(vol); 21701 } 21702 }); 21703 } 21704 21705 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21706 final String volumeUuid = vol.fsUuid; 21707 if (TextUtils.isEmpty(volumeUuid)) { 21708 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21709 return; 21710 } 21711 21712 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21713 synchronized (mInstallLock) { 21714 synchronized (mPackages) { 21715 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21716 for (PackageSetting ps : packages) { 21717 if (ps.pkg == null) continue; 21718 21719 final ApplicationInfo info = ps.pkg.applicationInfo; 21720 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21721 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21722 21723 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21724 "unloadPrivatePackagesInner")) { 21725 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21726 false, null)) { 21727 unloaded.add(info); 21728 } else { 21729 Slog.w(TAG, "Failed to unload " + ps.codePath); 21730 } 21731 } 21732 21733 // Try very hard to release any references to this package 21734 // so we don't risk the system server being killed due to 21735 // open FDs 21736 AttributeCache.instance().removePackage(ps.name); 21737 } 21738 21739 mSettings.writeLPr(); 21740 } 21741 } 21742 21743 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21744 sendResourcesChangedBroadcast(false, false, unloaded, null); 21745 21746 // Try very hard to release any references to this path so we don't risk 21747 // the system server being killed due to open FDs 21748 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21749 21750 for (int i = 0; i < 3; i++) { 21751 System.gc(); 21752 System.runFinalization(); 21753 } 21754 } 21755 21756 private void assertPackageKnown(String volumeUuid, String packageName) 21757 throws PackageManagerException { 21758 synchronized (mPackages) { 21759 // Normalize package name to handle renamed packages 21760 packageName = normalizePackageNameLPr(packageName); 21761 21762 final PackageSetting ps = mSettings.mPackages.get(packageName); 21763 if (ps == null) { 21764 throw new PackageManagerException("Package " + packageName + " is unknown"); 21765 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21766 throw new PackageManagerException( 21767 "Package " + packageName + " found on unknown volume " + volumeUuid 21768 + "; expected volume " + ps.volumeUuid); 21769 } 21770 } 21771 } 21772 21773 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21774 throws PackageManagerException { 21775 synchronized (mPackages) { 21776 // Normalize package name to handle renamed packages 21777 packageName = normalizePackageNameLPr(packageName); 21778 21779 final PackageSetting ps = mSettings.mPackages.get(packageName); 21780 if (ps == null) { 21781 throw new PackageManagerException("Package " + packageName + " is unknown"); 21782 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21783 throw new PackageManagerException( 21784 "Package " + packageName + " found on unknown volume " + volumeUuid 21785 + "; expected volume " + ps.volumeUuid); 21786 } else if (!ps.getInstalled(userId)) { 21787 throw new PackageManagerException( 21788 "Package " + packageName + " not installed for user " + userId); 21789 } 21790 } 21791 } 21792 21793 private List<String> collectAbsoluteCodePaths() { 21794 synchronized (mPackages) { 21795 List<String> codePaths = new ArrayList<>(); 21796 final int packageCount = mSettings.mPackages.size(); 21797 for (int i = 0; i < packageCount; i++) { 21798 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21799 codePaths.add(ps.codePath.getAbsolutePath()); 21800 } 21801 return codePaths; 21802 } 21803 } 21804 21805 /** 21806 * Examine all apps present on given mounted volume, and destroy apps that 21807 * aren't expected, either due to uninstallation or reinstallation on 21808 * another volume. 21809 */ 21810 private void reconcileApps(String volumeUuid) { 21811 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21812 List<File> filesToDelete = null; 21813 21814 final File[] files = FileUtils.listFilesOrEmpty( 21815 Environment.getDataAppDirectory(volumeUuid)); 21816 for (File file : files) { 21817 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21818 && !PackageInstallerService.isStageName(file.getName()); 21819 if (!isPackage) { 21820 // Ignore entries which are not packages 21821 continue; 21822 } 21823 21824 String absolutePath = file.getAbsolutePath(); 21825 21826 boolean pathValid = false; 21827 final int absoluteCodePathCount = absoluteCodePaths.size(); 21828 for (int i = 0; i < absoluteCodePathCount; i++) { 21829 String absoluteCodePath = absoluteCodePaths.get(i); 21830 if (absolutePath.startsWith(absoluteCodePath)) { 21831 pathValid = true; 21832 break; 21833 } 21834 } 21835 21836 if (!pathValid) { 21837 if (filesToDelete == null) { 21838 filesToDelete = new ArrayList<>(); 21839 } 21840 filesToDelete.add(file); 21841 } 21842 } 21843 21844 if (filesToDelete != null) { 21845 final int fileToDeleteCount = filesToDelete.size(); 21846 for (int i = 0; i < fileToDeleteCount; i++) { 21847 File fileToDelete = filesToDelete.get(i); 21848 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21849 synchronized (mInstallLock) { 21850 removeCodePathLI(fileToDelete); 21851 } 21852 } 21853 } 21854 } 21855 21856 /** 21857 * Reconcile all app data for the given user. 21858 * <p> 21859 * Verifies that directories exist and that ownership and labeling is 21860 * correct for all installed apps on all mounted volumes. 21861 */ 21862 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21863 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21864 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21865 final String volumeUuid = vol.getFsUuid(); 21866 synchronized (mInstallLock) { 21867 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21868 } 21869 } 21870 } 21871 21872 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21873 boolean migrateAppData) { 21874 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21875 } 21876 21877 /** 21878 * Reconcile all app data on given mounted volume. 21879 * <p> 21880 * Destroys app data that isn't expected, either due to uninstallation or 21881 * reinstallation on another volume. 21882 * <p> 21883 * Verifies that directories exist and that ownership and labeling is 21884 * correct for all installed apps. 21885 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21886 */ 21887 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21888 boolean migrateAppData, boolean onlyCoreApps) { 21889 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21890 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21891 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21892 21893 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21894 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21895 21896 // First look for stale data that doesn't belong, and check if things 21897 // have changed since we did our last restorecon 21898 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21899 if (StorageManager.isFileEncryptedNativeOrEmulated() 21900 && !StorageManager.isUserKeyUnlocked(userId)) { 21901 throw new RuntimeException( 21902 "Yikes, someone asked us to reconcile CE storage while " + userId 21903 + " was still locked; this would have caused massive data loss!"); 21904 } 21905 21906 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21907 for (File file : files) { 21908 final String packageName = file.getName(); 21909 try { 21910 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21911 } catch (PackageManagerException e) { 21912 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21913 try { 21914 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21915 StorageManager.FLAG_STORAGE_CE, 0); 21916 } catch (InstallerException e2) { 21917 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21918 } 21919 } 21920 } 21921 } 21922 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21923 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21924 for (File file : files) { 21925 final String packageName = file.getName(); 21926 try { 21927 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21928 } catch (PackageManagerException e) { 21929 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21930 try { 21931 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21932 StorageManager.FLAG_STORAGE_DE, 0); 21933 } catch (InstallerException e2) { 21934 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21935 } 21936 } 21937 } 21938 } 21939 21940 // Ensure that data directories are ready to roll for all packages 21941 // installed for this volume and user 21942 final List<PackageSetting> packages; 21943 synchronized (mPackages) { 21944 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21945 } 21946 int preparedCount = 0; 21947 for (PackageSetting ps : packages) { 21948 final String packageName = ps.name; 21949 if (ps.pkg == null) { 21950 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21951 // TODO: might be due to legacy ASEC apps; we should circle back 21952 // and reconcile again once they're scanned 21953 continue; 21954 } 21955 // Skip non-core apps if requested 21956 if (onlyCoreApps && !ps.pkg.coreApp) { 21957 result.add(packageName); 21958 continue; 21959 } 21960 21961 if (ps.getInstalled(userId)) { 21962 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21963 preparedCount++; 21964 } 21965 } 21966 21967 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21968 return result; 21969 } 21970 21971 /** 21972 * Prepare app data for the given app just after it was installed or 21973 * upgraded. This method carefully only touches users that it's installed 21974 * for, and it forces a restorecon to handle any seinfo changes. 21975 * <p> 21976 * Verifies that directories exist and that ownership and labeling is 21977 * correct for all installed apps. If there is an ownership mismatch, it 21978 * will try recovering system apps by wiping data; third-party app data is 21979 * left intact. 21980 * <p> 21981 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21982 */ 21983 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21984 final PackageSetting ps; 21985 synchronized (mPackages) { 21986 ps = mSettings.mPackages.get(pkg.packageName); 21987 mSettings.writeKernelMappingLPr(ps); 21988 } 21989 21990 final UserManager um = mContext.getSystemService(UserManager.class); 21991 UserManagerInternal umInternal = getUserManagerInternal(); 21992 for (UserInfo user : um.getUsers()) { 21993 final int flags; 21994 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21995 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21996 } else if (umInternal.isUserRunning(user.id)) { 21997 flags = StorageManager.FLAG_STORAGE_DE; 21998 } else { 21999 continue; 22000 } 22001 22002 if (ps.getInstalled(user.id)) { 22003 // TODO: when user data is locked, mark that we're still dirty 22004 prepareAppDataLIF(pkg, user.id, flags); 22005 } 22006 } 22007 } 22008 22009 /** 22010 * Prepare app data for the given app. 22011 * <p> 22012 * Verifies that directories exist and that ownership and labeling is 22013 * correct for all installed apps. If there is an ownership mismatch, this 22014 * will try recovering system apps by wiping data; third-party app data is 22015 * left intact. 22016 */ 22017 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22018 if (pkg == null) { 22019 Slog.wtf(TAG, "Package was null!", new Throwable()); 22020 return; 22021 } 22022 prepareAppDataLeafLIF(pkg, userId, flags); 22023 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22024 for (int i = 0; i < childCount; i++) { 22025 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22026 } 22027 } 22028 22029 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22030 boolean maybeMigrateAppData) { 22031 prepareAppDataLIF(pkg, userId, flags); 22032 22033 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22034 // We may have just shuffled around app data directories, so 22035 // prepare them one more time 22036 prepareAppDataLIF(pkg, userId, flags); 22037 } 22038 } 22039 22040 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22041 if (DEBUG_APP_DATA) { 22042 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22043 + Integer.toHexString(flags)); 22044 } 22045 22046 final String volumeUuid = pkg.volumeUuid; 22047 final String packageName = pkg.packageName; 22048 final ApplicationInfo app = pkg.applicationInfo; 22049 final int appId = UserHandle.getAppId(app.uid); 22050 22051 Preconditions.checkNotNull(app.seInfo); 22052 22053 long ceDataInode = -1; 22054 try { 22055 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22056 appId, app.seInfo, app.targetSdkVersion); 22057 } catch (InstallerException e) { 22058 if (app.isSystemApp()) { 22059 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22060 + ", but trying to recover: " + e); 22061 destroyAppDataLeafLIF(pkg, userId, flags); 22062 try { 22063 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22064 appId, app.seInfo, app.targetSdkVersion); 22065 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22066 } catch (InstallerException e2) { 22067 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22068 } 22069 } else { 22070 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22071 } 22072 } 22073 22074 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22075 // TODO: mark this structure as dirty so we persist it! 22076 synchronized (mPackages) { 22077 final PackageSetting ps = mSettings.mPackages.get(packageName); 22078 if (ps != null) { 22079 ps.setCeDataInode(ceDataInode, userId); 22080 } 22081 } 22082 } 22083 22084 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22085 } 22086 22087 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22088 if (pkg == null) { 22089 Slog.wtf(TAG, "Package was null!", new Throwable()); 22090 return; 22091 } 22092 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22093 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22094 for (int i = 0; i < childCount; i++) { 22095 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22096 } 22097 } 22098 22099 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22100 final String volumeUuid = pkg.volumeUuid; 22101 final String packageName = pkg.packageName; 22102 final ApplicationInfo app = pkg.applicationInfo; 22103 22104 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22105 // Create a native library symlink only if we have native libraries 22106 // and if the native libraries are 32 bit libraries. We do not provide 22107 // this symlink for 64 bit libraries. 22108 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22109 final String nativeLibPath = app.nativeLibraryDir; 22110 try { 22111 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22112 nativeLibPath, userId); 22113 } catch (InstallerException e) { 22114 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22115 } 22116 } 22117 } 22118 } 22119 22120 /** 22121 * For system apps on non-FBE devices, this method migrates any existing 22122 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22123 * requested by the app. 22124 */ 22125 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22126 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22127 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22128 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22129 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22130 try { 22131 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22132 storageTarget); 22133 } catch (InstallerException e) { 22134 logCriticalInfo(Log.WARN, 22135 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22136 } 22137 return true; 22138 } else { 22139 return false; 22140 } 22141 } 22142 22143 public PackageFreezer freezePackage(String packageName, String killReason) { 22144 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22145 } 22146 22147 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22148 return new PackageFreezer(packageName, userId, killReason); 22149 } 22150 22151 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22152 String killReason) { 22153 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22154 } 22155 22156 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22157 String killReason) { 22158 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22159 return new PackageFreezer(); 22160 } else { 22161 return freezePackage(packageName, userId, killReason); 22162 } 22163 } 22164 22165 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22166 String killReason) { 22167 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22168 } 22169 22170 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22171 String killReason) { 22172 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22173 return new PackageFreezer(); 22174 } else { 22175 return freezePackage(packageName, userId, killReason); 22176 } 22177 } 22178 22179 /** 22180 * Class that freezes and kills the given package upon creation, and 22181 * unfreezes it upon closing. This is typically used when doing surgery on 22182 * app code/data to prevent the app from running while you're working. 22183 */ 22184 private class PackageFreezer implements AutoCloseable { 22185 private final String mPackageName; 22186 private final PackageFreezer[] mChildren; 22187 22188 private final boolean mWeFroze; 22189 22190 private final AtomicBoolean mClosed = new AtomicBoolean(); 22191 private final CloseGuard mCloseGuard = CloseGuard.get(); 22192 22193 /** 22194 * Create and return a stub freezer that doesn't actually do anything, 22195 * typically used when someone requested 22196 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22197 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22198 */ 22199 public PackageFreezer() { 22200 mPackageName = null; 22201 mChildren = null; 22202 mWeFroze = false; 22203 mCloseGuard.open("close"); 22204 } 22205 22206 public PackageFreezer(String packageName, int userId, String killReason) { 22207 synchronized (mPackages) { 22208 mPackageName = packageName; 22209 mWeFroze = mFrozenPackages.add(mPackageName); 22210 22211 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22212 if (ps != null) { 22213 killApplication(ps.name, ps.appId, userId, killReason); 22214 } 22215 22216 final PackageParser.Package p = mPackages.get(packageName); 22217 if (p != null && p.childPackages != null) { 22218 final int N = p.childPackages.size(); 22219 mChildren = new PackageFreezer[N]; 22220 for (int i = 0; i < N; i++) { 22221 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22222 userId, killReason); 22223 } 22224 } else { 22225 mChildren = null; 22226 } 22227 } 22228 mCloseGuard.open("close"); 22229 } 22230 22231 @Override 22232 protected void finalize() throws Throwable { 22233 try { 22234 mCloseGuard.warnIfOpen(); 22235 close(); 22236 } finally { 22237 super.finalize(); 22238 } 22239 } 22240 22241 @Override 22242 public void close() { 22243 mCloseGuard.close(); 22244 if (mClosed.compareAndSet(false, true)) { 22245 synchronized (mPackages) { 22246 if (mWeFroze) { 22247 mFrozenPackages.remove(mPackageName); 22248 } 22249 22250 if (mChildren != null) { 22251 for (PackageFreezer freezer : mChildren) { 22252 freezer.close(); 22253 } 22254 } 22255 } 22256 } 22257 } 22258 } 22259 22260 /** 22261 * Verify that given package is currently frozen. 22262 */ 22263 private void checkPackageFrozen(String packageName) { 22264 synchronized (mPackages) { 22265 if (!mFrozenPackages.contains(packageName)) { 22266 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22267 } 22268 } 22269 } 22270 22271 @Override 22272 public int movePackage(final String packageName, final String volumeUuid) { 22273 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22274 22275 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22276 final int moveId = mNextMoveId.getAndIncrement(); 22277 mHandler.post(new Runnable() { 22278 @Override 22279 public void run() { 22280 try { 22281 movePackageInternal(packageName, volumeUuid, moveId, user); 22282 } catch (PackageManagerException e) { 22283 Slog.w(TAG, "Failed to move " + packageName, e); 22284 mMoveCallbacks.notifyStatusChanged(moveId, 22285 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22286 } 22287 } 22288 }); 22289 return moveId; 22290 } 22291 22292 private void movePackageInternal(final String packageName, final String volumeUuid, 22293 final int moveId, UserHandle user) throws PackageManagerException { 22294 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22295 final PackageManager pm = mContext.getPackageManager(); 22296 22297 final boolean currentAsec; 22298 final String currentVolumeUuid; 22299 final File codeFile; 22300 final String installerPackageName; 22301 final String packageAbiOverride; 22302 final int appId; 22303 final String seinfo; 22304 final String label; 22305 final int targetSdkVersion; 22306 final PackageFreezer freezer; 22307 final int[] installedUserIds; 22308 22309 // reader 22310 synchronized (mPackages) { 22311 final PackageParser.Package pkg = mPackages.get(packageName); 22312 final PackageSetting ps = mSettings.mPackages.get(packageName); 22313 if (pkg == null || ps == null) { 22314 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22315 } 22316 22317 if (pkg.applicationInfo.isSystemApp()) { 22318 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22319 "Cannot move system application"); 22320 } 22321 22322 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22323 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22324 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22325 if (isInternalStorage && !allow3rdPartyOnInternal) { 22326 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22327 "3rd party apps are not allowed on internal storage"); 22328 } 22329 22330 if (pkg.applicationInfo.isExternalAsec()) { 22331 currentAsec = true; 22332 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22333 } else if (pkg.applicationInfo.isForwardLocked()) { 22334 currentAsec = true; 22335 currentVolumeUuid = "forward_locked"; 22336 } else { 22337 currentAsec = false; 22338 currentVolumeUuid = ps.volumeUuid; 22339 22340 final File probe = new File(pkg.codePath); 22341 final File probeOat = new File(probe, "oat"); 22342 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22343 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22344 "Move only supported for modern cluster style installs"); 22345 } 22346 } 22347 22348 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22349 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22350 "Package already moved to " + volumeUuid); 22351 } 22352 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22353 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22354 "Device admin cannot be moved"); 22355 } 22356 22357 if (mFrozenPackages.contains(packageName)) { 22358 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22359 "Failed to move already frozen package"); 22360 } 22361 22362 codeFile = new File(pkg.codePath); 22363 installerPackageName = ps.installerPackageName; 22364 packageAbiOverride = ps.cpuAbiOverrideString; 22365 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22366 seinfo = pkg.applicationInfo.seInfo; 22367 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22368 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22369 freezer = freezePackage(packageName, "movePackageInternal"); 22370 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22371 } 22372 22373 final Bundle extras = new Bundle(); 22374 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22375 extras.putString(Intent.EXTRA_TITLE, label); 22376 mMoveCallbacks.notifyCreated(moveId, extras); 22377 22378 int installFlags; 22379 final boolean moveCompleteApp; 22380 final File measurePath; 22381 22382 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22383 installFlags = INSTALL_INTERNAL; 22384 moveCompleteApp = !currentAsec; 22385 measurePath = Environment.getDataAppDirectory(volumeUuid); 22386 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22387 installFlags = INSTALL_EXTERNAL; 22388 moveCompleteApp = false; 22389 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22390 } else { 22391 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22392 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22393 || !volume.isMountedWritable()) { 22394 freezer.close(); 22395 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22396 "Move location not mounted private volume"); 22397 } 22398 22399 Preconditions.checkState(!currentAsec); 22400 22401 installFlags = INSTALL_INTERNAL; 22402 moveCompleteApp = true; 22403 measurePath = Environment.getDataAppDirectory(volumeUuid); 22404 } 22405 22406 final PackageStats stats = new PackageStats(null, -1); 22407 synchronized (mInstaller) { 22408 for (int userId : installedUserIds) { 22409 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22410 freezer.close(); 22411 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22412 "Failed to measure package size"); 22413 } 22414 } 22415 } 22416 22417 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22418 + stats.dataSize); 22419 22420 final long startFreeBytes = measurePath.getUsableSpace(); 22421 final long sizeBytes; 22422 if (moveCompleteApp) { 22423 sizeBytes = stats.codeSize + stats.dataSize; 22424 } else { 22425 sizeBytes = stats.codeSize; 22426 } 22427 22428 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22429 freezer.close(); 22430 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22431 "Not enough free space to move"); 22432 } 22433 22434 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22435 22436 final CountDownLatch installedLatch = new CountDownLatch(1); 22437 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22438 @Override 22439 public void onUserActionRequired(Intent intent) throws RemoteException { 22440 throw new IllegalStateException(); 22441 } 22442 22443 @Override 22444 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22445 Bundle extras) throws RemoteException { 22446 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22447 + PackageManager.installStatusToString(returnCode, msg)); 22448 22449 installedLatch.countDown(); 22450 freezer.close(); 22451 22452 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22453 switch (status) { 22454 case PackageInstaller.STATUS_SUCCESS: 22455 mMoveCallbacks.notifyStatusChanged(moveId, 22456 PackageManager.MOVE_SUCCEEDED); 22457 break; 22458 case PackageInstaller.STATUS_FAILURE_STORAGE: 22459 mMoveCallbacks.notifyStatusChanged(moveId, 22460 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22461 break; 22462 default: 22463 mMoveCallbacks.notifyStatusChanged(moveId, 22464 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22465 break; 22466 } 22467 } 22468 }; 22469 22470 final MoveInfo move; 22471 if (moveCompleteApp) { 22472 // Kick off a thread to report progress estimates 22473 new Thread() { 22474 @Override 22475 public void run() { 22476 while (true) { 22477 try { 22478 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22479 break; 22480 } 22481 } catch (InterruptedException ignored) { 22482 } 22483 22484 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22485 final int progress = 10 + (int) MathUtils.constrain( 22486 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22487 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22488 } 22489 } 22490 }.start(); 22491 22492 final String dataAppName = codeFile.getName(); 22493 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22494 dataAppName, appId, seinfo, targetSdkVersion); 22495 } else { 22496 move = null; 22497 } 22498 22499 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22500 22501 final Message msg = mHandler.obtainMessage(INIT_COPY); 22502 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22503 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22504 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22505 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22506 PackageManager.INSTALL_REASON_UNKNOWN); 22507 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22508 msg.obj = params; 22509 22510 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22511 System.identityHashCode(msg.obj)); 22512 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22513 System.identityHashCode(msg.obj)); 22514 22515 mHandler.sendMessage(msg); 22516 } 22517 22518 @Override 22519 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22520 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22521 22522 final int realMoveId = mNextMoveId.getAndIncrement(); 22523 final Bundle extras = new Bundle(); 22524 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22525 mMoveCallbacks.notifyCreated(realMoveId, extras); 22526 22527 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22528 @Override 22529 public void onCreated(int moveId, Bundle extras) { 22530 // Ignored 22531 } 22532 22533 @Override 22534 public void onStatusChanged(int moveId, int status, long estMillis) { 22535 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22536 } 22537 }; 22538 22539 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22540 storage.setPrimaryStorageUuid(volumeUuid, callback); 22541 return realMoveId; 22542 } 22543 22544 @Override 22545 public int getMoveStatus(int moveId) { 22546 mContext.enforceCallingOrSelfPermission( 22547 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22548 return mMoveCallbacks.mLastStatus.get(moveId); 22549 } 22550 22551 @Override 22552 public void registerMoveCallback(IPackageMoveObserver callback) { 22553 mContext.enforceCallingOrSelfPermission( 22554 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22555 mMoveCallbacks.register(callback); 22556 } 22557 22558 @Override 22559 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22560 mContext.enforceCallingOrSelfPermission( 22561 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22562 mMoveCallbacks.unregister(callback); 22563 } 22564 22565 @Override 22566 public boolean setInstallLocation(int loc) { 22567 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22568 null); 22569 if (getInstallLocation() == loc) { 22570 return true; 22571 } 22572 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22573 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22574 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22575 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22576 return true; 22577 } 22578 return false; 22579 } 22580 22581 @Override 22582 public int getInstallLocation() { 22583 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22584 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22585 PackageHelper.APP_INSTALL_AUTO); 22586 } 22587 22588 /** Called by UserManagerService */ 22589 void cleanUpUser(UserManagerService userManager, int userHandle) { 22590 synchronized (mPackages) { 22591 mDirtyUsers.remove(userHandle); 22592 mUserNeedsBadging.delete(userHandle); 22593 mSettings.removeUserLPw(userHandle); 22594 mPendingBroadcasts.remove(userHandle); 22595 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22596 removeUnusedPackagesLPw(userManager, userHandle); 22597 } 22598 } 22599 22600 /** 22601 * We're removing userHandle and would like to remove any downloaded packages 22602 * that are no longer in use by any other user. 22603 * @param userHandle the user being removed 22604 */ 22605 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22606 final boolean DEBUG_CLEAN_APKS = false; 22607 int [] users = userManager.getUserIds(); 22608 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22609 while (psit.hasNext()) { 22610 PackageSetting ps = psit.next(); 22611 if (ps.pkg == null) { 22612 continue; 22613 } 22614 final String packageName = ps.pkg.packageName; 22615 // Skip over if system app 22616 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22617 continue; 22618 } 22619 if (DEBUG_CLEAN_APKS) { 22620 Slog.i(TAG, "Checking package " + packageName); 22621 } 22622 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22623 if (keep) { 22624 if (DEBUG_CLEAN_APKS) { 22625 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22626 } 22627 } else { 22628 for (int i = 0; i < users.length; i++) { 22629 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22630 keep = true; 22631 if (DEBUG_CLEAN_APKS) { 22632 Slog.i(TAG, " Keeping package " + packageName + " for user " 22633 + users[i]); 22634 } 22635 break; 22636 } 22637 } 22638 } 22639 if (!keep) { 22640 if (DEBUG_CLEAN_APKS) { 22641 Slog.i(TAG, " Removing package " + packageName); 22642 } 22643 mHandler.post(new Runnable() { 22644 public void run() { 22645 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22646 userHandle, 0); 22647 } //end run 22648 }); 22649 } 22650 } 22651 } 22652 22653 /** Called by UserManagerService */ 22654 void createNewUser(int userId, String[] disallowedPackages) { 22655 synchronized (mInstallLock) { 22656 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22657 } 22658 synchronized (mPackages) { 22659 scheduleWritePackageRestrictionsLocked(userId); 22660 scheduleWritePackageListLocked(userId); 22661 applyFactoryDefaultBrowserLPw(userId); 22662 primeDomainVerificationsLPw(userId); 22663 } 22664 } 22665 22666 void onNewUserCreated(final int userId) { 22667 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22668 // If permission review for legacy apps is required, we represent 22669 // dagerous permissions for such apps as always granted runtime 22670 // permissions to keep per user flag state whether review is needed. 22671 // Hence, if a new user is added we have to propagate dangerous 22672 // permission grants for these legacy apps. 22673 if (mPermissionReviewRequired) { 22674 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22675 | UPDATE_PERMISSIONS_REPLACE_ALL); 22676 } 22677 } 22678 22679 @Override 22680 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22681 mContext.enforceCallingOrSelfPermission( 22682 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22683 "Only package verification agents can read the verifier device identity"); 22684 22685 synchronized (mPackages) { 22686 return mSettings.getVerifierDeviceIdentityLPw(); 22687 } 22688 } 22689 22690 @Override 22691 public void setPermissionEnforced(String permission, boolean enforced) { 22692 // TODO: Now that we no longer change GID for storage, this should to away. 22693 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22694 "setPermissionEnforced"); 22695 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22696 synchronized (mPackages) { 22697 if (mSettings.mReadExternalStorageEnforced == null 22698 || mSettings.mReadExternalStorageEnforced != enforced) { 22699 mSettings.mReadExternalStorageEnforced = enforced; 22700 mSettings.writeLPr(); 22701 } 22702 } 22703 // kill any non-foreground processes so we restart them and 22704 // grant/revoke the GID. 22705 final IActivityManager am = ActivityManager.getService(); 22706 if (am != null) { 22707 final long token = Binder.clearCallingIdentity(); 22708 try { 22709 am.killProcessesBelowForeground("setPermissionEnforcement"); 22710 } catch (RemoteException e) { 22711 } finally { 22712 Binder.restoreCallingIdentity(token); 22713 } 22714 } 22715 } else { 22716 throw new IllegalArgumentException("No selective enforcement for " + permission); 22717 } 22718 } 22719 22720 @Override 22721 @Deprecated 22722 public boolean isPermissionEnforced(String permission) { 22723 return true; 22724 } 22725 22726 @Override 22727 public boolean isStorageLow() { 22728 final long token = Binder.clearCallingIdentity(); 22729 try { 22730 final DeviceStorageMonitorInternal 22731 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22732 if (dsm != null) { 22733 return dsm.isMemoryLow(); 22734 } else { 22735 return false; 22736 } 22737 } finally { 22738 Binder.restoreCallingIdentity(token); 22739 } 22740 } 22741 22742 @Override 22743 public IPackageInstaller getPackageInstaller() { 22744 return mInstallerService; 22745 } 22746 22747 private boolean userNeedsBadging(int userId) { 22748 int index = mUserNeedsBadging.indexOfKey(userId); 22749 if (index < 0) { 22750 final UserInfo userInfo; 22751 final long token = Binder.clearCallingIdentity(); 22752 try { 22753 userInfo = sUserManager.getUserInfo(userId); 22754 } finally { 22755 Binder.restoreCallingIdentity(token); 22756 } 22757 final boolean b; 22758 if (userInfo != null && userInfo.isManagedProfile()) { 22759 b = true; 22760 } else { 22761 b = false; 22762 } 22763 mUserNeedsBadging.put(userId, b); 22764 return b; 22765 } 22766 return mUserNeedsBadging.valueAt(index); 22767 } 22768 22769 @Override 22770 public KeySet getKeySetByAlias(String packageName, String alias) { 22771 if (packageName == null || alias == null) { 22772 return null; 22773 } 22774 synchronized(mPackages) { 22775 final PackageParser.Package pkg = mPackages.get(packageName); 22776 if (pkg == null) { 22777 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22778 throw new IllegalArgumentException("Unknown package: " + packageName); 22779 } 22780 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22781 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22782 } 22783 } 22784 22785 @Override 22786 public KeySet getSigningKeySet(String packageName) { 22787 if (packageName == null) { 22788 return null; 22789 } 22790 synchronized(mPackages) { 22791 final PackageParser.Package pkg = mPackages.get(packageName); 22792 if (pkg == null) { 22793 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22794 throw new IllegalArgumentException("Unknown package: " + packageName); 22795 } 22796 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22797 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22798 throw new SecurityException("May not access signing KeySet of other apps."); 22799 } 22800 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22801 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22802 } 22803 } 22804 22805 @Override 22806 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22807 if (packageName == null || ks == null) { 22808 return false; 22809 } 22810 synchronized(mPackages) { 22811 final PackageParser.Package pkg = mPackages.get(packageName); 22812 if (pkg == null) { 22813 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22814 throw new IllegalArgumentException("Unknown package: " + packageName); 22815 } 22816 IBinder ksh = ks.getToken(); 22817 if (ksh instanceof KeySetHandle) { 22818 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22819 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22820 } 22821 return false; 22822 } 22823 } 22824 22825 @Override 22826 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22827 if (packageName == null || ks == null) { 22828 return false; 22829 } 22830 synchronized(mPackages) { 22831 final PackageParser.Package pkg = mPackages.get(packageName); 22832 if (pkg == null) { 22833 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22834 throw new IllegalArgumentException("Unknown package: " + packageName); 22835 } 22836 IBinder ksh = ks.getToken(); 22837 if (ksh instanceof KeySetHandle) { 22838 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22839 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22840 } 22841 return false; 22842 } 22843 } 22844 22845 private void deletePackageIfUnusedLPr(final String packageName) { 22846 PackageSetting ps = mSettings.mPackages.get(packageName); 22847 if (ps == null) { 22848 return; 22849 } 22850 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22851 // TODO Implement atomic delete if package is unused 22852 // It is currently possible that the package will be deleted even if it is installed 22853 // after this method returns. 22854 mHandler.post(new Runnable() { 22855 public void run() { 22856 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22857 0, PackageManager.DELETE_ALL_USERS); 22858 } 22859 }); 22860 } 22861 } 22862 22863 /** 22864 * Check and throw if the given before/after packages would be considered a 22865 * downgrade. 22866 */ 22867 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22868 throws PackageManagerException { 22869 if (after.versionCode < before.mVersionCode) { 22870 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22871 "Update version code " + after.versionCode + " is older than current " 22872 + before.mVersionCode); 22873 } else if (after.versionCode == before.mVersionCode) { 22874 if (after.baseRevisionCode < before.baseRevisionCode) { 22875 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22876 "Update base revision code " + after.baseRevisionCode 22877 + " is older than current " + before.baseRevisionCode); 22878 } 22879 22880 if (!ArrayUtils.isEmpty(after.splitNames)) { 22881 for (int i = 0; i < after.splitNames.length; i++) { 22882 final String splitName = after.splitNames[i]; 22883 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22884 if (j != -1) { 22885 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22886 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22887 "Update split " + splitName + " revision code " 22888 + after.splitRevisionCodes[i] + " is older than current " 22889 + before.splitRevisionCodes[j]); 22890 } 22891 } 22892 } 22893 } 22894 } 22895 } 22896 22897 private static class MoveCallbacks extends Handler { 22898 private static final int MSG_CREATED = 1; 22899 private static final int MSG_STATUS_CHANGED = 2; 22900 22901 private final RemoteCallbackList<IPackageMoveObserver> 22902 mCallbacks = new RemoteCallbackList<>(); 22903 22904 private final SparseIntArray mLastStatus = new SparseIntArray(); 22905 22906 public MoveCallbacks(Looper looper) { 22907 super(looper); 22908 } 22909 22910 public void register(IPackageMoveObserver callback) { 22911 mCallbacks.register(callback); 22912 } 22913 22914 public void unregister(IPackageMoveObserver callback) { 22915 mCallbacks.unregister(callback); 22916 } 22917 22918 @Override 22919 public void handleMessage(Message msg) { 22920 final SomeArgs args = (SomeArgs) msg.obj; 22921 final int n = mCallbacks.beginBroadcast(); 22922 for (int i = 0; i < n; i++) { 22923 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22924 try { 22925 invokeCallback(callback, msg.what, args); 22926 } catch (RemoteException ignored) { 22927 } 22928 } 22929 mCallbacks.finishBroadcast(); 22930 args.recycle(); 22931 } 22932 22933 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22934 throws RemoteException { 22935 switch (what) { 22936 case MSG_CREATED: { 22937 callback.onCreated(args.argi1, (Bundle) args.arg2); 22938 break; 22939 } 22940 case MSG_STATUS_CHANGED: { 22941 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22942 break; 22943 } 22944 } 22945 } 22946 22947 private void notifyCreated(int moveId, Bundle extras) { 22948 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22949 22950 final SomeArgs args = SomeArgs.obtain(); 22951 args.argi1 = moveId; 22952 args.arg2 = extras; 22953 obtainMessage(MSG_CREATED, args).sendToTarget(); 22954 } 22955 22956 private void notifyStatusChanged(int moveId, int status) { 22957 notifyStatusChanged(moveId, status, -1); 22958 } 22959 22960 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22961 Slog.v(TAG, "Move " + moveId + " status " + status); 22962 22963 final SomeArgs args = SomeArgs.obtain(); 22964 args.argi1 = moveId; 22965 args.argi2 = status; 22966 args.arg3 = estMillis; 22967 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22968 22969 synchronized (mLastStatus) { 22970 mLastStatus.put(moveId, status); 22971 } 22972 } 22973 } 22974 22975 private final static class OnPermissionChangeListeners extends Handler { 22976 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22977 22978 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22979 new RemoteCallbackList<>(); 22980 22981 public OnPermissionChangeListeners(Looper looper) { 22982 super(looper); 22983 } 22984 22985 @Override 22986 public void handleMessage(Message msg) { 22987 switch (msg.what) { 22988 case MSG_ON_PERMISSIONS_CHANGED: { 22989 final int uid = msg.arg1; 22990 handleOnPermissionsChanged(uid); 22991 } break; 22992 } 22993 } 22994 22995 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22996 mPermissionListeners.register(listener); 22997 22998 } 22999 23000 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23001 mPermissionListeners.unregister(listener); 23002 } 23003 23004 public void onPermissionsChanged(int uid) { 23005 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23006 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23007 } 23008 } 23009 23010 private void handleOnPermissionsChanged(int uid) { 23011 final int count = mPermissionListeners.beginBroadcast(); 23012 try { 23013 for (int i = 0; i < count; i++) { 23014 IOnPermissionsChangeListener callback = mPermissionListeners 23015 .getBroadcastItem(i); 23016 try { 23017 callback.onPermissionsChanged(uid); 23018 } catch (RemoteException e) { 23019 Log.e(TAG, "Permission listener is dead", e); 23020 } 23021 } 23022 } finally { 23023 mPermissionListeners.finishBroadcast(); 23024 } 23025 } 23026 } 23027 23028 private class PackageManagerInternalImpl extends PackageManagerInternal { 23029 @Override 23030 public void setLocationPackagesProvider(PackagesProvider provider) { 23031 synchronized (mPackages) { 23032 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 23033 } 23034 } 23035 23036 @Override 23037 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23038 synchronized (mPackages) { 23039 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 23040 } 23041 } 23042 23043 @Override 23044 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23045 synchronized (mPackages) { 23046 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 23047 } 23048 } 23049 23050 @Override 23051 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23052 synchronized (mPackages) { 23053 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 23054 } 23055 } 23056 23057 @Override 23058 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23059 synchronized (mPackages) { 23060 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 23061 } 23062 } 23063 23064 @Override 23065 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23066 synchronized (mPackages) { 23067 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 23068 } 23069 } 23070 23071 @Override 23072 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23073 synchronized (mPackages) { 23074 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23075 packageName, userId); 23076 } 23077 } 23078 23079 @Override 23080 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23081 synchronized (mPackages) { 23082 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23083 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23084 packageName, userId); 23085 } 23086 } 23087 23088 @Override 23089 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23090 synchronized (mPackages) { 23091 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23092 packageName, userId); 23093 } 23094 } 23095 23096 @Override 23097 public void setKeepUninstalledPackages(final List<String> packageList) { 23098 Preconditions.checkNotNull(packageList); 23099 List<String> removedFromList = null; 23100 synchronized (mPackages) { 23101 if (mKeepUninstalledPackages != null) { 23102 final int packagesCount = mKeepUninstalledPackages.size(); 23103 for (int i = 0; i < packagesCount; i++) { 23104 String oldPackage = mKeepUninstalledPackages.get(i); 23105 if (packageList != null && packageList.contains(oldPackage)) { 23106 continue; 23107 } 23108 if (removedFromList == null) { 23109 removedFromList = new ArrayList<>(); 23110 } 23111 removedFromList.add(oldPackage); 23112 } 23113 } 23114 mKeepUninstalledPackages = new ArrayList<>(packageList); 23115 if (removedFromList != null) { 23116 final int removedCount = removedFromList.size(); 23117 for (int i = 0; i < removedCount; i++) { 23118 deletePackageIfUnusedLPr(removedFromList.get(i)); 23119 } 23120 } 23121 } 23122 } 23123 23124 @Override 23125 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23126 synchronized (mPackages) { 23127 // If we do not support permission review, done. 23128 if (!mPermissionReviewRequired) { 23129 return false; 23130 } 23131 23132 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23133 if (packageSetting == null) { 23134 return false; 23135 } 23136 23137 // Permission review applies only to apps not supporting the new permission model. 23138 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23139 return false; 23140 } 23141 23142 // Legacy apps have the permission and get user consent on launch. 23143 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23144 return permissionsState.isPermissionReviewRequired(userId); 23145 } 23146 } 23147 23148 @Override 23149 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23150 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23151 } 23152 23153 @Override 23154 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23155 int userId) { 23156 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23157 } 23158 23159 @Override 23160 public void setDeviceAndProfileOwnerPackages( 23161 int deviceOwnerUserId, String deviceOwnerPackage, 23162 SparseArray<String> profileOwnerPackages) { 23163 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23164 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23165 } 23166 23167 @Override 23168 public boolean isPackageDataProtected(int userId, String packageName) { 23169 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23170 } 23171 23172 @Override 23173 public boolean isPackageEphemeral(int userId, String packageName) { 23174 synchronized (mPackages) { 23175 final PackageSetting ps = mSettings.mPackages.get(packageName); 23176 return ps != null ? ps.getInstantApp(userId) : false; 23177 } 23178 } 23179 23180 @Override 23181 public boolean wasPackageEverLaunched(String packageName, int userId) { 23182 synchronized (mPackages) { 23183 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23184 } 23185 } 23186 23187 @Override 23188 public void grantRuntimePermission(String packageName, String name, int userId, 23189 boolean overridePolicy) { 23190 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23191 overridePolicy); 23192 } 23193 23194 @Override 23195 public void revokeRuntimePermission(String packageName, String name, int userId, 23196 boolean overridePolicy) { 23197 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23198 overridePolicy); 23199 } 23200 23201 @Override 23202 public String getNameForUid(int uid) { 23203 return PackageManagerService.this.getNameForUid(uid); 23204 } 23205 23206 @Override 23207 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23208 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23209 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23210 responseObj, origIntent, resolvedType, callingPackage, userId); 23211 } 23212 23213 @Override 23214 public void grantEphemeralAccess(int userId, Intent intent, 23215 int targetAppId, int ephemeralAppId) { 23216 synchronized (mPackages) { 23217 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23218 targetAppId, ephemeralAppId); 23219 } 23220 } 23221 23222 @Override 23223 public boolean isInstantAppInstallerComponent(ComponentName component) { 23224 synchronized (mPackages) { 23225 return mInstantAppInstallerActivity != null 23226 && mInstantAppInstallerActivity.getComponentName().equals(component); 23227 } 23228 } 23229 23230 @Override 23231 public void pruneInstantApps() { 23232 synchronized (mPackages) { 23233 mInstantAppRegistry.pruneInstantAppsLPw(); 23234 } 23235 } 23236 23237 @Override 23238 public String getSetupWizardPackageName() { 23239 return mSetupWizardPackage; 23240 } 23241 23242 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23243 if (policy != null) { 23244 mExternalSourcesPolicy = policy; 23245 } 23246 } 23247 23248 @Override 23249 public boolean isPackagePersistent(String packageName) { 23250 synchronized (mPackages) { 23251 PackageParser.Package pkg = mPackages.get(packageName); 23252 return pkg != null 23253 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23254 | ApplicationInfo.FLAG_PERSISTENT)) == 23255 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23256 : false; 23257 } 23258 } 23259 23260 @Override 23261 public List<PackageInfo> getOverlayPackages(int userId) { 23262 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23263 synchronized (mPackages) { 23264 for (PackageParser.Package p : mPackages.values()) { 23265 if (p.mOverlayTarget != null) { 23266 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23267 if (pkg != null) { 23268 overlayPackages.add(pkg); 23269 } 23270 } 23271 } 23272 } 23273 return overlayPackages; 23274 } 23275 23276 @Override 23277 public List<String> getTargetPackageNames(int userId) { 23278 List<String> targetPackages = new ArrayList<>(); 23279 synchronized (mPackages) { 23280 for (PackageParser.Package p : mPackages.values()) { 23281 if (p.mOverlayTarget == null) { 23282 targetPackages.add(p.packageName); 23283 } 23284 } 23285 } 23286 return targetPackages; 23287 } 23288 23289 @Override 23290 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23291 @Nullable List<String> overlayPackageNames) { 23292 synchronized (mPackages) { 23293 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23294 Slog.e(TAG, "failed to find package " + targetPackageName); 23295 return false; 23296 } 23297 23298 ArrayList<String> paths = null; 23299 if (overlayPackageNames != null) { 23300 final int N = overlayPackageNames.size(); 23301 paths = new ArrayList<>(N); 23302 for (int i = 0; i < N; i++) { 23303 final String packageName = overlayPackageNames.get(i); 23304 final PackageParser.Package pkg = mPackages.get(packageName); 23305 if (pkg == null) { 23306 Slog.e(TAG, "failed to find package " + packageName); 23307 return false; 23308 } 23309 paths.add(pkg.baseCodePath); 23310 } 23311 } 23312 23313 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23314 mEnabledOverlayPaths.get(userId); 23315 if (userSpecificOverlays == null) { 23316 userSpecificOverlays = new ArrayMap<>(); 23317 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23318 } 23319 23320 if (paths != null && paths.size() > 0) { 23321 userSpecificOverlays.put(targetPackageName, paths); 23322 } else { 23323 userSpecificOverlays.remove(targetPackageName); 23324 } 23325 return true; 23326 } 23327 } 23328 23329 @Override 23330 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23331 int flags, int userId) { 23332 return resolveIntentInternal( 23333 intent, resolvedType, flags, userId, true /*includeInstantApps*/); 23334 } 23335 23336 @Override 23337 public ResolveInfo resolveService(Intent intent, String resolvedType, 23338 int flags, int userId, int callingUid) { 23339 return resolveServiceInternal( 23340 intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/); 23341 } 23342 23343 23344 @Override 23345 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23346 synchronized (mPackages) { 23347 mIsolatedOwners.put(isolatedUid, ownerUid); 23348 } 23349 } 23350 23351 @Override 23352 public void removeIsolatedUid(int isolatedUid) { 23353 synchronized (mPackages) { 23354 mIsolatedOwners.delete(isolatedUid); 23355 } 23356 } 23357 } 23358 23359 @Override 23360 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23361 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23362 synchronized (mPackages) { 23363 final long identity = Binder.clearCallingIdentity(); 23364 try { 23365 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23366 packageNames, userId); 23367 } finally { 23368 Binder.restoreCallingIdentity(identity); 23369 } 23370 } 23371 } 23372 23373 @Override 23374 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23375 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23376 synchronized (mPackages) { 23377 final long identity = Binder.clearCallingIdentity(); 23378 try { 23379 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23380 packageNames, userId); 23381 } finally { 23382 Binder.restoreCallingIdentity(identity); 23383 } 23384 } 23385 } 23386 23387 private static void enforceSystemOrPhoneCaller(String tag) { 23388 int callingUid = Binder.getCallingUid(); 23389 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23390 throw new SecurityException( 23391 "Cannot call " + tag + " from UID " + callingUid); 23392 } 23393 } 23394 23395 boolean isHistoricalPackageUsageAvailable() { 23396 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23397 } 23398 23399 /** 23400 * Return a <b>copy</b> of the collection of packages known to the package manager. 23401 * @return A copy of the values of mPackages. 23402 */ 23403 Collection<PackageParser.Package> getPackages() { 23404 synchronized (mPackages) { 23405 return new ArrayList<>(mPackages.values()); 23406 } 23407 } 23408 23409 /** 23410 * Logs process start information (including base APK hash) to the security log. 23411 * @hide 23412 */ 23413 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23414 String apkFile, int pid) { 23415 if (!SecurityLog.isLoggingEnabled()) { 23416 return; 23417 } 23418 Bundle data = new Bundle(); 23419 data.putLong("startTimestamp", System.currentTimeMillis()); 23420 data.putString("processName", processName); 23421 data.putInt("uid", uid); 23422 data.putString("seinfo", seinfo); 23423 data.putString("apkFile", apkFile); 23424 data.putInt("pid", pid); 23425 Message msg = mProcessLoggingHandler.obtainMessage( 23426 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23427 msg.setData(data); 23428 mProcessLoggingHandler.sendMessage(msg); 23429 } 23430 23431 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23432 return mCompilerStats.getPackageStats(pkgName); 23433 } 23434 23435 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23436 return getOrCreateCompilerPackageStats(pkg.packageName); 23437 } 23438 23439 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23440 return mCompilerStats.getOrCreatePackageStats(pkgName); 23441 } 23442 23443 public void deleteCompilerPackageStats(String pkgName) { 23444 mCompilerStats.deletePackageStats(pkgName); 23445 } 23446 23447 @Override 23448 public int getInstallReason(String packageName, int userId) { 23449 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23450 true /* requireFullPermission */, false /* checkShell */, 23451 "get install reason"); 23452 synchronized (mPackages) { 23453 final PackageSetting ps = mSettings.mPackages.get(packageName); 23454 if (ps != null) { 23455 return ps.getInstallReason(userId); 23456 } 23457 } 23458 return PackageManager.INSTALL_REASON_UNKNOWN; 23459 } 23460 23461 @Override 23462 public boolean canRequestPackageInstalls(String packageName, int userId) { 23463 int callingUid = Binder.getCallingUid(); 23464 int uid = getPackageUid(packageName, 0, userId); 23465 if (callingUid != uid && callingUid != Process.ROOT_UID 23466 && callingUid != Process.SYSTEM_UID) { 23467 throw new SecurityException( 23468 "Caller uid " + callingUid + " does not own package " + packageName); 23469 } 23470 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23471 if (info == null) { 23472 return false; 23473 } 23474 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23475 throw new UnsupportedOperationException( 23476 "Operation only supported on apps targeting Android O or higher"); 23477 } 23478 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23479 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23480 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23481 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23482 } 23483 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23484 return false; 23485 } 23486 if (mExternalSourcesPolicy != null) { 23487 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23488 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23489 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23490 } 23491 } 23492 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23493 } 23494 23495 @Override 23496 public ComponentName getInstantAppResolverSettingsComponent() { 23497 return mInstantAppResolverSettingsComponent; 23498 } 23499} 23500