PackageManagerService.java revision b94103d25dc15adde4329383a2bf0281868c45c9
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.EphemeralRequest; 132import android.content.pm.EphemeralResolveInfo; 133import android.content.pm.AuxiliaryResolveInfo; 134import android.content.pm.FallbackCategoryProvider; 135import android.content.pm.FeatureInfo; 136import android.content.pm.IOnPermissionsChangeListener; 137import android.content.pm.IPackageDataObserver; 138import android.content.pm.IPackageDeleteObserver; 139import android.content.pm.IPackageDeleteObserver2; 140import android.content.pm.IPackageInstallObserver2; 141import android.content.pm.IPackageInstaller; 142import android.content.pm.IPackageManager; 143import android.content.pm.IPackageMoveObserver; 144import android.content.pm.IPackageStatsObserver; 145import android.content.pm.InstantAppInfo; 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.FastPrintWriter; 258import com.android.internal.util.FastXmlSerializer; 259import com.android.internal.util.IndentingPrintWriter; 260import com.android.internal.util.Preconditions; 261import com.android.internal.util.XmlUtils; 262import com.android.server.AttributeCache; 263import com.android.server.BackgroundDexOptJobService; 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.ServiceThread; 270import com.android.server.SystemConfig; 271import com.android.server.SystemServerInitThreadPool; 272import com.android.server.Watchdog; 273import com.android.server.net.NetworkPolicyManagerInternal; 274import com.android.server.pm.Installer.InstallerException; 275import com.android.server.pm.PermissionsState.PermissionState; 276import com.android.server.pm.Settings.DatabaseVersion; 277import com.android.server.pm.Settings.VersionInfo; 278import com.android.server.pm.dex.DexManager; 279import com.android.server.storage.DeviceStorageMonitorInternal; 280 281import dalvik.system.CloseGuard; 282import dalvik.system.DexFile; 283import dalvik.system.VMRuntime; 284 285import libcore.io.IoUtils; 286import libcore.util.EmptyArray; 287 288import org.xmlpull.v1.XmlPullParser; 289import org.xmlpull.v1.XmlPullParserException; 290import org.xmlpull.v1.XmlSerializer; 291 292import java.io.BufferedOutputStream; 293import java.io.BufferedReader; 294import java.io.ByteArrayInputStream; 295import java.io.ByteArrayOutputStream; 296import java.io.File; 297import java.io.FileDescriptor; 298import java.io.FileInputStream; 299import java.io.FileNotFoundException; 300import java.io.FileOutputStream; 301import java.io.FileReader; 302import java.io.FilenameFilter; 303import java.io.IOException; 304import java.io.PrintWriter; 305import java.nio.charset.StandardCharsets; 306import java.security.DigestInputStream; 307import java.security.MessageDigest; 308import java.security.NoSuchAlgorithmException; 309import java.security.PublicKey; 310import java.security.SecureRandom; 311import java.security.cert.Certificate; 312import java.security.cert.CertificateEncodingException; 313import java.security.cert.CertificateException; 314import java.text.SimpleDateFormat; 315import java.util.ArrayList; 316import java.util.Arrays; 317import java.util.Collection; 318import java.util.Collections; 319import java.util.Comparator; 320import java.util.Date; 321import java.util.HashMap; 322import java.util.HashSet; 323import java.util.Iterator; 324import java.util.List; 325import java.util.Map; 326import java.util.Objects; 327import java.util.Set; 328import java.util.concurrent.CountDownLatch; 329import java.util.concurrent.Future; 330import java.util.concurrent.TimeUnit; 331import java.util.concurrent.atomic.AtomicBoolean; 332import java.util.concurrent.atomic.AtomicInteger; 333 334/** 335 * Keep track of all those APKs everywhere. 336 * <p> 337 * Internally there are two important locks: 338 * <ul> 339 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 340 * and other related state. It is a fine-grained lock that should only be held 341 * momentarily, as it's one of the most contended locks in the system. 342 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 343 * operations typically involve heavy lifting of application data on disk. Since 344 * {@code installd} is single-threaded, and it's operations can often be slow, 345 * this lock should never be acquired while already holding {@link #mPackages}. 346 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 347 * holding {@link #mInstallLock}. 348 * </ul> 349 * Many internal methods rely on the caller to hold the appropriate locks, and 350 * this contract is expressed through method name suffixes: 351 * <ul> 352 * <li>fooLI(): the caller must hold {@link #mInstallLock} 353 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 354 * being modified must be frozen 355 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 356 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 357 * </ul> 358 * <p> 359 * Because this class is very central to the platform's security; please run all 360 * CTS and unit tests whenever making modifications: 361 * 362 * <pre> 363 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 364 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 365 * </pre> 366 */ 367public class PackageManagerService extends IPackageManager.Stub { 368 static final String TAG = "PackageManager"; 369 static final boolean DEBUG_SETTINGS = false; 370 static final boolean DEBUG_PREFERRED = false; 371 static final boolean DEBUG_UPGRADE = false; 372 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 373 private static final boolean DEBUG_BACKUP = false; 374 private static final boolean DEBUG_INSTALL = false; 375 private static final boolean DEBUG_REMOVE = false; 376 private static final boolean DEBUG_BROADCASTS = false; 377 private static final boolean DEBUG_SHOW_INFO = false; 378 private static final boolean DEBUG_PACKAGE_INFO = false; 379 private static final boolean DEBUG_INTENT_MATCHING = false; 380 private static final boolean DEBUG_PACKAGE_SCANNING = false; 381 private static final boolean DEBUG_VERIFY = false; 382 private static final boolean DEBUG_FILTERS = false; 383 384 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 385 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 386 // user, but by default initialize to this. 387 public static final boolean DEBUG_DEXOPT = false; 388 389 private static final boolean DEBUG_ABI_SELECTION = false; 390 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 391 private static final boolean DEBUG_TRIAGED_MISSING = false; 392 private static final boolean DEBUG_APP_DATA = false; 393 394 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 395 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 396 397 private static final boolean DISABLE_EPHEMERAL_APPS = false; 398 private static final boolean HIDE_EPHEMERAL_APIS = false; 399 400 private static final boolean ENABLE_FREE_CACHE_V2 = 401 SystemProperties.getBoolean("fw.free_cache_v2", false); 402 403 private static final int RADIO_UID = Process.PHONE_UID; 404 private static final int LOG_UID = Process.LOG_UID; 405 private static final int NFC_UID = Process.NFC_UID; 406 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 407 private static final int SHELL_UID = Process.SHELL_UID; 408 409 // Cap the size of permission trees that 3rd party apps can define 410 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 411 412 // Suffix used during package installation when copying/moving 413 // package apks to install directory. 414 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 415 416 static final int SCAN_NO_DEX = 1<<1; 417 static final int SCAN_FORCE_DEX = 1<<2; 418 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 419 static final int SCAN_NEW_INSTALL = 1<<4; 420 static final int SCAN_UPDATE_TIME = 1<<5; 421 static final int SCAN_BOOTING = 1<<6; 422 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 423 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 424 static final int SCAN_REPLACING = 1<<9; 425 static final int SCAN_REQUIRE_KNOWN = 1<<10; 426 static final int SCAN_MOVE = 1<<11; 427 static final int SCAN_INITIAL = 1<<12; 428 static final int SCAN_CHECK_ONLY = 1<<13; 429 static final int SCAN_DONT_KILL_APP = 1<<14; 430 static final int SCAN_IGNORE_FROZEN = 1<<15; 431 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 432 static final int SCAN_AS_INSTANT_APP = 1<<17; 433 static final int SCAN_AS_FULL_APP = 1<<18; 434 /** Should not be with the scan flags */ 435 static final int FLAGS_REMOVE_CHATTY = 1<<31; 436 437 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 438 439 private static final int[] EMPTY_INT_ARRAY = new int[0]; 440 441 /** 442 * Timeout (in milliseconds) after which the watchdog should declare that 443 * our handler thread is wedged. The usual default for such things is one 444 * minute but we sometimes do very lengthy I/O operations on this thread, 445 * such as installing multi-gigabyte applications, so ours needs to be longer. 446 */ 447 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 448 449 /** 450 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 451 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 452 * settings entry if available, otherwise we use the hardcoded default. If it's been 453 * more than this long since the last fstrim, we force one during the boot sequence. 454 * 455 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 456 * one gets run at the next available charging+idle time. This final mandatory 457 * no-fstrim check kicks in only of the other scheduling criteria is never met. 458 */ 459 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 460 461 /** 462 * Whether verification is enabled by default. 463 */ 464 private static final boolean DEFAULT_VERIFY_ENABLE = true; 465 466 /** 467 * The default maximum time to wait for the verification agent to return in 468 * milliseconds. 469 */ 470 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 471 472 /** 473 * The default response for package verification timeout. 474 * 475 * This can be either PackageManager.VERIFICATION_ALLOW or 476 * PackageManager.VERIFICATION_REJECT. 477 */ 478 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 479 480 static final String PLATFORM_PACKAGE_NAME = "android"; 481 482 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 483 484 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 485 DEFAULT_CONTAINER_PACKAGE, 486 "com.android.defcontainer.DefaultContainerService"); 487 488 private static final String KILL_APP_REASON_GIDS_CHANGED = 489 "permission grant or revoke changed gids"; 490 491 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 492 "permissions revoked"; 493 494 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 495 496 private static final String PACKAGE_SCHEME = "package"; 497 498 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 499 500 /** Permission grant: not grant the permission. */ 501 private static final int GRANT_DENIED = 1; 502 503 /** Permission grant: grant the permission as an install permission. */ 504 private static final int GRANT_INSTALL = 2; 505 506 /** Permission grant: grant the permission as a runtime one. */ 507 private static final int GRANT_RUNTIME = 3; 508 509 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 510 private static final int GRANT_UPGRADE = 4; 511 512 /** Canonical intent used to identify what counts as a "web browser" app */ 513 private static final Intent sBrowserIntent; 514 static { 515 sBrowserIntent = new Intent(); 516 sBrowserIntent.setAction(Intent.ACTION_VIEW); 517 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 518 sBrowserIntent.setData(Uri.parse("http:")); 519 } 520 521 /** 522 * The set of all protected actions [i.e. those actions for which a high priority 523 * intent filter is disallowed]. 524 */ 525 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 526 static { 527 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 528 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 530 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 531 } 532 533 // Compilation reasons. 534 public static final int REASON_FIRST_BOOT = 0; 535 public static final int REASON_BOOT = 1; 536 public static final int REASON_INSTALL = 2; 537 public static final int REASON_BACKGROUND_DEXOPT = 3; 538 public static final int REASON_AB_OTA = 4; 539 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 540 public static final int REASON_SHARED_APK = 6; 541 public static final int REASON_FORCED_DEXOPT = 7; 542 public static final int REASON_CORE_APP = 8; 543 544 public static final int REASON_LAST = REASON_CORE_APP; 545 546 /** All dangerous permission names in the same order as the events in MetricsEvent */ 547 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 548 Manifest.permission.READ_CALENDAR, 549 Manifest.permission.WRITE_CALENDAR, 550 Manifest.permission.CAMERA, 551 Manifest.permission.READ_CONTACTS, 552 Manifest.permission.WRITE_CONTACTS, 553 Manifest.permission.GET_ACCOUNTS, 554 Manifest.permission.ACCESS_FINE_LOCATION, 555 Manifest.permission.ACCESS_COARSE_LOCATION, 556 Manifest.permission.RECORD_AUDIO, 557 Manifest.permission.READ_PHONE_STATE, 558 Manifest.permission.CALL_PHONE, 559 Manifest.permission.READ_CALL_LOG, 560 Manifest.permission.WRITE_CALL_LOG, 561 Manifest.permission.ADD_VOICEMAIL, 562 Manifest.permission.USE_SIP, 563 Manifest.permission.PROCESS_OUTGOING_CALLS, 564 Manifest.permission.READ_CELL_BROADCASTS, 565 Manifest.permission.BODY_SENSORS, 566 Manifest.permission.SEND_SMS, 567 Manifest.permission.RECEIVE_SMS, 568 Manifest.permission.READ_SMS, 569 Manifest.permission.RECEIVE_WAP_PUSH, 570 Manifest.permission.RECEIVE_MMS, 571 Manifest.permission.READ_EXTERNAL_STORAGE, 572 Manifest.permission.WRITE_EXTERNAL_STORAGE, 573 Manifest.permission.READ_PHONE_NUMBER, 574 Manifest.permission.ANSWER_PHONE_CALLS); 575 576 577 /** 578 * Version number for the package parser cache. Increment this whenever the format or 579 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 580 */ 581 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 582 583 /** 584 * Whether the package parser cache is enabled. 585 */ 586 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 587 588 final ServiceThread mHandlerThread; 589 590 final PackageHandler mHandler; 591 592 private final ProcessLoggingHandler mProcessLoggingHandler; 593 594 /** 595 * Messages for {@link #mHandler} that need to wait for system ready before 596 * being dispatched. 597 */ 598 private ArrayList<Message> mPostSystemReadyMessages; 599 600 final int mSdkVersion = Build.VERSION.SDK_INT; 601 602 final Context mContext; 603 final boolean mFactoryTest; 604 final boolean mOnlyCore; 605 final DisplayMetrics mMetrics; 606 final int mDefParseFlags; 607 final String[] mSeparateProcesses; 608 final boolean mIsUpgrade; 609 final boolean mIsPreNUpgrade; 610 final boolean mIsPreNMR1Upgrade; 611 612 @GuardedBy("mPackages") 613 private boolean mDexOptDialogShown; 614 615 /** The location for ASEC container files on internal storage. */ 616 final String mAsecInternalPath; 617 618 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 619 // LOCK HELD. Can be called with mInstallLock held. 620 @GuardedBy("mInstallLock") 621 final Installer mInstaller; 622 623 /** Directory where installed third-party apps stored */ 624 final File mAppInstallDir; 625 626 /** 627 * Directory to which applications installed internally have their 628 * 32 bit native libraries copied. 629 */ 630 private File mAppLib32InstallDir; 631 632 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 633 // apps. 634 final File mDrmAppPrivateInstallDir; 635 636 // ---------------------------------------------------------------- 637 638 // Lock for state used when installing and doing other long running 639 // operations. Methods that must be called with this lock held have 640 // the suffix "LI". 641 final Object mInstallLock = new Object(); 642 643 // ---------------------------------------------------------------- 644 645 // Keys are String (package name), values are Package. This also serves 646 // as the lock for the global state. Methods that must be called with 647 // this lock held have the prefix "LP". 648 @GuardedBy("mPackages") 649 final ArrayMap<String, PackageParser.Package> mPackages = 650 new ArrayMap<String, PackageParser.Package>(); 651 652 final ArrayMap<String, Set<String>> mKnownCodebase = 653 new ArrayMap<String, Set<String>>(); 654 655 // List of APK paths to load for each user and package. This data is never 656 // persisted by the package manager. Instead, the overlay manager will 657 // ensure the data is up-to-date in runtime. 658 @GuardedBy("mPackages") 659 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 660 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 661 662 /** 663 * Tracks new system packages [received in an OTA] that we expect to 664 * find updated user-installed versions. Keys are package name, values 665 * are package location. 666 */ 667 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 668 /** 669 * Tracks high priority intent filters for protected actions. During boot, certain 670 * filter actions are protected and should never be allowed to have a high priority 671 * intent filter for them. However, there is one, and only one exception -- the 672 * setup wizard. It must be able to define a high priority intent filter for these 673 * actions to ensure there are no escapes from the wizard. We need to delay processing 674 * of these during boot as we need to look at all of the system packages in order 675 * to know which component is the setup wizard. 676 */ 677 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 678 /** 679 * Whether or not processing protected filters should be deferred. 680 */ 681 private boolean mDeferProtectedFilters = true; 682 683 /** 684 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 685 */ 686 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 687 /** 688 * Whether or not system app permissions should be promoted from install to runtime. 689 */ 690 boolean mPromoteSystemApps; 691 692 @GuardedBy("mPackages") 693 final Settings mSettings; 694 695 /** 696 * Set of package names that are currently "frozen", which means active 697 * surgery is being done on the code/data for that package. The platform 698 * will refuse to launch frozen packages to avoid race conditions. 699 * 700 * @see PackageFreezer 701 */ 702 @GuardedBy("mPackages") 703 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 704 705 final ProtectedPackages mProtectedPackages; 706 707 boolean mFirstBoot; 708 709 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 710 711 // System configuration read by SystemConfig. 712 final int[] mGlobalGids; 713 final SparseArray<ArraySet<String>> mSystemPermissions; 714 @GuardedBy("mAvailableFeatures") 715 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 716 717 // If mac_permissions.xml was found for seinfo labeling. 718 boolean mFoundPolicyFile; 719 720 private final InstantAppRegistry mInstantAppRegistry; 721 722 @GuardedBy("mPackages") 723 int mChangedPackagesSequenceNumber; 724 /** 725 * List of changed [installed, removed or updated] packages. 726 * mapping from user id -> sequence number -> package name 727 */ 728 @GuardedBy("mPackages") 729 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 730 /** 731 * The sequence number of the last change to a package. 732 * mapping from user id -> package name -> sequence number 733 */ 734 @GuardedBy("mPackages") 735 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 736 737 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 738 @Override public boolean hasFeature(String feature) { 739 return PackageManagerService.this.hasSystemFeature(feature, 0); 740 } 741 }; 742 743 public static final class SharedLibraryEntry { 744 public final String path; 745 public final String apk; 746 public final SharedLibraryInfo info; 747 748 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 749 String declaringPackageName, int declaringPackageVersionCode) { 750 path = _path; 751 apk = _apk; 752 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 753 declaringPackageName, declaringPackageVersionCode), null); 754 } 755 } 756 757 // Currently known shared libraries. 758 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 759 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 760 new ArrayMap<>(); 761 762 // All available activities, for your resolving pleasure. 763 final ActivityIntentResolver mActivities = 764 new ActivityIntentResolver(); 765 766 // All available receivers, for your resolving pleasure. 767 final ActivityIntentResolver mReceivers = 768 new ActivityIntentResolver(); 769 770 // All available services, for your resolving pleasure. 771 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 772 773 // All available providers, for your resolving pleasure. 774 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 775 776 // Mapping from provider base names (first directory in content URI codePath) 777 // to the provider information. 778 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 779 new ArrayMap<String, PackageParser.Provider>(); 780 781 // Mapping from instrumentation class names to info about them. 782 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 783 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 784 785 // Mapping from permission names to info about them. 786 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 787 new ArrayMap<String, PackageParser.PermissionGroup>(); 788 789 // Packages whose data we have transfered into another package, thus 790 // should no longer exist. 791 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 792 793 // Broadcast actions that are only available to the system. 794 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 795 796 /** List of packages waiting for verification. */ 797 final SparseArray<PackageVerificationState> mPendingVerification 798 = new SparseArray<PackageVerificationState>(); 799 800 /** Set of packages associated with each app op permission. */ 801 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 802 803 final PackageInstallerService mInstallerService; 804 805 private final PackageDexOptimizer mPackageDexOptimizer; 806 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 807 // is used by other apps). 808 private final DexManager mDexManager; 809 810 private AtomicInteger mNextMoveId = new AtomicInteger(); 811 private final MoveCallbacks mMoveCallbacks; 812 813 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 814 815 // Cache of users who need badging. 816 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 817 818 /** Token for keys in mPendingVerification. */ 819 private int mPendingVerificationToken = 0; 820 821 volatile boolean mSystemReady; 822 volatile boolean mSafeMode; 823 volatile boolean mHasSystemUidErrors; 824 825 ApplicationInfo mAndroidApplication; 826 final ActivityInfo mResolveActivity = new ActivityInfo(); 827 final ResolveInfo mResolveInfo = new ResolveInfo(); 828 ComponentName mResolveComponentName; 829 PackageParser.Package mPlatformPackage; 830 ComponentName mCustomResolverComponentName; 831 832 boolean mResolverReplaced = false; 833 834 private final @Nullable ComponentName mIntentFilterVerifierComponent; 835 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 836 837 private int mIntentFilterVerificationToken = 0; 838 839 /** The service connection to the ephemeral resolver */ 840 final EphemeralResolverConnection mInstantAppResolverConnection; 841 842 /** Component used to install ephemeral applications */ 843 ComponentName mInstantAppInstallerComponent; 844 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 845 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 846 847 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 848 = new SparseArray<IntentFilterVerificationState>(); 849 850 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 851 852 // List of packages names to keep cached, even if they are uninstalled for all users 853 private List<String> mKeepUninstalledPackages; 854 855 private UserManagerInternal mUserManagerInternal; 856 857 private DeviceIdleController.LocalService mDeviceIdleController; 858 859 private File mCacheDir; 860 861 private ArraySet<String> mPrivappPermissionsViolations; 862 863 private Future<?> mPrepareAppDataFuture; 864 865 private static class IFVerificationParams { 866 PackageParser.Package pkg; 867 boolean replacing; 868 int userId; 869 int verifierUid; 870 871 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 872 int _userId, int _verifierUid) { 873 pkg = _pkg; 874 replacing = _replacing; 875 userId = _userId; 876 replacing = _replacing; 877 verifierUid = _verifierUid; 878 } 879 } 880 881 private interface IntentFilterVerifier<T extends IntentFilter> { 882 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 883 T filter, String packageName); 884 void startVerifications(int userId); 885 void receiveVerificationResponse(int verificationId); 886 } 887 888 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 889 private Context mContext; 890 private ComponentName mIntentFilterVerifierComponent; 891 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 892 893 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 894 mContext = context; 895 mIntentFilterVerifierComponent = verifierComponent; 896 } 897 898 private String getDefaultScheme() { 899 return IntentFilter.SCHEME_HTTPS; 900 } 901 902 @Override 903 public void startVerifications(int userId) { 904 // Launch verifications requests 905 int count = mCurrentIntentFilterVerifications.size(); 906 for (int n=0; n<count; n++) { 907 int verificationId = mCurrentIntentFilterVerifications.get(n); 908 final IntentFilterVerificationState ivs = 909 mIntentFilterVerificationStates.get(verificationId); 910 911 String packageName = ivs.getPackageName(); 912 913 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 914 final int filterCount = filters.size(); 915 ArraySet<String> domainsSet = new ArraySet<>(); 916 for (int m=0; m<filterCount; m++) { 917 PackageParser.ActivityIntentInfo filter = filters.get(m); 918 domainsSet.addAll(filter.getHostsList()); 919 } 920 synchronized (mPackages) { 921 if (mSettings.createIntentFilterVerificationIfNeededLPw( 922 packageName, domainsSet) != null) { 923 scheduleWriteSettingsLocked(); 924 } 925 } 926 sendVerificationRequest(userId, verificationId, ivs); 927 } 928 mCurrentIntentFilterVerifications.clear(); 929 } 930 931 private void sendVerificationRequest(int userId, int verificationId, 932 IntentFilterVerificationState ivs) { 933 934 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 935 verificationIntent.putExtra( 936 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 937 verificationId); 938 verificationIntent.putExtra( 939 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 940 getDefaultScheme()); 941 verificationIntent.putExtra( 942 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 943 ivs.getHostsString()); 944 verificationIntent.putExtra( 945 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 946 ivs.getPackageName()); 947 verificationIntent.setComponent(mIntentFilterVerifierComponent); 948 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 949 950 UserHandle user = new UserHandle(userId); 951 mContext.sendBroadcastAsUser(verificationIntent, user); 952 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 953 "Sending IntentFilter verification broadcast"); 954 } 955 956 public void receiveVerificationResponse(int verificationId) { 957 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 958 959 final boolean verified = ivs.isVerified(); 960 961 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 962 final int count = filters.size(); 963 if (DEBUG_DOMAIN_VERIFICATION) { 964 Slog.i(TAG, "Received verification response " + verificationId 965 + " for " + count + " filters, verified=" + verified); 966 } 967 for (int n=0; n<count; n++) { 968 PackageParser.ActivityIntentInfo filter = filters.get(n); 969 filter.setVerified(verified); 970 971 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 972 + " verified with result:" + verified + " and hosts:" 973 + ivs.getHostsString()); 974 } 975 976 mIntentFilterVerificationStates.remove(verificationId); 977 978 final String packageName = ivs.getPackageName(); 979 IntentFilterVerificationInfo ivi = null; 980 981 synchronized (mPackages) { 982 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 983 } 984 if (ivi == null) { 985 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 986 + verificationId + " packageName:" + packageName); 987 return; 988 } 989 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 990 "Updating IntentFilterVerificationInfo for package " + packageName 991 +" verificationId:" + verificationId); 992 993 synchronized (mPackages) { 994 if (verified) { 995 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 996 } else { 997 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 998 } 999 scheduleWriteSettingsLocked(); 1000 1001 final int userId = ivs.getUserId(); 1002 if (userId != UserHandle.USER_ALL) { 1003 final int userStatus = 1004 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1005 1006 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1007 boolean needUpdate = false; 1008 1009 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1010 // already been set by the User thru the Disambiguation dialog 1011 switch (userStatus) { 1012 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1013 if (verified) { 1014 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1015 } else { 1016 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1017 } 1018 needUpdate = true; 1019 break; 1020 1021 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1022 if (verified) { 1023 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1024 needUpdate = true; 1025 } 1026 break; 1027 1028 default: 1029 // Nothing to do 1030 } 1031 1032 if (needUpdate) { 1033 mSettings.updateIntentFilterVerificationStatusLPw( 1034 packageName, updatedStatus, userId); 1035 scheduleWritePackageRestrictionsLocked(userId); 1036 } 1037 } 1038 } 1039 } 1040 1041 @Override 1042 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1043 ActivityIntentInfo filter, String packageName) { 1044 if (!hasValidDomains(filter)) { 1045 return false; 1046 } 1047 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1048 if (ivs == null) { 1049 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1050 packageName); 1051 } 1052 if (DEBUG_DOMAIN_VERIFICATION) { 1053 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1054 } 1055 ivs.addFilter(filter); 1056 return true; 1057 } 1058 1059 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1060 int userId, int verificationId, String packageName) { 1061 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1062 verifierUid, userId, packageName); 1063 ivs.setPendingState(); 1064 synchronized (mPackages) { 1065 mIntentFilterVerificationStates.append(verificationId, ivs); 1066 mCurrentIntentFilterVerifications.add(verificationId); 1067 } 1068 return ivs; 1069 } 1070 } 1071 1072 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1073 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1074 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1075 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1076 } 1077 1078 // Set of pending broadcasts for aggregating enable/disable of components. 1079 static class PendingPackageBroadcasts { 1080 // for each user id, a map of <package name -> components within that package> 1081 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1082 1083 public PendingPackageBroadcasts() { 1084 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1085 } 1086 1087 public ArrayList<String> get(int userId, String packageName) { 1088 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1089 return packages.get(packageName); 1090 } 1091 1092 public void put(int userId, String packageName, ArrayList<String> components) { 1093 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1094 packages.put(packageName, components); 1095 } 1096 1097 public void remove(int userId, String packageName) { 1098 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1099 if (packages != null) { 1100 packages.remove(packageName); 1101 } 1102 } 1103 1104 public void remove(int userId) { 1105 mUidMap.remove(userId); 1106 } 1107 1108 public int userIdCount() { 1109 return mUidMap.size(); 1110 } 1111 1112 public int userIdAt(int n) { 1113 return mUidMap.keyAt(n); 1114 } 1115 1116 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1117 return mUidMap.get(userId); 1118 } 1119 1120 public int size() { 1121 // total number of pending broadcast entries across all userIds 1122 int num = 0; 1123 for (int i = 0; i< mUidMap.size(); i++) { 1124 num += mUidMap.valueAt(i).size(); 1125 } 1126 return num; 1127 } 1128 1129 public void clear() { 1130 mUidMap.clear(); 1131 } 1132 1133 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1134 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1135 if (map == null) { 1136 map = new ArrayMap<String, ArrayList<String>>(); 1137 mUidMap.put(userId, map); 1138 } 1139 return map; 1140 } 1141 } 1142 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1143 1144 // Service Connection to remote media container service to copy 1145 // package uri's from external media onto secure containers 1146 // or internal storage. 1147 private IMediaContainerService mContainerService = null; 1148 1149 static final int SEND_PENDING_BROADCAST = 1; 1150 static final int MCS_BOUND = 3; 1151 static final int END_COPY = 4; 1152 static final int INIT_COPY = 5; 1153 static final int MCS_UNBIND = 6; 1154 static final int START_CLEANING_PACKAGE = 7; 1155 static final int FIND_INSTALL_LOC = 8; 1156 static final int POST_INSTALL = 9; 1157 static final int MCS_RECONNECT = 10; 1158 static final int MCS_GIVE_UP = 11; 1159 static final int UPDATED_MEDIA_STATUS = 12; 1160 static final int WRITE_SETTINGS = 13; 1161 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1162 static final int PACKAGE_VERIFIED = 15; 1163 static final int CHECK_PENDING_VERIFICATION = 16; 1164 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1165 static final int INTENT_FILTER_VERIFIED = 18; 1166 static final int WRITE_PACKAGE_LIST = 19; 1167 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1168 1169 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1170 1171 // Delay time in millisecs 1172 static final int BROADCAST_DELAY = 10 * 1000; 1173 1174 static UserManagerService sUserManager; 1175 1176 // Stores a list of users whose package restrictions file needs to be updated 1177 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1178 1179 final private DefaultContainerConnection mDefContainerConn = 1180 new DefaultContainerConnection(); 1181 class DefaultContainerConnection implements ServiceConnection { 1182 public void onServiceConnected(ComponentName name, IBinder service) { 1183 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1184 final IMediaContainerService imcs = IMediaContainerService.Stub 1185 .asInterface(Binder.allowBlocking(service)); 1186 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1187 } 1188 1189 public void onServiceDisconnected(ComponentName name) { 1190 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1191 } 1192 } 1193 1194 // Recordkeeping of restore-after-install operations that are currently in flight 1195 // between the Package Manager and the Backup Manager 1196 static class PostInstallData { 1197 public InstallArgs args; 1198 public PackageInstalledInfo res; 1199 1200 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1201 args = _a; 1202 res = _r; 1203 } 1204 } 1205 1206 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1207 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1208 1209 // XML tags for backup/restore of various bits of state 1210 private static final String TAG_PREFERRED_BACKUP = "pa"; 1211 private static final String TAG_DEFAULT_APPS = "da"; 1212 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1213 1214 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1215 private static final String TAG_ALL_GRANTS = "rt-grants"; 1216 private static final String TAG_GRANT = "grant"; 1217 private static final String ATTR_PACKAGE_NAME = "pkg"; 1218 1219 private static final String TAG_PERMISSION = "perm"; 1220 private static final String ATTR_PERMISSION_NAME = "name"; 1221 private static final String ATTR_IS_GRANTED = "g"; 1222 private static final String ATTR_USER_SET = "set"; 1223 private static final String ATTR_USER_FIXED = "fixed"; 1224 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1225 1226 // System/policy permission grants are not backed up 1227 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1228 FLAG_PERMISSION_POLICY_FIXED 1229 | FLAG_PERMISSION_SYSTEM_FIXED 1230 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1231 1232 // And we back up these user-adjusted states 1233 private static final int USER_RUNTIME_GRANT_MASK = 1234 FLAG_PERMISSION_USER_SET 1235 | FLAG_PERMISSION_USER_FIXED 1236 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1237 1238 final @Nullable String mRequiredVerifierPackage; 1239 final @NonNull String mRequiredInstallerPackage; 1240 final @NonNull String mRequiredUninstallerPackage; 1241 final @Nullable String mSetupWizardPackage; 1242 final @Nullable String mStorageManagerPackage; 1243 final @NonNull String mServicesSystemSharedLibraryPackageName; 1244 final @NonNull String mSharedSystemSharedLibraryPackageName; 1245 1246 final boolean mPermissionReviewRequired; 1247 1248 private final PackageUsage mPackageUsage = new PackageUsage(); 1249 private final CompilerStats mCompilerStats = new CompilerStats(); 1250 1251 class PackageHandler extends Handler { 1252 private boolean mBound = false; 1253 final ArrayList<HandlerParams> mPendingInstalls = 1254 new ArrayList<HandlerParams>(); 1255 1256 private boolean connectToService() { 1257 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1258 " DefaultContainerService"); 1259 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1261 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1262 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 mBound = true; 1265 return true; 1266 } 1267 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1268 return false; 1269 } 1270 1271 private void disconnectService() { 1272 mContainerService = null; 1273 mBound = false; 1274 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1275 mContext.unbindService(mDefContainerConn); 1276 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1277 } 1278 1279 PackageHandler(Looper looper) { 1280 super(looper); 1281 } 1282 1283 public void handleMessage(Message msg) { 1284 try { 1285 doHandleMessage(msg); 1286 } finally { 1287 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1288 } 1289 } 1290 1291 void doHandleMessage(Message msg) { 1292 switch (msg.what) { 1293 case INIT_COPY: { 1294 HandlerParams params = (HandlerParams) msg.obj; 1295 int idx = mPendingInstalls.size(); 1296 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1297 // If a bind was already initiated we dont really 1298 // need to do anything. The pending install 1299 // will be processed later on. 1300 if (!mBound) { 1301 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1302 System.identityHashCode(mHandler)); 1303 // If this is the only one pending we might 1304 // have to bind to the service again. 1305 if (!connectToService()) { 1306 Slog.e(TAG, "Failed to bind to media container service"); 1307 params.serviceError(); 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1309 System.identityHashCode(mHandler)); 1310 if (params.traceMethod != null) { 1311 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1312 params.traceCookie); 1313 } 1314 return; 1315 } else { 1316 // Once we bind to the service, the first 1317 // pending request will be processed. 1318 mPendingInstalls.add(idx, params); 1319 } 1320 } else { 1321 mPendingInstalls.add(idx, params); 1322 // Already bound to the service. Just make 1323 // sure we trigger off processing the first request. 1324 if (idx == 0) { 1325 mHandler.sendEmptyMessage(MCS_BOUND); 1326 } 1327 } 1328 break; 1329 } 1330 case MCS_BOUND: { 1331 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1332 if (msg.obj != null) { 1333 mContainerService = (IMediaContainerService) msg.obj; 1334 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1335 System.identityHashCode(mHandler)); 1336 } 1337 if (mContainerService == null) { 1338 if (!mBound) { 1339 // Something seriously wrong since we are not bound and we are not 1340 // waiting for connection. Bail out. 1341 Slog.e(TAG, "Cannot bind to media container service"); 1342 for (HandlerParams params : mPendingInstalls) { 1343 // Indicate service bind error 1344 params.serviceError(); 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1346 System.identityHashCode(params)); 1347 if (params.traceMethod != null) { 1348 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1349 params.traceMethod, params.traceCookie); 1350 } 1351 return; 1352 } 1353 mPendingInstalls.clear(); 1354 } else { 1355 Slog.w(TAG, "Waiting to connect to media container service"); 1356 } 1357 } else if (mPendingInstalls.size() > 0) { 1358 HandlerParams params = mPendingInstalls.get(0); 1359 if (params != null) { 1360 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1361 System.identityHashCode(params)); 1362 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1363 if (params.startCopy()) { 1364 // We are done... look for more work or to 1365 // go idle. 1366 if (DEBUG_SD_INSTALL) Log.i(TAG, 1367 "Checking for more work or unbind..."); 1368 // Delete pending install 1369 if (mPendingInstalls.size() > 0) { 1370 mPendingInstalls.remove(0); 1371 } 1372 if (mPendingInstalls.size() == 0) { 1373 if (mBound) { 1374 if (DEBUG_SD_INSTALL) Log.i(TAG, 1375 "Posting delayed MCS_UNBIND"); 1376 removeMessages(MCS_UNBIND); 1377 Message ubmsg = obtainMessage(MCS_UNBIND); 1378 // Unbind after a little delay, to avoid 1379 // continual thrashing. 1380 sendMessageDelayed(ubmsg, 10000); 1381 } 1382 } else { 1383 // There are more pending requests in queue. 1384 // Just post MCS_BOUND message to trigger processing 1385 // of next pending install. 1386 if (DEBUG_SD_INSTALL) Log.i(TAG, 1387 "Posting MCS_BOUND for next work"); 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 } 1391 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1392 } 1393 } else { 1394 // Should never happen ideally. 1395 Slog.w(TAG, "Empty queue"); 1396 } 1397 break; 1398 } 1399 case MCS_RECONNECT: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1401 if (mPendingInstalls.size() > 0) { 1402 if (mBound) { 1403 disconnectService(); 1404 } 1405 if (!connectToService()) { 1406 Slog.e(TAG, "Failed to bind to media container service"); 1407 for (HandlerParams params : mPendingInstalls) { 1408 // Indicate service bind error 1409 params.serviceError(); 1410 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1411 System.identityHashCode(params)); 1412 } 1413 mPendingInstalls.clear(); 1414 } 1415 } 1416 break; 1417 } 1418 case MCS_UNBIND: { 1419 // If there is no actual work left, then time to unbind. 1420 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1421 1422 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1423 if (mBound) { 1424 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1425 1426 disconnectService(); 1427 } 1428 } else if (mPendingInstalls.size() > 0) { 1429 // There are more pending requests in queue. 1430 // Just post MCS_BOUND message to trigger processing 1431 // of next pending install. 1432 mHandler.sendEmptyMessage(MCS_BOUND); 1433 } 1434 1435 break; 1436 } 1437 case MCS_GIVE_UP: { 1438 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1439 HandlerParams params = mPendingInstalls.remove(0); 1440 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1441 System.identityHashCode(params)); 1442 break; 1443 } 1444 case SEND_PENDING_BROADCAST: { 1445 String packages[]; 1446 ArrayList<String> components[]; 1447 int size = 0; 1448 int uids[]; 1449 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1450 synchronized (mPackages) { 1451 if (mPendingBroadcasts == null) { 1452 return; 1453 } 1454 size = mPendingBroadcasts.size(); 1455 if (size <= 0) { 1456 // Nothing to be done. Just return 1457 return; 1458 } 1459 packages = new String[size]; 1460 components = new ArrayList[size]; 1461 uids = new int[size]; 1462 int i = 0; // filling out the above arrays 1463 1464 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1465 int packageUserId = mPendingBroadcasts.userIdAt(n); 1466 Iterator<Map.Entry<String, ArrayList<String>>> it 1467 = mPendingBroadcasts.packagesForUserId(packageUserId) 1468 .entrySet().iterator(); 1469 while (it.hasNext() && i < size) { 1470 Map.Entry<String, ArrayList<String>> ent = it.next(); 1471 packages[i] = ent.getKey(); 1472 components[i] = ent.getValue(); 1473 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1474 uids[i] = (ps != null) 1475 ? UserHandle.getUid(packageUserId, ps.appId) 1476 : -1; 1477 i++; 1478 } 1479 } 1480 size = i; 1481 mPendingBroadcasts.clear(); 1482 } 1483 // Send broadcasts 1484 for (int i = 0; i < size; i++) { 1485 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1486 } 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1488 break; 1489 } 1490 case START_CLEANING_PACKAGE: { 1491 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1492 final String packageName = (String)msg.obj; 1493 final int userId = msg.arg1; 1494 final boolean andCode = msg.arg2 != 0; 1495 synchronized (mPackages) { 1496 if (userId == UserHandle.USER_ALL) { 1497 int[] users = sUserManager.getUserIds(); 1498 for (int user : users) { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(user, packageName, andCode)); 1501 } 1502 } else { 1503 mSettings.addPackageToCleanLPw( 1504 new PackageCleanItem(userId, packageName, andCode)); 1505 } 1506 } 1507 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1508 startCleaningPackages(); 1509 } break; 1510 case POST_INSTALL: { 1511 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1512 1513 PostInstallData data = mRunningInstalls.get(msg.arg1); 1514 final boolean didRestore = (msg.arg2 != 0); 1515 mRunningInstalls.delete(msg.arg1); 1516 1517 if (data != null) { 1518 InstallArgs args = data.args; 1519 PackageInstalledInfo parentRes = data.res; 1520 1521 final boolean grantPermissions = (args.installFlags 1522 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1523 final boolean killApp = (args.installFlags 1524 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1525 final String[] grantedPermissions = args.installGrantPermissions; 1526 1527 // Handle the parent package 1528 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1529 grantedPermissions, didRestore, args.installerPackageName, 1530 args.observer); 1531 1532 // Handle the child packages 1533 final int childCount = (parentRes.addedChildPackages != null) 1534 ? parentRes.addedChildPackages.size() : 0; 1535 for (int i = 0; i < childCount; i++) { 1536 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1537 handlePackagePostInstall(childRes, grantPermissions, killApp, 1538 grantedPermissions, false, args.installerPackageName, 1539 args.observer); 1540 } 1541 1542 // Log tracing if needed 1543 if (args.traceMethod != null) { 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1545 args.traceCookie); 1546 } 1547 } else { 1548 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1549 } 1550 1551 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1552 } break; 1553 case UPDATED_MEDIA_STATUS: { 1554 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1555 boolean reportStatus = msg.arg1 == 1; 1556 boolean doGc = msg.arg2 == 1; 1557 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1558 if (doGc) { 1559 // Force a gc to clear up stale containers. 1560 Runtime.getRuntime().gc(); 1561 } 1562 if (msg.obj != null) { 1563 @SuppressWarnings("unchecked") 1564 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1565 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1566 // Unload containers 1567 unloadAllContainers(args); 1568 } 1569 if (reportStatus) { 1570 try { 1571 if (DEBUG_SD_INSTALL) Log.i(TAG, 1572 "Invoking StorageManagerService call back"); 1573 PackageHelper.getStorageManager().finishMediaUpdate(); 1574 } catch (RemoteException e) { 1575 Log.e(TAG, "StorageManagerService not running?"); 1576 } 1577 } 1578 } break; 1579 case WRITE_SETTINGS: { 1580 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1581 synchronized (mPackages) { 1582 removeMessages(WRITE_SETTINGS); 1583 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1584 mSettings.writeLPr(); 1585 mDirtyUsers.clear(); 1586 } 1587 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1588 } break; 1589 case WRITE_PACKAGE_RESTRICTIONS: { 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1593 for (int userId : mDirtyUsers) { 1594 mSettings.writePackageRestrictionsLPr(userId); 1595 } 1596 mDirtyUsers.clear(); 1597 } 1598 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1599 } break; 1600 case WRITE_PACKAGE_LIST: { 1601 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1602 synchronized (mPackages) { 1603 removeMessages(WRITE_PACKAGE_LIST); 1604 mSettings.writePackageListLPr(msg.arg1); 1605 } 1606 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1607 } break; 1608 case CHECK_PENDING_VERIFICATION: { 1609 final int verificationId = msg.arg1; 1610 final PackageVerificationState state = mPendingVerification.get(verificationId); 1611 1612 if ((state != null) && !state.timeoutExtended()) { 1613 final InstallArgs args = state.getInstallArgs(); 1614 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1615 1616 Slog.i(TAG, "Verification timed out for " + originUri); 1617 mPendingVerification.remove(verificationId); 1618 1619 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1620 1621 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1622 Slog.i(TAG, "Continuing with installation of " + originUri); 1623 state.setVerifierResponse(Binder.getCallingUid(), 1624 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1625 broadcastPackageVerified(verificationId, originUri, 1626 PackageManager.VERIFICATION_ALLOW, 1627 state.getInstallArgs().getUser()); 1628 try { 1629 ret = args.copyApk(mContainerService, true); 1630 } catch (RemoteException e) { 1631 Slog.e(TAG, "Could not contact the ContainerService"); 1632 } 1633 } else { 1634 broadcastPackageVerified(verificationId, originUri, 1635 PackageManager.VERIFICATION_REJECT, 1636 state.getInstallArgs().getUser()); 1637 } 1638 1639 Trace.asyncTraceEnd( 1640 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1641 1642 processPendingInstall(args, ret); 1643 mHandler.sendEmptyMessage(MCS_UNBIND); 1644 } 1645 break; 1646 } 1647 case PACKAGE_VERIFIED: { 1648 final int verificationId = msg.arg1; 1649 1650 final PackageVerificationState state = mPendingVerification.get(verificationId); 1651 if (state == null) { 1652 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1653 break; 1654 } 1655 1656 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1657 1658 state.setVerifierResponse(response.callerUid, response.code); 1659 1660 if (state.isVerificationComplete()) { 1661 mPendingVerification.remove(verificationId); 1662 1663 final InstallArgs args = state.getInstallArgs(); 1664 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1665 1666 int ret; 1667 if (state.isInstallAllowed()) { 1668 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1669 broadcastPackageVerified(verificationId, originUri, 1670 response.code, state.getInstallArgs().getUser()); 1671 try { 1672 ret = args.copyApk(mContainerService, true); 1673 } catch (RemoteException e) { 1674 Slog.e(TAG, "Could not contact the ContainerService"); 1675 } 1676 } else { 1677 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1678 } 1679 1680 Trace.asyncTraceEnd( 1681 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1682 1683 processPendingInstall(args, ret); 1684 mHandler.sendEmptyMessage(MCS_UNBIND); 1685 } 1686 1687 break; 1688 } 1689 case START_INTENT_FILTER_VERIFICATIONS: { 1690 IFVerificationParams params = (IFVerificationParams) msg.obj; 1691 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1692 params.replacing, params.pkg); 1693 break; 1694 } 1695 case INTENT_FILTER_VERIFIED: { 1696 final int verificationId = msg.arg1; 1697 1698 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1699 verificationId); 1700 if (state == null) { 1701 Slog.w(TAG, "Invalid IntentFilter verification token " 1702 + verificationId + " received"); 1703 break; 1704 } 1705 1706 final int userId = state.getUserId(); 1707 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1709 "Processing IntentFilter verification with token:" 1710 + verificationId + " and userId:" + userId); 1711 1712 final IntentFilterVerificationResponse response = 1713 (IntentFilterVerificationResponse) msg.obj; 1714 1715 state.setVerifierResponse(response.callerUid, response.code); 1716 1717 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1718 "IntentFilter verification with token:" + verificationId 1719 + " and userId:" + userId 1720 + " is settings verifier response with response code:" 1721 + response.code); 1722 1723 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1724 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1725 + response.getFailedDomainsString()); 1726 } 1727 1728 if (state.isVerificationComplete()) { 1729 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1730 } else { 1731 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1732 "IntentFilter verification with token:" + verificationId 1733 + " was not said to be complete"); 1734 } 1735 1736 break; 1737 } 1738 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1739 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1740 mInstantAppResolverConnection, 1741 (EphemeralRequest) msg.obj, 1742 mInstantAppInstallerActivity, 1743 mHandler); 1744 } 1745 } 1746 } 1747 } 1748 1749 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1750 boolean killApp, String[] grantedPermissions, 1751 boolean launchedForRestore, String installerPackage, 1752 IPackageInstallObserver2 installObserver) { 1753 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1754 // Send the removed broadcasts 1755 if (res.removedInfo != null) { 1756 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1757 } 1758 1759 // Now that we successfully installed the package, grant runtime 1760 // permissions if requested before broadcasting the install. Also 1761 // for legacy apps in permission review mode we clear the permission 1762 // review flag which is used to emulate runtime permissions for 1763 // legacy apps. 1764 if (grantPermissions) { 1765 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1766 } 1767 1768 final boolean update = res.removedInfo != null 1769 && res.removedInfo.removedPackage != null; 1770 1771 // If this is the first time we have child packages for a disabled privileged 1772 // app that had no children, we grant requested runtime permissions to the new 1773 // children if the parent on the system image had them already granted. 1774 if (res.pkg.parentPackage != null) { 1775 synchronized (mPackages) { 1776 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1777 } 1778 } 1779 1780 synchronized (mPackages) { 1781 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1782 } 1783 1784 final String packageName = res.pkg.applicationInfo.packageName; 1785 1786 // Determine the set of users who are adding this package for 1787 // the first time vs. those who are seeing an update. 1788 int[] firstUsers = EMPTY_INT_ARRAY; 1789 int[] updateUsers = EMPTY_INT_ARRAY; 1790 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1791 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1792 for (int newUser : res.newUsers) { 1793 if (ps.getInstantApp(newUser)) { 1794 continue; 1795 } 1796 if (allNewUsers) { 1797 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1798 continue; 1799 } 1800 boolean isNew = true; 1801 for (int origUser : res.origUsers) { 1802 if (origUser == newUser) { 1803 isNew = false; 1804 break; 1805 } 1806 } 1807 if (isNew) { 1808 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1809 } else { 1810 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1811 } 1812 } 1813 1814 // Send installed broadcasts if the package is not a static shared lib. 1815 if (res.pkg.staticSharedLibName == null) { 1816 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1817 1818 // Send added for users that see the package for the first time 1819 // sendPackageAddedForNewUsers also deals with system apps 1820 int appId = UserHandle.getAppId(res.uid); 1821 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1822 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1823 1824 // Send added for users that don't see the package for the first time 1825 Bundle extras = new Bundle(1); 1826 extras.putInt(Intent.EXTRA_UID, res.uid); 1827 if (update) { 1828 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1829 } 1830 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1831 extras, 0 /*flags*/, null /*targetPackage*/, 1832 null /*finishedReceiver*/, updateUsers); 1833 1834 // Send replaced for users that don't see the package for the first time 1835 if (update) { 1836 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1837 packageName, extras, 0 /*flags*/, 1838 null /*targetPackage*/, null /*finishedReceiver*/, 1839 updateUsers); 1840 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1841 null /*package*/, null /*extras*/, 0 /*flags*/, 1842 packageName /*targetPackage*/, 1843 null /*finishedReceiver*/, updateUsers); 1844 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1845 // First-install and we did a restore, so we're responsible for the 1846 // first-launch broadcast. 1847 if (DEBUG_BACKUP) { 1848 Slog.i(TAG, "Post-restore of " + packageName 1849 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1850 } 1851 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1852 } 1853 1854 // Send broadcast package appeared if forward locked/external for all users 1855 // treat asec-hosted packages like removable media on upgrade 1856 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1857 if (DEBUG_INSTALL) { 1858 Slog.i(TAG, "upgrading pkg " + res.pkg 1859 + " is ASEC-hosted -> AVAILABLE"); 1860 } 1861 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1862 ArrayList<String> pkgList = new ArrayList<>(1); 1863 pkgList.add(packageName); 1864 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1865 } 1866 } 1867 1868 // Work that needs to happen on first install within each user 1869 if (firstUsers != null && firstUsers.length > 0) { 1870 synchronized (mPackages) { 1871 for (int userId : firstUsers) { 1872 // If this app is a browser and it's newly-installed for some 1873 // users, clear any default-browser state in those users. The 1874 // app's nature doesn't depend on the user, so we can just check 1875 // its browser nature in any user and generalize. 1876 if (packageIsBrowser(packageName, userId)) { 1877 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1878 } 1879 1880 // We may also need to apply pending (restored) runtime 1881 // permission grants within these users. 1882 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1883 } 1884 } 1885 } 1886 1887 // Log current value of "unknown sources" setting 1888 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1889 getUnknownSourcesSettings()); 1890 1891 // Force a gc to clear up things 1892 Runtime.getRuntime().gc(); 1893 1894 // Remove the replaced package's older resources safely now 1895 // We delete after a gc for applications on sdcard. 1896 if (res.removedInfo != null && res.removedInfo.args != null) { 1897 synchronized (mInstallLock) { 1898 res.removedInfo.args.doPostDeleteLI(true); 1899 } 1900 } 1901 1902 // Notify DexManager that the package was installed for new users. 1903 // The updated users should already be indexed and the package code paths 1904 // should not change. 1905 // Don't notify the manager for ephemeral apps as they are not expected to 1906 // survive long enough to benefit of background optimizations. 1907 for (int userId : firstUsers) { 1908 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1909 mDexManager.notifyPackageInstalled(info, userId); 1910 } 1911 } 1912 1913 // If someone is watching installs - notify them 1914 if (installObserver != null) { 1915 try { 1916 Bundle extras = extrasForInstallResult(res); 1917 installObserver.onPackageInstalled(res.name, res.returnCode, 1918 res.returnMsg, extras); 1919 } catch (RemoteException e) { 1920 Slog.i(TAG, "Observer no longer exists."); 1921 } 1922 } 1923 } 1924 1925 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1926 PackageParser.Package pkg) { 1927 if (pkg.parentPackage == null) { 1928 return; 1929 } 1930 if (pkg.requestedPermissions == null) { 1931 return; 1932 } 1933 final PackageSetting disabledSysParentPs = mSettings 1934 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1935 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1936 || !disabledSysParentPs.isPrivileged() 1937 || (disabledSysParentPs.childPackageNames != null 1938 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1939 return; 1940 } 1941 final int[] allUserIds = sUserManager.getUserIds(); 1942 final int permCount = pkg.requestedPermissions.size(); 1943 for (int i = 0; i < permCount; i++) { 1944 String permission = pkg.requestedPermissions.get(i); 1945 BasePermission bp = mSettings.mPermissions.get(permission); 1946 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1947 continue; 1948 } 1949 for (int userId : allUserIds) { 1950 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1951 permission, userId)) { 1952 grantRuntimePermission(pkg.packageName, permission, userId); 1953 } 1954 } 1955 } 1956 } 1957 1958 private StorageEventListener mStorageListener = new StorageEventListener() { 1959 @Override 1960 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1961 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1962 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1963 final String volumeUuid = vol.getFsUuid(); 1964 1965 // Clean up any users or apps that were removed or recreated 1966 // while this volume was missing 1967 sUserManager.reconcileUsers(volumeUuid); 1968 reconcileApps(volumeUuid); 1969 1970 // Clean up any install sessions that expired or were 1971 // cancelled while this volume was missing 1972 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1973 1974 loadPrivatePackages(vol); 1975 1976 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1977 unloadPrivatePackages(vol); 1978 } 1979 } 1980 1981 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1982 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1983 updateExternalMediaStatus(true, false); 1984 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1985 updateExternalMediaStatus(false, false); 1986 } 1987 } 1988 } 1989 1990 @Override 1991 public void onVolumeForgotten(String fsUuid) { 1992 if (TextUtils.isEmpty(fsUuid)) { 1993 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1994 return; 1995 } 1996 1997 // Remove any apps installed on the forgotten volume 1998 synchronized (mPackages) { 1999 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2000 for (PackageSetting ps : packages) { 2001 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2002 deletePackageVersioned(new VersionedPackage(ps.name, 2003 PackageManager.VERSION_CODE_HIGHEST), 2004 new LegacyPackageDeleteObserver(null).getBinder(), 2005 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2006 // Try very hard to release any references to this package 2007 // so we don't risk the system server being killed due to 2008 // open FDs 2009 AttributeCache.instance().removePackage(ps.name); 2010 } 2011 2012 mSettings.onVolumeForgotten(fsUuid); 2013 mSettings.writeLPr(); 2014 } 2015 } 2016 }; 2017 2018 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2019 String[] grantedPermissions) { 2020 for (int userId : userIds) { 2021 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2022 } 2023 } 2024 2025 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2026 String[] grantedPermissions) { 2027 SettingBase sb = (SettingBase) pkg.mExtras; 2028 if (sb == null) { 2029 return; 2030 } 2031 2032 PermissionsState permissionsState = sb.getPermissionsState(); 2033 2034 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2035 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2036 2037 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2038 >= Build.VERSION_CODES.M; 2039 2040 for (String permission : pkg.requestedPermissions) { 2041 final BasePermission bp; 2042 synchronized (mPackages) { 2043 bp = mSettings.mPermissions.get(permission); 2044 } 2045 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2046 && (grantedPermissions == null 2047 || ArrayUtils.contains(grantedPermissions, permission))) { 2048 final int flags = permissionsState.getPermissionFlags(permission, userId); 2049 if (supportsRuntimePermissions) { 2050 // Installer cannot change immutable permissions. 2051 if ((flags & immutableFlags) == 0) { 2052 grantRuntimePermission(pkg.packageName, permission, userId); 2053 } 2054 } else if (mPermissionReviewRequired) { 2055 // In permission review mode we clear the review flag when we 2056 // are asked to install the app with all permissions granted. 2057 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2058 updatePermissionFlags(permission, pkg.packageName, 2059 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2060 } 2061 } 2062 } 2063 } 2064 } 2065 2066 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2067 Bundle extras = null; 2068 switch (res.returnCode) { 2069 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2070 extras = new Bundle(); 2071 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2072 res.origPermission); 2073 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2074 res.origPackage); 2075 break; 2076 } 2077 case PackageManager.INSTALL_SUCCEEDED: { 2078 extras = new Bundle(); 2079 extras.putBoolean(Intent.EXTRA_REPLACING, 2080 res.removedInfo != null && res.removedInfo.removedPackage != null); 2081 break; 2082 } 2083 } 2084 return extras; 2085 } 2086 2087 void scheduleWriteSettingsLocked() { 2088 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2089 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2090 } 2091 } 2092 2093 void scheduleWritePackageListLocked(int userId) { 2094 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2095 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2096 msg.arg1 = userId; 2097 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2098 } 2099 } 2100 2101 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2102 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2103 scheduleWritePackageRestrictionsLocked(userId); 2104 } 2105 2106 void scheduleWritePackageRestrictionsLocked(int userId) { 2107 final int[] userIds = (userId == UserHandle.USER_ALL) 2108 ? sUserManager.getUserIds() : new int[]{userId}; 2109 for (int nextUserId : userIds) { 2110 if (!sUserManager.exists(nextUserId)) return; 2111 mDirtyUsers.add(nextUserId); 2112 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2113 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2114 } 2115 } 2116 } 2117 2118 public static PackageManagerService main(Context context, Installer installer, 2119 boolean factoryTest, boolean onlyCore) { 2120 // Self-check for initial settings. 2121 PackageManagerServiceCompilerMapping.checkProperties(); 2122 2123 PackageManagerService m = new PackageManagerService(context, installer, 2124 factoryTest, onlyCore); 2125 m.enableSystemUserPackages(); 2126 ServiceManager.addService("package", m); 2127 return m; 2128 } 2129 2130 private void enableSystemUserPackages() { 2131 if (!UserManager.isSplitSystemUser()) { 2132 return; 2133 } 2134 // For system user, enable apps based on the following conditions: 2135 // - app is whitelisted or belong to one of these groups: 2136 // -- system app which has no launcher icons 2137 // -- system app which has INTERACT_ACROSS_USERS permission 2138 // -- system IME app 2139 // - app is not in the blacklist 2140 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2141 Set<String> enableApps = new ArraySet<>(); 2142 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2143 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2144 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2145 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2146 enableApps.addAll(wlApps); 2147 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2148 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2149 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2150 enableApps.removeAll(blApps); 2151 Log.i(TAG, "Applications installed for system user: " + enableApps); 2152 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2153 UserHandle.SYSTEM); 2154 final int allAppsSize = allAps.size(); 2155 synchronized (mPackages) { 2156 for (int i = 0; i < allAppsSize; i++) { 2157 String pName = allAps.get(i); 2158 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2159 // Should not happen, but we shouldn't be failing if it does 2160 if (pkgSetting == null) { 2161 continue; 2162 } 2163 boolean install = enableApps.contains(pName); 2164 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2165 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2166 + " for system user"); 2167 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2168 } 2169 } 2170 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2171 } 2172 } 2173 2174 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2175 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2176 Context.DISPLAY_SERVICE); 2177 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2178 } 2179 2180 /** 2181 * Requests that files preopted on a secondary system partition be copied to the data partition 2182 * if possible. Note that the actual copying of the files is accomplished by init for security 2183 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2184 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2185 */ 2186 private static void requestCopyPreoptedFiles() { 2187 final int WAIT_TIME_MS = 100; 2188 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2189 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2190 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2191 // We will wait for up to 100 seconds. 2192 final long timeStart = SystemClock.uptimeMillis(); 2193 final long timeEnd = timeStart + 100 * 1000; 2194 long timeNow = timeStart; 2195 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2196 try { 2197 Thread.sleep(WAIT_TIME_MS); 2198 } catch (InterruptedException e) { 2199 // Do nothing 2200 } 2201 timeNow = SystemClock.uptimeMillis(); 2202 if (timeNow > timeEnd) { 2203 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2204 Slog.wtf(TAG, "cppreopt did not finish!"); 2205 break; 2206 } 2207 } 2208 2209 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2210 } 2211 } 2212 2213 public PackageManagerService(Context context, Installer installer, 2214 boolean factoryTest, boolean onlyCore) { 2215 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2216 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2217 SystemClock.uptimeMillis()); 2218 2219 if (mSdkVersion <= 0) { 2220 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2221 } 2222 2223 mContext = context; 2224 2225 mPermissionReviewRequired = context.getResources().getBoolean( 2226 R.bool.config_permissionReviewRequired); 2227 2228 mFactoryTest = factoryTest; 2229 mOnlyCore = onlyCore; 2230 mMetrics = new DisplayMetrics(); 2231 mSettings = new Settings(mPackages); 2232 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 2245 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2246 if (separateProcesses != null && separateProcesses.length() > 0) { 2247 if ("*".equals(separateProcesses)) { 2248 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2249 mSeparateProcesses = null; 2250 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2251 } else { 2252 mDefParseFlags = 0; 2253 mSeparateProcesses = separateProcesses.split(","); 2254 Slog.w(TAG, "Running with debug.separate_processes: " 2255 + separateProcesses); 2256 } 2257 } else { 2258 mDefParseFlags = 0; 2259 mSeparateProcesses = null; 2260 } 2261 2262 mInstaller = installer; 2263 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2264 "*dexopt*"); 2265 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2266 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2267 2268 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2269 FgThread.get().getLooper()); 2270 2271 getDefaultDisplayMetrics(context, mMetrics); 2272 2273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2274 SystemConfig systemConfig = SystemConfig.getInstance(); 2275 mGlobalGids = systemConfig.getGlobalGids(); 2276 mSystemPermissions = systemConfig.getSystemPermissions(); 2277 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2279 2280 mProtectedPackages = new ProtectedPackages(mContext); 2281 2282 synchronized (mInstallLock) { 2283 // writer 2284 synchronized (mPackages) { 2285 mHandlerThread = new ServiceThread(TAG, 2286 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2287 mHandlerThread.start(); 2288 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2289 mProcessLoggingHandler = new ProcessLoggingHandler(); 2290 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2291 2292 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2293 mInstantAppRegistry = new InstantAppRegistry(this); 2294 2295 File dataDir = Environment.getDataDirectory(); 2296 mAppInstallDir = new File(dataDir, "app"); 2297 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2298 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2299 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2300 sUserManager = new UserManagerService(context, this, 2301 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2302 2303 // Propagate permission configuration in to package manager. 2304 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2305 = systemConfig.getPermissions(); 2306 for (int i=0; i<permConfig.size(); i++) { 2307 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2308 BasePermission bp = mSettings.mPermissions.get(perm.name); 2309 if (bp == null) { 2310 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2311 mSettings.mPermissions.put(perm.name, bp); 2312 } 2313 if (perm.gids != null) { 2314 bp.setGids(perm.gids, perm.perUser); 2315 } 2316 } 2317 2318 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2319 final int builtInLibCount = libConfig.size(); 2320 for (int i = 0; i < builtInLibCount; i++) { 2321 String name = libConfig.keyAt(i); 2322 String path = libConfig.valueAt(i); 2323 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2324 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2325 } 2326 2327 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2328 2329 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2330 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2332 2333 // Clean up orphaned packages for which the code path doesn't exist 2334 // and they are an update to a system app - caused by bug/32321269 2335 final int packageSettingCount = mSettings.mPackages.size(); 2336 for (int i = packageSettingCount - 1; i >= 0; i--) { 2337 PackageSetting ps = mSettings.mPackages.valueAt(i); 2338 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2339 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2340 mSettings.mPackages.removeAt(i); 2341 mSettings.enableSystemPackageLPw(ps.name); 2342 } 2343 } 2344 2345 if (mFirstBoot) { 2346 requestCopyPreoptedFiles(); 2347 } 2348 2349 String customResolverActivity = Resources.getSystem().getString( 2350 R.string.config_customResolverActivity); 2351 if (TextUtils.isEmpty(customResolverActivity)) { 2352 customResolverActivity = null; 2353 } else { 2354 mCustomResolverComponentName = ComponentName.unflattenFromString( 2355 customResolverActivity); 2356 } 2357 2358 long startTime = SystemClock.uptimeMillis(); 2359 2360 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2361 startTime); 2362 2363 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2364 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2365 2366 if (bootClassPath == null) { 2367 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2368 } 2369 2370 if (systemServerClassPath == null) { 2371 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2372 } 2373 2374 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2375 final String[] dexCodeInstructionSets = 2376 getDexCodeInstructionSets( 2377 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2378 2379 /** 2380 * Ensure all external libraries have had dexopt run on them. 2381 */ 2382 if (mSharedLibraries.size() > 0) { 2383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2384 // NOTE: For now, we're compiling these system "shared libraries" 2385 // (and framework jars) into all available architectures. It's possible 2386 // to compile them only when we come across an app that uses them (there's 2387 // already logic for that in scanPackageLI) but that adds some complexity. 2388 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2389 final int libCount = mSharedLibraries.size(); 2390 for (int i = 0; i < libCount; i++) { 2391 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2392 final int versionCount = versionedLib.size(); 2393 for (int j = 0; j < versionCount; j++) { 2394 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2395 final String libPath = libEntry.path != null 2396 ? libEntry.path : libEntry.apk; 2397 if (libPath == null) { 2398 continue; 2399 } 2400 try { 2401 // Shared libraries do not have profiles so we perform a full 2402 // AOT compilation (if needed). 2403 int dexoptNeeded = DexFile.getDexOptNeeded( 2404 libPath, dexCodeInstructionSet, 2405 getCompilerFilterForReason(REASON_SHARED_APK), 2406 false /* newProfile */); 2407 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2408 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2409 dexCodeInstructionSet, dexoptNeeded, null, 2410 DEXOPT_PUBLIC, 2411 getCompilerFilterForReason(REASON_SHARED_APK), 2412 StorageManager.UUID_PRIVATE_INTERNAL, 2413 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2414 } 2415 } catch (FileNotFoundException e) { 2416 Slog.w(TAG, "Library not found: " + libPath); 2417 } catch (IOException | InstallerException e) { 2418 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2419 + e.getMessage()); 2420 } 2421 } 2422 } 2423 } 2424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2425 } 2426 2427 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2428 2429 final VersionInfo ver = mSettings.getInternalVersion(); 2430 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2431 2432 // when upgrading from pre-M, promote system app permissions from install to runtime 2433 mPromoteSystemApps = 2434 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2435 2436 // When upgrading from pre-N, we need to handle package extraction like first boot, 2437 // as there is no profiling data available. 2438 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2439 2440 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2441 2442 // save off the names of pre-existing system packages prior to scanning; we don't 2443 // want to automatically grant runtime permissions for new system apps 2444 if (mPromoteSystemApps) { 2445 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2446 while (pkgSettingIter.hasNext()) { 2447 PackageSetting ps = pkgSettingIter.next(); 2448 if (isSystemApp(ps)) { 2449 mExistingSystemPackages.add(ps.name); 2450 } 2451 } 2452 } 2453 2454 mCacheDir = preparePackageParserCache(mIsUpgrade); 2455 2456 // Set flag to monitor and not change apk file paths when 2457 // scanning install directories. 2458 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2459 2460 if (mIsUpgrade || mFirstBoot) { 2461 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2462 } 2463 2464 // Collect vendor overlay packages. (Do this before scanning any apps.) 2465 // For security and version matching reason, only consider 2466 // overlay packages if they reside in the right directory. 2467 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2468 | PackageParser.PARSE_IS_SYSTEM 2469 | PackageParser.PARSE_IS_SYSTEM_DIR 2470 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2471 2472 // Find base frameworks (resource packages without code). 2473 scanDirTracedLI(frameworkDir, mDefParseFlags 2474 | PackageParser.PARSE_IS_SYSTEM 2475 | PackageParser.PARSE_IS_SYSTEM_DIR 2476 | PackageParser.PARSE_IS_PRIVILEGED, 2477 scanFlags | SCAN_NO_DEX, 0); 2478 2479 // Collected privileged system packages. 2480 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2481 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2482 | PackageParser.PARSE_IS_SYSTEM 2483 | PackageParser.PARSE_IS_SYSTEM_DIR 2484 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2485 2486 // Collect ordinary system packages. 2487 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2488 scanDirTracedLI(systemAppDir, mDefParseFlags 2489 | PackageParser.PARSE_IS_SYSTEM 2490 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2491 2492 // Collect all vendor packages. 2493 File vendorAppDir = new File("/vendor/app"); 2494 try { 2495 vendorAppDir = vendorAppDir.getCanonicalFile(); 2496 } catch (IOException e) { 2497 // failed to look up canonical path, continue with original one 2498 } 2499 scanDirTracedLI(vendorAppDir, mDefParseFlags 2500 | PackageParser.PARSE_IS_SYSTEM 2501 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2502 2503 // Collect all OEM packages. 2504 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2505 scanDirTracedLI(oemAppDir, mDefParseFlags 2506 | PackageParser.PARSE_IS_SYSTEM 2507 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2508 2509 // Prune any system packages that no longer exist. 2510 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2511 if (!mOnlyCore) { 2512 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2513 while (psit.hasNext()) { 2514 PackageSetting ps = psit.next(); 2515 2516 /* 2517 * If this is not a system app, it can't be a 2518 * disable system app. 2519 */ 2520 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2521 continue; 2522 } 2523 2524 /* 2525 * If the package is scanned, it's not erased. 2526 */ 2527 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2528 if (scannedPkg != null) { 2529 /* 2530 * If the system app is both scanned and in the 2531 * disabled packages list, then it must have been 2532 * added via OTA. Remove it from the currently 2533 * scanned package so the previously user-installed 2534 * application can be scanned. 2535 */ 2536 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2537 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2538 + ps.name + "; removing system app. Last known codePath=" 2539 + ps.codePathString + ", installStatus=" + ps.installStatus 2540 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2541 + scannedPkg.mVersionCode); 2542 removePackageLI(scannedPkg, true); 2543 mExpectingBetter.put(ps.name, ps.codePath); 2544 } 2545 2546 continue; 2547 } 2548 2549 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2550 psit.remove(); 2551 logCriticalInfo(Log.WARN, "System package " + ps.name 2552 + " no longer exists; it's data will be wiped"); 2553 // Actual deletion of code and data will be handled by later 2554 // reconciliation step 2555 } else { 2556 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2557 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2558 possiblyDeletedUpdatedSystemApps.add(ps.name); 2559 } 2560 } 2561 } 2562 } 2563 2564 //look for any incomplete package installations 2565 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2566 for (int i = 0; i < deletePkgsList.size(); i++) { 2567 // Actual deletion of code and data will be handled by later 2568 // reconciliation step 2569 final String packageName = deletePkgsList.get(i).name; 2570 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2571 synchronized (mPackages) { 2572 mSettings.removePackageLPw(packageName); 2573 } 2574 } 2575 2576 //delete tmp files 2577 deleteTempPackageFiles(); 2578 2579 // Remove any shared userIDs that have no associated packages 2580 mSettings.pruneSharedUsersLPw(); 2581 2582 if (!mOnlyCore) { 2583 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2584 SystemClock.uptimeMillis()); 2585 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2586 2587 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2588 | PackageParser.PARSE_FORWARD_LOCK, 2589 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2590 2591 /** 2592 * Remove disable package settings for any updated system 2593 * apps that were removed via an OTA. If they're not a 2594 * previously-updated app, remove them completely. 2595 * Otherwise, just revoke their system-level permissions. 2596 */ 2597 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2598 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2599 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2600 2601 String msg; 2602 if (deletedPkg == null) { 2603 msg = "Updated system package " + deletedAppName 2604 + " no longer exists; it's data will be wiped"; 2605 // Actual deletion of code and data will be handled by later 2606 // reconciliation step 2607 } else { 2608 msg = "Updated system app + " + deletedAppName 2609 + " no longer present; removing system privileges for " 2610 + deletedAppName; 2611 2612 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2613 2614 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2615 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2616 } 2617 logCriticalInfo(Log.WARN, msg); 2618 } 2619 2620 /** 2621 * Make sure all system apps that we expected to appear on 2622 * the userdata partition actually showed up. If they never 2623 * appeared, crawl back and revive the system version. 2624 */ 2625 for (int i = 0; i < mExpectingBetter.size(); i++) { 2626 final String packageName = mExpectingBetter.keyAt(i); 2627 if (!mPackages.containsKey(packageName)) { 2628 final File scanFile = mExpectingBetter.valueAt(i); 2629 2630 logCriticalInfo(Log.WARN, "Expected better " + packageName 2631 + " but never showed up; reverting to system"); 2632 2633 int reparseFlags = mDefParseFlags; 2634 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2635 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2636 | PackageParser.PARSE_IS_SYSTEM_DIR 2637 | PackageParser.PARSE_IS_PRIVILEGED; 2638 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2639 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2640 | PackageParser.PARSE_IS_SYSTEM_DIR; 2641 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2642 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2643 | PackageParser.PARSE_IS_SYSTEM_DIR; 2644 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2645 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2646 | PackageParser.PARSE_IS_SYSTEM_DIR; 2647 } else { 2648 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2649 continue; 2650 } 2651 2652 mSettings.enableSystemPackageLPw(packageName); 2653 2654 try { 2655 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2656 } catch (PackageManagerException e) { 2657 Slog.e(TAG, "Failed to parse original system package: " 2658 + e.getMessage()); 2659 } 2660 } 2661 } 2662 } 2663 mExpectingBetter.clear(); 2664 2665 // Resolve the storage manager. 2666 mStorageManagerPackage = getStorageManagerPackageName(); 2667 2668 // Resolve protected action filters. Only the setup wizard is allowed to 2669 // have a high priority filter for these actions. 2670 mSetupWizardPackage = getSetupWizardPackageName(); 2671 if (mProtectedFilters.size() > 0) { 2672 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2673 Slog.i(TAG, "No setup wizard;" 2674 + " All protected intents capped to priority 0"); 2675 } 2676 for (ActivityIntentInfo filter : mProtectedFilters) { 2677 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2678 if (DEBUG_FILTERS) { 2679 Slog.i(TAG, "Found setup wizard;" 2680 + " allow priority " + filter.getPriority() + ";" 2681 + " package: " + filter.activity.info.packageName 2682 + " activity: " + filter.activity.className 2683 + " priority: " + filter.getPriority()); 2684 } 2685 // skip setup wizard; allow it to keep the high priority filter 2686 continue; 2687 } 2688 Slog.w(TAG, "Protected action; cap priority to 0;" 2689 + " package: " + filter.activity.info.packageName 2690 + " activity: " + filter.activity.className 2691 + " origPrio: " + filter.getPriority()); 2692 filter.setPriority(0); 2693 } 2694 } 2695 mDeferProtectedFilters = false; 2696 mProtectedFilters.clear(); 2697 2698 // Now that we know all of the shared libraries, update all clients to have 2699 // the correct library paths. 2700 updateAllSharedLibrariesLPw(null); 2701 2702 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2703 // NOTE: We ignore potential failures here during a system scan (like 2704 // the rest of the commands above) because there's precious little we 2705 // can do about it. A settings error is reported, though. 2706 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2707 } 2708 2709 // Now that we know all the packages we are keeping, 2710 // read and update their last usage times. 2711 mPackageUsage.read(mPackages); 2712 mCompilerStats.read(); 2713 2714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2715 SystemClock.uptimeMillis()); 2716 Slog.i(TAG, "Time to scan packages: " 2717 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2718 + " seconds"); 2719 2720 // If the platform SDK has changed since the last time we booted, 2721 // we need to re-grant app permission to catch any new ones that 2722 // appear. This is really a hack, and means that apps can in some 2723 // cases get permissions that the user didn't initially explicitly 2724 // allow... it would be nice to have some better way to handle 2725 // this situation. 2726 int updateFlags = UPDATE_PERMISSIONS_ALL; 2727 if (ver.sdkVersion != mSdkVersion) { 2728 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2729 + mSdkVersion + "; regranting permissions for internal storage"); 2730 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2731 } 2732 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2733 ver.sdkVersion = mSdkVersion; 2734 2735 // If this is the first boot or an update from pre-M, and it is a normal 2736 // boot, then we need to initialize the default preferred apps across 2737 // all defined users. 2738 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2739 for (UserInfo user : sUserManager.getUsers(true)) { 2740 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2741 applyFactoryDefaultBrowserLPw(user.id); 2742 primeDomainVerificationsLPw(user.id); 2743 } 2744 } 2745 2746 // Prepare storage for system user really early during boot, 2747 // since core system apps like SettingsProvider and SystemUI 2748 // can't wait for user to start 2749 final int storageFlags; 2750 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2751 storageFlags = StorageManager.FLAG_STORAGE_DE; 2752 } else { 2753 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2754 } 2755 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2756 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2757 true /* onlyCoreApps */); 2758 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2759 if (deferPackages == null || deferPackages.isEmpty()) { 2760 return; 2761 } 2762 int count = 0; 2763 for (String pkgName : deferPackages) { 2764 PackageParser.Package pkg = null; 2765 synchronized (mPackages) { 2766 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2767 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2768 pkg = ps.pkg; 2769 } 2770 } 2771 if (pkg != null) { 2772 synchronized (mInstallLock) { 2773 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2774 true /* maybeMigrateAppData */); 2775 } 2776 count++; 2777 } 2778 } 2779 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2780 }, "prepareAppData"); 2781 2782 // If this is first boot after an OTA, and a normal boot, then 2783 // we need to clear code cache directories. 2784 // Note that we do *not* clear the application profiles. These remain valid 2785 // across OTAs and are used to drive profile verification (post OTA) and 2786 // profile compilation (without waiting to collect a fresh set of profiles). 2787 if (mIsUpgrade && !onlyCore) { 2788 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2789 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2790 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2791 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2792 // No apps are running this early, so no need to freeze 2793 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2794 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2795 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2796 } 2797 } 2798 ver.fingerprint = Build.FINGERPRINT; 2799 } 2800 2801 checkDefaultBrowser(); 2802 2803 // clear only after permissions and other defaults have been updated 2804 mExistingSystemPackages.clear(); 2805 mPromoteSystemApps = false; 2806 2807 // All the changes are done during package scanning. 2808 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2809 2810 // can downgrade to reader 2811 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2812 mSettings.writeLPr(); 2813 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2814 2815 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2816 // early on (before the package manager declares itself as early) because other 2817 // components in the system server might ask for package contexts for these apps. 2818 // 2819 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2820 // (i.e, that the data partition is unavailable). 2821 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2822 long start = System.nanoTime(); 2823 List<PackageParser.Package> coreApps = new ArrayList<>(); 2824 for (PackageParser.Package pkg : mPackages.values()) { 2825 if (pkg.coreApp) { 2826 coreApps.add(pkg); 2827 } 2828 } 2829 2830 int[] stats = performDexOptUpgrade(coreApps, false, 2831 getCompilerFilterForReason(REASON_CORE_APP)); 2832 2833 final int elapsedTimeSeconds = 2834 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2835 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2836 2837 if (DEBUG_DEXOPT) { 2838 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2839 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2840 } 2841 2842 2843 // TODO: Should we log these stats to tron too ? 2844 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2845 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2846 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2847 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2848 } 2849 2850 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2851 SystemClock.uptimeMillis()); 2852 2853 if (!mOnlyCore) { 2854 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2855 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2856 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2857 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2858 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2859 mIntentFilterVerifierComponent); 2860 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2861 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2862 SharedLibraryInfo.VERSION_UNDEFINED); 2863 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2864 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2865 SharedLibraryInfo.VERSION_UNDEFINED); 2866 } else { 2867 mRequiredVerifierPackage = null; 2868 mRequiredInstallerPackage = null; 2869 mRequiredUninstallerPackage = null; 2870 mIntentFilterVerifierComponent = null; 2871 mIntentFilterVerifier = null; 2872 mServicesSystemSharedLibraryPackageName = null; 2873 mSharedSystemSharedLibraryPackageName = null; 2874 } 2875 2876 mInstallerService = new PackageInstallerService(context, this); 2877 2878 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2879 if (ephemeralResolverComponent != null) { 2880 if (DEBUG_EPHEMERAL) { 2881 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2882 } 2883 mInstantAppResolverConnection = 2884 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2885 } else { 2886 mInstantAppResolverConnection = null; 2887 } 2888 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2889 if (mInstantAppInstallerComponent != null) { 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2892 } 2893 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2894 } 2895 2896 // Read and update the usage of dex files. 2897 // Do this at the end of PM init so that all the packages have their 2898 // data directory reconciled. 2899 // At this point we know the code paths of the packages, so we can validate 2900 // the disk file and build the internal cache. 2901 // The usage file is expected to be small so loading and verifying it 2902 // should take a fairly small time compare to the other activities (e.g. package 2903 // scanning). 2904 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2905 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2906 for (int userId : currentUserIds) { 2907 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2908 } 2909 mDexManager.load(userPackages); 2910 } // synchronized (mPackages) 2911 } // synchronized (mInstallLock) 2912 2913 // Now after opening every single application zip, make sure they 2914 // are all flushed. Not really needed, but keeps things nice and 2915 // tidy. 2916 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2917 Runtime.getRuntime().gc(); 2918 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2919 2920 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2921 FallbackCategoryProvider.loadFallbacks(); 2922 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2923 2924 // The initial scanning above does many calls into installd while 2925 // holding the mPackages lock, but we're mostly interested in yelling 2926 // once we have a booted system. 2927 mInstaller.setWarnIfHeld(mPackages); 2928 2929 // Expose private service for system components to use. 2930 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2931 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2932 } 2933 2934 private static File preparePackageParserCache(boolean isUpgrade) { 2935 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2936 return null; 2937 } 2938 2939 // Disable package parsing on eng builds to allow for faster incremental development. 2940 if ("eng".equals(Build.TYPE)) { 2941 return null; 2942 } 2943 2944 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2945 Slog.i(TAG, "Disabling package parser cache due to system property."); 2946 return null; 2947 } 2948 2949 // The base directory for the package parser cache lives under /data/system/. 2950 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2951 "package_cache"); 2952 if (cacheBaseDir == null) { 2953 return null; 2954 } 2955 2956 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2957 // This also serves to "GC" unused entries when the package cache version changes (which 2958 // can only happen during upgrades). 2959 if (isUpgrade) { 2960 FileUtils.deleteContents(cacheBaseDir); 2961 } 2962 2963 2964 // Return the versioned package cache directory. This is something like 2965 // "/data/system/package_cache/1" 2966 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2967 2968 // The following is a workaround to aid development on non-numbered userdebug 2969 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2970 // the system partition is newer. 2971 // 2972 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2973 // that starts with "eng." to signify that this is an engineering build and not 2974 // destined for release. 2975 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2976 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2977 2978 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2979 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2980 // in general and should not be used for production changes. In this specific case, 2981 // we know that they will work. 2982 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2983 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2984 FileUtils.deleteContents(cacheBaseDir); 2985 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2986 } 2987 } 2988 2989 return cacheDir; 2990 } 2991 2992 @Override 2993 public boolean isFirstBoot() { 2994 return mFirstBoot; 2995 } 2996 2997 @Override 2998 public boolean isOnlyCoreApps() { 2999 return mOnlyCore; 3000 } 3001 3002 @Override 3003 public boolean isUpgrade() { 3004 return mIsUpgrade; 3005 } 3006 3007 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3008 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3009 3010 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3011 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3012 UserHandle.USER_SYSTEM); 3013 if (matches.size() == 1) { 3014 return matches.get(0).getComponentInfo().packageName; 3015 } else if (matches.size() == 0) { 3016 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3017 return null; 3018 } 3019 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3020 } 3021 3022 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3023 synchronized (mPackages) { 3024 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3025 if (libraryEntry == null) { 3026 throw new IllegalStateException("Missing required shared library:" + name); 3027 } 3028 return libraryEntry.apk; 3029 } 3030 } 3031 3032 private @NonNull String getRequiredInstallerLPr() { 3033 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3034 intent.addCategory(Intent.CATEGORY_DEFAULT); 3035 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3036 3037 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3038 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3039 UserHandle.USER_SYSTEM); 3040 if (matches.size() == 1) { 3041 ResolveInfo resolveInfo = matches.get(0); 3042 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3043 throw new RuntimeException("The installer must be a privileged app"); 3044 } 3045 return matches.get(0).getComponentInfo().packageName; 3046 } else { 3047 throw new RuntimeException("There must be exactly one installer; found " + matches); 3048 } 3049 } 3050 3051 private @NonNull String getRequiredUninstallerLPr() { 3052 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3053 intent.addCategory(Intent.CATEGORY_DEFAULT); 3054 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3055 3056 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3057 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3058 UserHandle.USER_SYSTEM); 3059 if (resolveInfo == null || 3060 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3061 throw new RuntimeException("There must be exactly one uninstaller; found " 3062 + resolveInfo); 3063 } 3064 return resolveInfo.getComponentInfo().packageName; 3065 } 3066 3067 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3068 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3069 3070 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3071 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3072 UserHandle.USER_SYSTEM); 3073 ResolveInfo best = null; 3074 final int N = matches.size(); 3075 for (int i = 0; i < N; i++) { 3076 final ResolveInfo cur = matches.get(i); 3077 final String packageName = cur.getComponentInfo().packageName; 3078 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3079 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3080 continue; 3081 } 3082 3083 if (best == null || cur.priority > best.priority) { 3084 best = cur; 3085 } 3086 } 3087 3088 if (best != null) { 3089 return best.getComponentInfo().getComponentName(); 3090 } else { 3091 throw new RuntimeException("There must be at least one intent filter verifier"); 3092 } 3093 } 3094 3095 private @Nullable ComponentName getEphemeralResolverLPr() { 3096 final String[] packageArray = 3097 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3098 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3099 if (DEBUG_EPHEMERAL) { 3100 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3101 } 3102 return null; 3103 } 3104 3105 final int resolveFlags = 3106 MATCH_DIRECT_BOOT_AWARE 3107 | MATCH_DIRECT_BOOT_UNAWARE 3108 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3109 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3110 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3111 resolveFlags, UserHandle.USER_SYSTEM); 3112 3113 final int N = resolvers.size(); 3114 if (N == 0) { 3115 if (DEBUG_EPHEMERAL) { 3116 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3117 } 3118 return null; 3119 } 3120 3121 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3122 for (int i = 0; i < N; i++) { 3123 final ResolveInfo info = resolvers.get(i); 3124 3125 if (info.serviceInfo == null) { 3126 continue; 3127 } 3128 3129 final String packageName = info.serviceInfo.packageName; 3130 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3131 if (DEBUG_EPHEMERAL) { 3132 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3133 + " pkg: " + packageName + ", info:" + info); 3134 } 3135 continue; 3136 } 3137 3138 if (DEBUG_EPHEMERAL) { 3139 Slog.v(TAG, "Ephemeral resolver found;" 3140 + " pkg: " + packageName + ", info:" + info); 3141 } 3142 return new ComponentName(packageName, info.serviceInfo.name); 3143 } 3144 if (DEBUG_EPHEMERAL) { 3145 Slog.v(TAG, "Ephemeral resolver NOT found"); 3146 } 3147 return null; 3148 } 3149 3150 private @Nullable ComponentName getEphemeralInstallerLPr() { 3151 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3152 intent.addCategory(Intent.CATEGORY_DEFAULT); 3153 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3154 3155 final int resolveFlags = 3156 MATCH_DIRECT_BOOT_AWARE 3157 | MATCH_DIRECT_BOOT_UNAWARE 3158 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3159 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3160 resolveFlags, UserHandle.USER_SYSTEM); 3161 Iterator<ResolveInfo> iter = matches.iterator(); 3162 while (iter.hasNext()) { 3163 final ResolveInfo rInfo = iter.next(); 3164 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3165 if (ps != null) { 3166 final PermissionsState permissionsState = ps.getPermissionsState(); 3167 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3168 continue; 3169 } 3170 } 3171 iter.remove(); 3172 } 3173 if (matches.size() == 0) { 3174 return null; 3175 } else if (matches.size() == 1) { 3176 return matches.get(0).getComponentInfo().getComponentName(); 3177 } else { 3178 throw new RuntimeException( 3179 "There must be at most one ephemeral installer; found " + matches); 3180 } 3181 } 3182 3183 private void primeDomainVerificationsLPw(int userId) { 3184 if (DEBUG_DOMAIN_VERIFICATION) { 3185 Slog.d(TAG, "Priming domain verifications in user " + userId); 3186 } 3187 3188 SystemConfig systemConfig = SystemConfig.getInstance(); 3189 ArraySet<String> packages = systemConfig.getLinkedApps(); 3190 3191 for (String packageName : packages) { 3192 PackageParser.Package pkg = mPackages.get(packageName); 3193 if (pkg != null) { 3194 if (!pkg.isSystemApp()) { 3195 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3196 continue; 3197 } 3198 3199 ArraySet<String> domains = null; 3200 for (PackageParser.Activity a : pkg.activities) { 3201 for (ActivityIntentInfo filter : a.intents) { 3202 if (hasValidDomains(filter)) { 3203 if (domains == null) { 3204 domains = new ArraySet<String>(); 3205 } 3206 domains.addAll(filter.getHostsList()); 3207 } 3208 } 3209 } 3210 3211 if (domains != null && domains.size() > 0) { 3212 if (DEBUG_DOMAIN_VERIFICATION) { 3213 Slog.v(TAG, " + " + packageName); 3214 } 3215 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3216 // state w.r.t. the formal app-linkage "no verification attempted" state; 3217 // and then 'always' in the per-user state actually used for intent resolution. 3218 final IntentFilterVerificationInfo ivi; 3219 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3220 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3221 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3222 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3223 } else { 3224 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3225 + "' does not handle web links"); 3226 } 3227 } else { 3228 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3229 } 3230 } 3231 3232 scheduleWritePackageRestrictionsLocked(userId); 3233 scheduleWriteSettingsLocked(); 3234 } 3235 3236 private void applyFactoryDefaultBrowserLPw(int userId) { 3237 // The default browser app's package name is stored in a string resource, 3238 // with a product-specific overlay used for vendor customization. 3239 String browserPkg = mContext.getResources().getString( 3240 com.android.internal.R.string.default_browser); 3241 if (!TextUtils.isEmpty(browserPkg)) { 3242 // non-empty string => required to be a known package 3243 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3244 if (ps == null) { 3245 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3246 browserPkg = null; 3247 } else { 3248 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3249 } 3250 } 3251 3252 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3253 // default. If there's more than one, just leave everything alone. 3254 if (browserPkg == null) { 3255 calculateDefaultBrowserLPw(userId); 3256 } 3257 } 3258 3259 private void calculateDefaultBrowserLPw(int userId) { 3260 List<String> allBrowsers = resolveAllBrowserApps(userId); 3261 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3262 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3263 } 3264 3265 private List<String> resolveAllBrowserApps(int userId) { 3266 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3267 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3268 PackageManager.MATCH_ALL, userId); 3269 3270 final int count = list.size(); 3271 List<String> result = new ArrayList<String>(count); 3272 for (int i=0; i<count; i++) { 3273 ResolveInfo info = list.get(i); 3274 if (info.activityInfo == null 3275 || !info.handleAllWebDataURI 3276 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3277 || result.contains(info.activityInfo.packageName)) { 3278 continue; 3279 } 3280 result.add(info.activityInfo.packageName); 3281 } 3282 3283 return result; 3284 } 3285 3286 private boolean packageIsBrowser(String packageName, int userId) { 3287 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3288 PackageManager.MATCH_ALL, userId); 3289 final int N = list.size(); 3290 for (int i = 0; i < N; i++) { 3291 ResolveInfo info = list.get(i); 3292 if (packageName.equals(info.activityInfo.packageName)) { 3293 return true; 3294 } 3295 } 3296 return false; 3297 } 3298 3299 private void checkDefaultBrowser() { 3300 final int myUserId = UserHandle.myUserId(); 3301 final String packageName = getDefaultBrowserPackageName(myUserId); 3302 if (packageName != null) { 3303 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3304 if (info == null) { 3305 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3306 synchronized (mPackages) { 3307 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3308 } 3309 } 3310 } 3311 } 3312 3313 @Override 3314 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3315 throws RemoteException { 3316 try { 3317 return super.onTransact(code, data, reply, flags); 3318 } catch (RuntimeException e) { 3319 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3320 Slog.wtf(TAG, "Package Manager Crash", e); 3321 } 3322 throw e; 3323 } 3324 } 3325 3326 static int[] appendInts(int[] cur, int[] add) { 3327 if (add == null) return cur; 3328 if (cur == null) return add; 3329 final int N = add.length; 3330 for (int i=0; i<N; i++) { 3331 cur = appendInt(cur, add[i]); 3332 } 3333 return cur; 3334 } 3335 3336 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3337 if (!sUserManager.exists(userId)) return null; 3338 if (ps == null) { 3339 return null; 3340 } 3341 final PackageParser.Package p = ps.pkg; 3342 if (p == null) { 3343 return null; 3344 } 3345 // Filter out ephemeral app metadata: 3346 // * The system/shell/root can see metadata for any app 3347 // * An installed app can see metadata for 1) other installed apps 3348 // and 2) ephemeral apps that have explicitly interacted with it 3349 // * Ephemeral apps can only see their own metadata 3350 // * Holding a signature permission allows seeing instant apps 3351 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3352 if (callingAppId != Process.SYSTEM_UID 3353 && callingAppId != Process.SHELL_UID 3354 && callingAppId != Process.ROOT_UID 3355 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3356 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3357 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3358 if (instantAppPackageName != null) { 3359 // ephemeral apps can only get information on themselves 3360 if (!instantAppPackageName.equals(p.packageName)) { 3361 return null; 3362 } 3363 } else { 3364 if (ps.getInstantApp(userId)) { 3365 // only get access to the ephemeral app if we've been granted access 3366 if (!mInstantAppRegistry.isInstantAccessGranted( 3367 userId, callingAppId, ps.appId)) { 3368 return null; 3369 } 3370 } 3371 } 3372 } 3373 3374 final PermissionsState permissionsState = ps.getPermissionsState(); 3375 3376 // Compute GIDs only if requested 3377 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3378 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3379 // Compute granted permissions only if package has requested permissions 3380 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3381 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3382 final PackageUserState state = ps.readUserState(userId); 3383 3384 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3385 && ps.isSystem()) { 3386 flags |= MATCH_ANY_USER; 3387 } 3388 3389 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3390 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3391 3392 if (packageInfo == null) { 3393 return null; 3394 } 3395 3396 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3397 3398 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3399 resolveExternalPackageNameLPr(p); 3400 3401 return packageInfo; 3402 } 3403 3404 @Override 3405 public void checkPackageStartable(String packageName, int userId) { 3406 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3407 3408 synchronized (mPackages) { 3409 final PackageSetting ps = mSettings.mPackages.get(packageName); 3410 if (ps == null) { 3411 throw new SecurityException("Package " + packageName + " was not found!"); 3412 } 3413 3414 if (!ps.getInstalled(userId)) { 3415 throw new SecurityException( 3416 "Package " + packageName + " was not installed for user " + userId + "!"); 3417 } 3418 3419 if (mSafeMode && !ps.isSystem()) { 3420 throw new SecurityException("Package " + packageName + " not a system app!"); 3421 } 3422 3423 if (mFrozenPackages.contains(packageName)) { 3424 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3425 } 3426 3427 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3428 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3429 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3430 } 3431 } 3432 } 3433 3434 @Override 3435 public boolean isPackageAvailable(String packageName, int userId) { 3436 if (!sUserManager.exists(userId)) return false; 3437 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3438 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3439 synchronized (mPackages) { 3440 PackageParser.Package p = mPackages.get(packageName); 3441 if (p != null) { 3442 final PackageSetting ps = (PackageSetting) p.mExtras; 3443 if (ps != null) { 3444 final PackageUserState state = ps.readUserState(userId); 3445 if (state != null) { 3446 return PackageParser.isAvailable(state); 3447 } 3448 } 3449 } 3450 } 3451 return false; 3452 } 3453 3454 @Override 3455 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3456 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3457 flags, userId); 3458 } 3459 3460 @Override 3461 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3462 int flags, int userId) { 3463 return getPackageInfoInternal(versionedPackage.getPackageName(), 3464 // TODO: We will change version code to long, so in the new API it is long 3465 (int) versionedPackage.getVersionCode(), flags, userId); 3466 } 3467 3468 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3469 int flags, int userId) { 3470 if (!sUserManager.exists(userId)) return null; 3471 flags = updateFlagsForPackage(flags, userId, packageName); 3472 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3473 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3474 3475 // reader 3476 synchronized (mPackages) { 3477 // Normalize package name to handle renamed packages and static libs 3478 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3479 3480 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3481 if (matchFactoryOnly) { 3482 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3483 if (ps != null) { 3484 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3485 return null; 3486 } 3487 return generatePackageInfo(ps, flags, userId); 3488 } 3489 } 3490 3491 PackageParser.Package p = mPackages.get(packageName); 3492 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3493 return null; 3494 } 3495 if (DEBUG_PACKAGE_INFO) 3496 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3497 if (p != null) { 3498 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3499 Binder.getCallingUid(), userId)) { 3500 return null; 3501 } 3502 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3503 } 3504 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3505 final PackageSetting ps = mSettings.mPackages.get(packageName); 3506 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3507 return null; 3508 } 3509 return generatePackageInfo(ps, flags, userId); 3510 } 3511 } 3512 return null; 3513 } 3514 3515 3516 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3517 // System/shell/root get to see all static libs 3518 final int appId = UserHandle.getAppId(uid); 3519 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3520 || appId == Process.ROOT_UID) { 3521 return false; 3522 } 3523 3524 // No package means no static lib as it is always on internal storage 3525 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3526 return false; 3527 } 3528 3529 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3530 ps.pkg.staticSharedLibVersion); 3531 if (libEntry == null) { 3532 return false; 3533 } 3534 3535 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3536 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3537 if (uidPackageNames == null) { 3538 return true; 3539 } 3540 3541 for (String uidPackageName : uidPackageNames) { 3542 if (ps.name.equals(uidPackageName)) { 3543 return false; 3544 } 3545 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3546 if (uidPs != null) { 3547 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3548 libEntry.info.getName()); 3549 if (index < 0) { 3550 continue; 3551 } 3552 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3553 return false; 3554 } 3555 } 3556 } 3557 return true; 3558 } 3559 3560 @Override 3561 public String[] currentToCanonicalPackageNames(String[] names) { 3562 String[] out = new String[names.length]; 3563 // reader 3564 synchronized (mPackages) { 3565 for (int i=names.length-1; i>=0; i--) { 3566 PackageSetting ps = mSettings.mPackages.get(names[i]); 3567 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3568 } 3569 } 3570 return out; 3571 } 3572 3573 @Override 3574 public String[] canonicalToCurrentPackageNames(String[] names) { 3575 String[] out = new String[names.length]; 3576 // reader 3577 synchronized (mPackages) { 3578 for (int i=names.length-1; i>=0; i--) { 3579 String cur = mSettings.getRenamedPackageLPr(names[i]); 3580 out[i] = cur != null ? cur : names[i]; 3581 } 3582 } 3583 return out; 3584 } 3585 3586 @Override 3587 public int getPackageUid(String packageName, int flags, int userId) { 3588 if (!sUserManager.exists(userId)) return -1; 3589 flags = updateFlagsForPackage(flags, userId, packageName); 3590 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3591 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3592 3593 // reader 3594 synchronized (mPackages) { 3595 final PackageParser.Package p = mPackages.get(packageName); 3596 if (p != null && p.isMatch(flags)) { 3597 return UserHandle.getUid(userId, p.applicationInfo.uid); 3598 } 3599 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3600 final PackageSetting ps = mSettings.mPackages.get(packageName); 3601 if (ps != null && ps.isMatch(flags)) { 3602 return UserHandle.getUid(userId, ps.appId); 3603 } 3604 } 3605 } 3606 3607 return -1; 3608 } 3609 3610 @Override 3611 public int[] getPackageGids(String packageName, int flags, int userId) { 3612 if (!sUserManager.exists(userId)) return null; 3613 flags = updateFlagsForPackage(flags, userId, packageName); 3614 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3615 false /* requireFullPermission */, false /* checkShell */, 3616 "getPackageGids"); 3617 3618 // reader 3619 synchronized (mPackages) { 3620 final PackageParser.Package p = mPackages.get(packageName); 3621 if (p != null && p.isMatch(flags)) { 3622 PackageSetting ps = (PackageSetting) p.mExtras; 3623 // TODO: Shouldn't this be checking for package installed state for userId and 3624 // return null? 3625 return ps.getPermissionsState().computeGids(userId); 3626 } 3627 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3628 final PackageSetting ps = mSettings.mPackages.get(packageName); 3629 if (ps != null && ps.isMatch(flags)) { 3630 return ps.getPermissionsState().computeGids(userId); 3631 } 3632 } 3633 } 3634 3635 return null; 3636 } 3637 3638 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3639 if (bp.perm != null) { 3640 return PackageParser.generatePermissionInfo(bp.perm, flags); 3641 } 3642 PermissionInfo pi = new PermissionInfo(); 3643 pi.name = bp.name; 3644 pi.packageName = bp.sourcePackage; 3645 pi.nonLocalizedLabel = bp.name; 3646 pi.protectionLevel = bp.protectionLevel; 3647 return pi; 3648 } 3649 3650 @Override 3651 public PermissionInfo getPermissionInfo(String name, int flags) { 3652 // reader 3653 synchronized (mPackages) { 3654 final BasePermission p = mSettings.mPermissions.get(name); 3655 if (p != null) { 3656 return generatePermissionInfo(p, flags); 3657 } 3658 return null; 3659 } 3660 } 3661 3662 @Override 3663 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3664 int flags) { 3665 // reader 3666 synchronized (mPackages) { 3667 if (group != null && !mPermissionGroups.containsKey(group)) { 3668 // This is thrown as NameNotFoundException 3669 return null; 3670 } 3671 3672 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3673 for (BasePermission p : mSettings.mPermissions.values()) { 3674 if (group == null) { 3675 if (p.perm == null || p.perm.info.group == null) { 3676 out.add(generatePermissionInfo(p, flags)); 3677 } 3678 } else { 3679 if (p.perm != null && group.equals(p.perm.info.group)) { 3680 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3681 } 3682 } 3683 } 3684 return new ParceledListSlice<>(out); 3685 } 3686 } 3687 3688 @Override 3689 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3690 // reader 3691 synchronized (mPackages) { 3692 return PackageParser.generatePermissionGroupInfo( 3693 mPermissionGroups.get(name), flags); 3694 } 3695 } 3696 3697 @Override 3698 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3699 // reader 3700 synchronized (mPackages) { 3701 final int N = mPermissionGroups.size(); 3702 ArrayList<PermissionGroupInfo> out 3703 = new ArrayList<PermissionGroupInfo>(N); 3704 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3705 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3706 } 3707 return new ParceledListSlice<>(out); 3708 } 3709 } 3710 3711 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3712 int uid, int userId) { 3713 if (!sUserManager.exists(userId)) return null; 3714 PackageSetting ps = mSettings.mPackages.get(packageName); 3715 if (ps != null) { 3716 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3717 return null; 3718 } 3719 if (ps.pkg == null) { 3720 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3721 if (pInfo != null) { 3722 return pInfo.applicationInfo; 3723 } 3724 return null; 3725 } 3726 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3727 ps.readUserState(userId), userId); 3728 if (ai != null) { 3729 rebaseEnabledOverlays(ai, userId); 3730 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3731 } 3732 return ai; 3733 } 3734 return null; 3735 } 3736 3737 @Override 3738 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3739 if (!sUserManager.exists(userId)) return null; 3740 flags = updateFlagsForApplication(flags, userId, packageName); 3741 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3742 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3743 3744 // writer 3745 synchronized (mPackages) { 3746 // Normalize package name to handle renamed packages and static libs 3747 packageName = resolveInternalPackageNameLPr(packageName, 3748 PackageManager.VERSION_CODE_HIGHEST); 3749 3750 PackageParser.Package p = mPackages.get(packageName); 3751 if (DEBUG_PACKAGE_INFO) Log.v( 3752 TAG, "getApplicationInfo " + packageName 3753 + ": " + p); 3754 if (p != null) { 3755 PackageSetting ps = mSettings.mPackages.get(packageName); 3756 if (ps == null) return null; 3757 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3758 return null; 3759 } 3760 // Note: isEnabledLP() does not apply here - always return info 3761 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3762 p, flags, ps.readUserState(userId), userId); 3763 if (ai != null) { 3764 rebaseEnabledOverlays(ai, userId); 3765 ai.packageName = resolveExternalPackageNameLPr(p); 3766 } 3767 return ai; 3768 } 3769 if ("android".equals(packageName)||"system".equals(packageName)) { 3770 return mAndroidApplication; 3771 } 3772 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3773 // Already generates the external package name 3774 return generateApplicationInfoFromSettingsLPw(packageName, 3775 Binder.getCallingUid(), flags, userId); 3776 } 3777 } 3778 return null; 3779 } 3780 3781 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3782 List<String> paths = new ArrayList<>(); 3783 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3784 mEnabledOverlayPaths.get(userId); 3785 if (userSpecificOverlays != null) { 3786 if (!"android".equals(ai.packageName)) { 3787 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3788 if (frameworkOverlays != null) { 3789 paths.addAll(frameworkOverlays); 3790 } 3791 } 3792 3793 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3794 if (appOverlays != null) { 3795 paths.addAll(appOverlays); 3796 } 3797 } 3798 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3799 } 3800 3801 private String normalizePackageNameLPr(String packageName) { 3802 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3803 return normalizedPackageName != null ? normalizedPackageName : packageName; 3804 } 3805 3806 @Override 3807 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3808 final IPackageDataObserver observer) { 3809 mContext.enforceCallingOrSelfPermission( 3810 android.Manifest.permission.CLEAR_APP_CACHE, null); 3811 mHandler.post(() -> { 3812 boolean success = false; 3813 try { 3814 freeStorage(volumeUuid, freeStorageSize, 0); 3815 success = true; 3816 } catch (IOException e) { 3817 Slog.w(TAG, e); 3818 } 3819 if (observer != null) { 3820 try { 3821 observer.onRemoveCompleted(null, success); 3822 } catch (RemoteException e) { 3823 Slog.w(TAG, e); 3824 } 3825 } 3826 }); 3827 } 3828 3829 @Override 3830 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3831 final IntentSender pi) { 3832 mContext.enforceCallingOrSelfPermission( 3833 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3834 mHandler.post(() -> { 3835 boolean success = false; 3836 try { 3837 freeStorage(volumeUuid, freeStorageSize, 0); 3838 success = true; 3839 } catch (IOException e) { 3840 Slog.w(TAG, e); 3841 } 3842 if (pi != null) { 3843 try { 3844 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3845 } catch (SendIntentException e) { 3846 Slog.w(TAG, e); 3847 } 3848 } 3849 }); 3850 } 3851 3852 /** 3853 * Blocking call to clear various types of cached data across the system 3854 * until the requested bytes are available. 3855 */ 3856 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3857 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3858 final File file = storage.findPathForUuid(volumeUuid); 3859 3860 if (ENABLE_FREE_CACHE_V2) { 3861 final boolean aggressive = (storageFlags 3862 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3863 3864 // 1. Pre-flight to determine if we have any chance to succeed 3865 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3866 3867 // 3. Consider parsed APK data (aggressive only) 3868 if (aggressive) { 3869 FileUtils.deleteContents(mCacheDir); 3870 } 3871 if (file.getUsableSpace() >= bytes) return; 3872 3873 // 4. Consider cached app data (above quotas) 3874 try { 3875 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3876 } catch (InstallerException ignored) { 3877 } 3878 if (file.getUsableSpace() >= bytes) return; 3879 3880 // 5. Consider shared libraries with refcount=0 and age>2h 3881 // 6. Consider dexopt output (aggressive only) 3882 // 7. Consider ephemeral apps not used in last week 3883 3884 // 8. Consider cached app data (below quotas) 3885 try { 3886 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3887 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3888 } catch (InstallerException ignored) { 3889 } 3890 if (file.getUsableSpace() >= bytes) return; 3891 3892 // 9. Consider DropBox entries 3893 // 10. Consider ephemeral cookies 3894 3895 } else { 3896 try { 3897 mInstaller.freeCache(volumeUuid, bytes, 0); 3898 } catch (InstallerException ignored) { 3899 } 3900 if (file.getUsableSpace() >= bytes) return; 3901 } 3902 3903 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3904 } 3905 3906 /** 3907 * Update given flags based on encryption status of current user. 3908 */ 3909 private int updateFlags(int flags, int userId) { 3910 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3911 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3912 // Caller expressed an explicit opinion about what encryption 3913 // aware/unaware components they want to see, so fall through and 3914 // give them what they want 3915 } else { 3916 // Caller expressed no opinion, so match based on user state 3917 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3918 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3919 } else { 3920 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3921 } 3922 } 3923 return flags; 3924 } 3925 3926 private UserManagerInternal getUserManagerInternal() { 3927 if (mUserManagerInternal == null) { 3928 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3929 } 3930 return mUserManagerInternal; 3931 } 3932 3933 private DeviceIdleController.LocalService getDeviceIdleController() { 3934 if (mDeviceIdleController == null) { 3935 mDeviceIdleController = 3936 LocalServices.getService(DeviceIdleController.LocalService.class); 3937 } 3938 return mDeviceIdleController; 3939 } 3940 3941 /** 3942 * Update given flags when being used to request {@link PackageInfo}. 3943 */ 3944 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3945 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3946 boolean triaged = true; 3947 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3948 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3949 // Caller is asking for component details, so they'd better be 3950 // asking for specific encryption matching behavior, or be triaged 3951 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3952 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3953 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3954 triaged = false; 3955 } 3956 } 3957 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3958 | PackageManager.MATCH_SYSTEM_ONLY 3959 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3960 triaged = false; 3961 } 3962 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3963 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3964 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3965 + Debug.getCallers(5)); 3966 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3967 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3968 // If the caller wants all packages and has a restricted profile associated with it, 3969 // then match all users. This is to make sure that launchers that need to access work 3970 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3971 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3972 flags |= PackageManager.MATCH_ANY_USER; 3973 } 3974 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3975 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3976 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3977 } 3978 return updateFlags(flags, userId); 3979 } 3980 3981 /** 3982 * Update given flags when being used to request {@link ApplicationInfo}. 3983 */ 3984 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3985 return updateFlagsForPackage(flags, userId, cookie); 3986 } 3987 3988 /** 3989 * Update given flags when being used to request {@link ComponentInfo}. 3990 */ 3991 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3992 if (cookie instanceof Intent) { 3993 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3994 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3995 } 3996 } 3997 3998 boolean triaged = true; 3999 // Caller is asking for component details, so they'd better be 4000 // asking for specific encryption matching behavior, or be triaged 4001 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4002 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4003 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4004 triaged = false; 4005 } 4006 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4007 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4008 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4009 } 4010 4011 return updateFlags(flags, userId); 4012 } 4013 4014 /** 4015 * Update given intent when being used to request {@link ResolveInfo}. 4016 */ 4017 private Intent updateIntentForResolve(Intent intent) { 4018 if (intent.getSelector() != null) { 4019 intent = intent.getSelector(); 4020 } 4021 if (DEBUG_PREFERRED) { 4022 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4023 } 4024 return intent; 4025 } 4026 4027 /** 4028 * Update given flags when being used to request {@link ResolveInfo}. 4029 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4030 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4031 * flag set. However, this flag is only honoured in three circumstances: 4032 * <ul> 4033 * <li>when called from a system process</li> 4034 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4035 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4036 * action and a {@code android.intent.category.BROWSABLE} category</li> 4037 * </ul> 4038 */ 4039 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4040 // Safe mode means we shouldn't match any third-party components 4041 if (mSafeMode) { 4042 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4043 } 4044 final int callingUid = Binder.getCallingUid(); 4045 if (getInstantAppPackageName(callingUid) != null) { 4046 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4047 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4048 flags |= PackageManager.MATCH_INSTANT; 4049 } else { 4050 // Otherwise, prevent leaking ephemeral components 4051 final boolean isSpecialProcess = 4052 callingUid == Process.SYSTEM_UID 4053 || callingUid == Process.SHELL_UID 4054 || callingUid == 0; 4055 final boolean allowMatchInstant = 4056 (includeInstantApp 4057 && Intent.ACTION_VIEW.equals(intent.getAction()) 4058 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4059 && hasWebURI(intent)) 4060 || isSpecialProcess 4061 || mContext.checkCallingOrSelfPermission( 4062 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4063 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4064 if (!allowMatchInstant) { 4065 flags &= ~PackageManager.MATCH_INSTANT; 4066 } 4067 } 4068 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4069 } 4070 4071 @Override 4072 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4073 if (!sUserManager.exists(userId)) return null; 4074 flags = updateFlagsForComponent(flags, userId, component); 4075 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4076 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4077 synchronized (mPackages) { 4078 PackageParser.Activity a = mActivities.mActivities.get(component); 4079 4080 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4081 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4082 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4083 if (ps == null) return null; 4084 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4085 userId); 4086 } 4087 if (mResolveComponentName.equals(component)) { 4088 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4089 new PackageUserState(), userId); 4090 } 4091 } 4092 return null; 4093 } 4094 4095 @Override 4096 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4097 String resolvedType) { 4098 synchronized (mPackages) { 4099 if (component.equals(mResolveComponentName)) { 4100 // The resolver supports EVERYTHING! 4101 return true; 4102 } 4103 PackageParser.Activity a = mActivities.mActivities.get(component); 4104 if (a == null) { 4105 return false; 4106 } 4107 for (int i=0; i<a.intents.size(); i++) { 4108 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4109 intent.getData(), intent.getCategories(), TAG) >= 0) { 4110 return true; 4111 } 4112 } 4113 return false; 4114 } 4115 } 4116 4117 @Override 4118 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4119 if (!sUserManager.exists(userId)) return null; 4120 flags = updateFlagsForComponent(flags, userId, component); 4121 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4122 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4123 synchronized (mPackages) { 4124 PackageParser.Activity a = mReceivers.mActivities.get(component); 4125 if (DEBUG_PACKAGE_INFO) Log.v( 4126 TAG, "getReceiverInfo " + component + ": " + a); 4127 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4128 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4129 if (ps == null) return null; 4130 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4131 ps.readUserState(userId), userId); 4132 if (ri != null) { 4133 rebaseEnabledOverlays(ri.applicationInfo, userId); 4134 } 4135 return ri; 4136 } 4137 } 4138 return null; 4139 } 4140 4141 @Override 4142 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4143 if (!sUserManager.exists(userId)) return null; 4144 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4145 4146 flags = updateFlagsForPackage(flags, userId, null); 4147 4148 final boolean canSeeStaticLibraries = 4149 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4150 == PERMISSION_GRANTED 4151 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4152 == PERMISSION_GRANTED 4153 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4154 == PERMISSION_GRANTED 4155 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4156 == PERMISSION_GRANTED; 4157 4158 synchronized (mPackages) { 4159 List<SharedLibraryInfo> result = null; 4160 4161 final int libCount = mSharedLibraries.size(); 4162 for (int i = 0; i < libCount; i++) { 4163 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4164 if (versionedLib == null) { 4165 continue; 4166 } 4167 4168 final int versionCount = versionedLib.size(); 4169 for (int j = 0; j < versionCount; j++) { 4170 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4171 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4172 break; 4173 } 4174 final long identity = Binder.clearCallingIdentity(); 4175 try { 4176 // TODO: We will change version code to long, so in the new API it is long 4177 PackageInfo packageInfo = getPackageInfoVersioned( 4178 libInfo.getDeclaringPackage(), flags, userId); 4179 if (packageInfo == null) { 4180 continue; 4181 } 4182 } finally { 4183 Binder.restoreCallingIdentity(identity); 4184 } 4185 4186 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4187 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4188 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4189 4190 if (result == null) { 4191 result = new ArrayList<>(); 4192 } 4193 result.add(resLibInfo); 4194 } 4195 } 4196 4197 return result != null ? new ParceledListSlice<>(result) : null; 4198 } 4199 } 4200 4201 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4202 SharedLibraryInfo libInfo, int flags, int userId) { 4203 List<VersionedPackage> versionedPackages = null; 4204 final int packageCount = mSettings.mPackages.size(); 4205 for (int i = 0; i < packageCount; i++) { 4206 PackageSetting ps = mSettings.mPackages.valueAt(i); 4207 4208 if (ps == null) { 4209 continue; 4210 } 4211 4212 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4213 continue; 4214 } 4215 4216 final String libName = libInfo.getName(); 4217 if (libInfo.isStatic()) { 4218 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4219 if (libIdx < 0) { 4220 continue; 4221 } 4222 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4223 continue; 4224 } 4225 if (versionedPackages == null) { 4226 versionedPackages = new ArrayList<>(); 4227 } 4228 // If the dependent is a static shared lib, use the public package name 4229 String dependentPackageName = ps.name; 4230 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4231 dependentPackageName = ps.pkg.manifestPackageName; 4232 } 4233 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4234 } else if (ps.pkg != null) { 4235 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4236 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4237 if (versionedPackages == null) { 4238 versionedPackages = new ArrayList<>(); 4239 } 4240 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4241 } 4242 } 4243 } 4244 4245 return versionedPackages; 4246 } 4247 4248 @Override 4249 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4250 if (!sUserManager.exists(userId)) return null; 4251 flags = updateFlagsForComponent(flags, userId, component); 4252 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4253 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4254 synchronized (mPackages) { 4255 PackageParser.Service s = mServices.mServices.get(component); 4256 if (DEBUG_PACKAGE_INFO) Log.v( 4257 TAG, "getServiceInfo " + component + ": " + s); 4258 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4259 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4260 if (ps == null) return null; 4261 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4262 ps.readUserState(userId), userId); 4263 if (si != null) { 4264 rebaseEnabledOverlays(si.applicationInfo, userId); 4265 } 4266 return si; 4267 } 4268 } 4269 return null; 4270 } 4271 4272 @Override 4273 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4274 if (!sUserManager.exists(userId)) return null; 4275 flags = updateFlagsForComponent(flags, userId, component); 4276 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4277 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4278 synchronized (mPackages) { 4279 PackageParser.Provider p = mProviders.mProviders.get(component); 4280 if (DEBUG_PACKAGE_INFO) Log.v( 4281 TAG, "getProviderInfo " + component + ": " + p); 4282 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4283 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4284 if (ps == null) return null; 4285 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4286 ps.readUserState(userId), userId); 4287 if (pi != null) { 4288 rebaseEnabledOverlays(pi.applicationInfo, userId); 4289 } 4290 return pi; 4291 } 4292 } 4293 return null; 4294 } 4295 4296 @Override 4297 public String[] getSystemSharedLibraryNames() { 4298 synchronized (mPackages) { 4299 Set<String> libs = null; 4300 final int libCount = mSharedLibraries.size(); 4301 for (int i = 0; i < libCount; i++) { 4302 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4303 if (versionedLib == null) { 4304 continue; 4305 } 4306 final int versionCount = versionedLib.size(); 4307 for (int j = 0; j < versionCount; j++) { 4308 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4309 if (!libEntry.info.isStatic()) { 4310 if (libs == null) { 4311 libs = new ArraySet<>(); 4312 } 4313 libs.add(libEntry.info.getName()); 4314 break; 4315 } 4316 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4317 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4318 UserHandle.getUserId(Binder.getCallingUid()))) { 4319 if (libs == null) { 4320 libs = new ArraySet<>(); 4321 } 4322 libs.add(libEntry.info.getName()); 4323 break; 4324 } 4325 } 4326 } 4327 4328 if (libs != null) { 4329 String[] libsArray = new String[libs.size()]; 4330 libs.toArray(libsArray); 4331 return libsArray; 4332 } 4333 4334 return null; 4335 } 4336 } 4337 4338 @Override 4339 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4340 synchronized (mPackages) { 4341 return mServicesSystemSharedLibraryPackageName; 4342 } 4343 } 4344 4345 @Override 4346 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4347 synchronized (mPackages) { 4348 return mSharedSystemSharedLibraryPackageName; 4349 } 4350 } 4351 4352 private void updateSequenceNumberLP(String packageName, int[] userList) { 4353 for (int i = userList.length - 1; i >= 0; --i) { 4354 final int userId = userList[i]; 4355 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4356 if (changedPackages == null) { 4357 changedPackages = new SparseArray<>(); 4358 mChangedPackages.put(userId, changedPackages); 4359 } 4360 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4361 if (sequenceNumbers == null) { 4362 sequenceNumbers = new HashMap<>(); 4363 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4364 } 4365 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4366 if (sequenceNumber != null) { 4367 changedPackages.remove(sequenceNumber); 4368 } 4369 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4370 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4371 } 4372 mChangedPackagesSequenceNumber++; 4373 } 4374 4375 @Override 4376 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4377 synchronized (mPackages) { 4378 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4379 return null; 4380 } 4381 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4382 if (changedPackages == null) { 4383 return null; 4384 } 4385 final List<String> packageNames = 4386 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4387 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4388 final String packageName = changedPackages.get(i); 4389 if (packageName != null) { 4390 packageNames.add(packageName); 4391 } 4392 } 4393 return packageNames.isEmpty() 4394 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4395 } 4396 } 4397 4398 @Override 4399 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4400 ArrayList<FeatureInfo> res; 4401 synchronized (mAvailableFeatures) { 4402 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4403 res.addAll(mAvailableFeatures.values()); 4404 } 4405 final FeatureInfo fi = new FeatureInfo(); 4406 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4407 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4408 res.add(fi); 4409 4410 return new ParceledListSlice<>(res); 4411 } 4412 4413 @Override 4414 public boolean hasSystemFeature(String name, int version) { 4415 synchronized (mAvailableFeatures) { 4416 final FeatureInfo feat = mAvailableFeatures.get(name); 4417 if (feat == null) { 4418 return false; 4419 } else { 4420 return feat.version >= version; 4421 } 4422 } 4423 } 4424 4425 @Override 4426 public int checkPermission(String permName, String pkgName, int userId) { 4427 if (!sUserManager.exists(userId)) { 4428 return PackageManager.PERMISSION_DENIED; 4429 } 4430 4431 synchronized (mPackages) { 4432 final PackageParser.Package p = mPackages.get(pkgName); 4433 if (p != null && p.mExtras != null) { 4434 final PackageSetting ps = (PackageSetting) p.mExtras; 4435 final PermissionsState permissionsState = ps.getPermissionsState(); 4436 if (permissionsState.hasPermission(permName, userId)) { 4437 return PackageManager.PERMISSION_GRANTED; 4438 } 4439 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4440 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4441 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4442 return PackageManager.PERMISSION_GRANTED; 4443 } 4444 } 4445 } 4446 4447 return PackageManager.PERMISSION_DENIED; 4448 } 4449 4450 @Override 4451 public int checkUidPermission(String permName, int uid) { 4452 final int userId = UserHandle.getUserId(uid); 4453 4454 if (!sUserManager.exists(userId)) { 4455 return PackageManager.PERMISSION_DENIED; 4456 } 4457 4458 synchronized (mPackages) { 4459 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4460 if (obj != null) { 4461 final SettingBase ps = (SettingBase) obj; 4462 final PermissionsState permissionsState = ps.getPermissionsState(); 4463 if (permissionsState.hasPermission(permName, userId)) { 4464 return PackageManager.PERMISSION_GRANTED; 4465 } 4466 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4467 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4468 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4469 return PackageManager.PERMISSION_GRANTED; 4470 } 4471 } else { 4472 ArraySet<String> perms = mSystemPermissions.get(uid); 4473 if (perms != null) { 4474 if (perms.contains(permName)) { 4475 return PackageManager.PERMISSION_GRANTED; 4476 } 4477 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4478 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4479 return PackageManager.PERMISSION_GRANTED; 4480 } 4481 } 4482 } 4483 } 4484 4485 return PackageManager.PERMISSION_DENIED; 4486 } 4487 4488 @Override 4489 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4490 if (UserHandle.getCallingUserId() != userId) { 4491 mContext.enforceCallingPermission( 4492 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4493 "isPermissionRevokedByPolicy for user " + userId); 4494 } 4495 4496 if (checkPermission(permission, packageName, userId) 4497 == PackageManager.PERMISSION_GRANTED) { 4498 return false; 4499 } 4500 4501 final long identity = Binder.clearCallingIdentity(); 4502 try { 4503 final int flags = getPermissionFlags(permission, packageName, userId); 4504 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4505 } finally { 4506 Binder.restoreCallingIdentity(identity); 4507 } 4508 } 4509 4510 @Override 4511 public String getPermissionControllerPackageName() { 4512 synchronized (mPackages) { 4513 return mRequiredInstallerPackage; 4514 } 4515 } 4516 4517 /** 4518 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4519 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4520 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4521 * @param message the message to log on security exception 4522 */ 4523 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4524 boolean checkShell, String message) { 4525 if (userId < 0) { 4526 throw new IllegalArgumentException("Invalid userId " + userId); 4527 } 4528 if (checkShell) { 4529 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4530 } 4531 if (userId == UserHandle.getUserId(callingUid)) return; 4532 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4533 if (requireFullPermission) { 4534 mContext.enforceCallingOrSelfPermission( 4535 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4536 } else { 4537 try { 4538 mContext.enforceCallingOrSelfPermission( 4539 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4540 } catch (SecurityException se) { 4541 mContext.enforceCallingOrSelfPermission( 4542 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4543 } 4544 } 4545 } 4546 } 4547 4548 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4549 if (callingUid == Process.SHELL_UID) { 4550 if (userHandle >= 0 4551 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4552 throw new SecurityException("Shell does not have permission to access user " 4553 + userHandle); 4554 } else if (userHandle < 0) { 4555 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4556 + Debug.getCallers(3)); 4557 } 4558 } 4559 } 4560 4561 private BasePermission findPermissionTreeLP(String permName) { 4562 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4563 if (permName.startsWith(bp.name) && 4564 permName.length() > bp.name.length() && 4565 permName.charAt(bp.name.length()) == '.') { 4566 return bp; 4567 } 4568 } 4569 return null; 4570 } 4571 4572 private BasePermission checkPermissionTreeLP(String permName) { 4573 if (permName != null) { 4574 BasePermission bp = findPermissionTreeLP(permName); 4575 if (bp != null) { 4576 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4577 return bp; 4578 } 4579 throw new SecurityException("Calling uid " 4580 + Binder.getCallingUid() 4581 + " is not allowed to add to permission tree " 4582 + bp.name + " owned by uid " + bp.uid); 4583 } 4584 } 4585 throw new SecurityException("No permission tree found for " + permName); 4586 } 4587 4588 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4589 if (s1 == null) { 4590 return s2 == null; 4591 } 4592 if (s2 == null) { 4593 return false; 4594 } 4595 if (s1.getClass() != s2.getClass()) { 4596 return false; 4597 } 4598 return s1.equals(s2); 4599 } 4600 4601 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4602 if (pi1.icon != pi2.icon) return false; 4603 if (pi1.logo != pi2.logo) return false; 4604 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4605 if (!compareStrings(pi1.name, pi2.name)) return false; 4606 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4607 // We'll take care of setting this one. 4608 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4609 // These are not currently stored in settings. 4610 //if (!compareStrings(pi1.group, pi2.group)) return false; 4611 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4612 //if (pi1.labelRes != pi2.labelRes) return false; 4613 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4614 return true; 4615 } 4616 4617 int permissionInfoFootprint(PermissionInfo info) { 4618 int size = info.name.length(); 4619 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4620 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4621 return size; 4622 } 4623 4624 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4625 int size = 0; 4626 for (BasePermission perm : mSettings.mPermissions.values()) { 4627 if (perm.uid == tree.uid) { 4628 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4629 } 4630 } 4631 return size; 4632 } 4633 4634 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4635 // We calculate the max size of permissions defined by this uid and throw 4636 // if that plus the size of 'info' would exceed our stated maximum. 4637 if (tree.uid != Process.SYSTEM_UID) { 4638 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4639 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4640 throw new SecurityException("Permission tree size cap exceeded"); 4641 } 4642 } 4643 } 4644 4645 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4646 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4647 throw new SecurityException("Label must be specified in permission"); 4648 } 4649 BasePermission tree = checkPermissionTreeLP(info.name); 4650 BasePermission bp = mSettings.mPermissions.get(info.name); 4651 boolean added = bp == null; 4652 boolean changed = true; 4653 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4654 if (added) { 4655 enforcePermissionCapLocked(info, tree); 4656 bp = new BasePermission(info.name, tree.sourcePackage, 4657 BasePermission.TYPE_DYNAMIC); 4658 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4659 throw new SecurityException( 4660 "Not allowed to modify non-dynamic permission " 4661 + info.name); 4662 } else { 4663 if (bp.protectionLevel == fixedLevel 4664 && bp.perm.owner.equals(tree.perm.owner) 4665 && bp.uid == tree.uid 4666 && comparePermissionInfos(bp.perm.info, info)) { 4667 changed = false; 4668 } 4669 } 4670 bp.protectionLevel = fixedLevel; 4671 info = new PermissionInfo(info); 4672 info.protectionLevel = fixedLevel; 4673 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4674 bp.perm.info.packageName = tree.perm.info.packageName; 4675 bp.uid = tree.uid; 4676 if (added) { 4677 mSettings.mPermissions.put(info.name, bp); 4678 } 4679 if (changed) { 4680 if (!async) { 4681 mSettings.writeLPr(); 4682 } else { 4683 scheduleWriteSettingsLocked(); 4684 } 4685 } 4686 return added; 4687 } 4688 4689 @Override 4690 public boolean addPermission(PermissionInfo info) { 4691 synchronized (mPackages) { 4692 return addPermissionLocked(info, false); 4693 } 4694 } 4695 4696 @Override 4697 public boolean addPermissionAsync(PermissionInfo info) { 4698 synchronized (mPackages) { 4699 return addPermissionLocked(info, true); 4700 } 4701 } 4702 4703 @Override 4704 public void removePermission(String name) { 4705 synchronized (mPackages) { 4706 checkPermissionTreeLP(name); 4707 BasePermission bp = mSettings.mPermissions.get(name); 4708 if (bp != null) { 4709 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4710 throw new SecurityException( 4711 "Not allowed to modify non-dynamic permission " 4712 + name); 4713 } 4714 mSettings.mPermissions.remove(name); 4715 mSettings.writeLPr(); 4716 } 4717 } 4718 } 4719 4720 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4721 BasePermission bp) { 4722 int index = pkg.requestedPermissions.indexOf(bp.name); 4723 if (index == -1) { 4724 throw new SecurityException("Package " + pkg.packageName 4725 + " has not requested permission " + bp.name); 4726 } 4727 if (!bp.isRuntime() && !bp.isDevelopment()) { 4728 throw new SecurityException("Permission " + bp.name 4729 + " is not a changeable permission type"); 4730 } 4731 } 4732 4733 @Override 4734 public void grantRuntimePermission(String packageName, String name, final int userId) { 4735 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4736 } 4737 4738 private void grantRuntimePermission(String packageName, String name, final int userId, 4739 boolean overridePolicy) { 4740 if (!sUserManager.exists(userId)) { 4741 Log.e(TAG, "No such user:" + userId); 4742 return; 4743 } 4744 4745 mContext.enforceCallingOrSelfPermission( 4746 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4747 "grantRuntimePermission"); 4748 4749 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4750 true /* requireFullPermission */, true /* checkShell */, 4751 "grantRuntimePermission"); 4752 4753 final int uid; 4754 final SettingBase sb; 4755 4756 synchronized (mPackages) { 4757 final PackageParser.Package pkg = mPackages.get(packageName); 4758 if (pkg == null) { 4759 throw new IllegalArgumentException("Unknown package: " + packageName); 4760 } 4761 4762 final BasePermission bp = mSettings.mPermissions.get(name); 4763 if (bp == null) { 4764 throw new IllegalArgumentException("Unknown permission: " + name); 4765 } 4766 4767 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4768 4769 // If a permission review is required for legacy apps we represent 4770 // their permissions as always granted runtime ones since we need 4771 // to keep the review required permission flag per user while an 4772 // install permission's state is shared across all users. 4773 if (mPermissionReviewRequired 4774 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4775 && bp.isRuntime()) { 4776 return; 4777 } 4778 4779 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4780 sb = (SettingBase) pkg.mExtras; 4781 if (sb == null) { 4782 throw new IllegalArgumentException("Unknown package: " + packageName); 4783 } 4784 4785 final PermissionsState permissionsState = sb.getPermissionsState(); 4786 4787 final int flags = permissionsState.getPermissionFlags(name, userId); 4788 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4789 throw new SecurityException("Cannot grant system fixed permission " 4790 + name + " for package " + packageName); 4791 } 4792 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4793 throw new SecurityException("Cannot grant policy fixed permission " 4794 + name + " for package " + packageName); 4795 } 4796 4797 if (bp.isDevelopment()) { 4798 // Development permissions must be handled specially, since they are not 4799 // normal runtime permissions. For now they apply to all users. 4800 if (permissionsState.grantInstallPermission(bp) != 4801 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4802 scheduleWriteSettingsLocked(); 4803 } 4804 return; 4805 } 4806 4807 final PackageSetting ps = mSettings.mPackages.get(packageName); 4808 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4809 throw new SecurityException("Cannot grant non-ephemeral permission" 4810 + name + " for package " + packageName); 4811 } 4812 4813 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4814 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4815 return; 4816 } 4817 4818 final int result = permissionsState.grantRuntimePermission(bp, userId); 4819 switch (result) { 4820 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4821 return; 4822 } 4823 4824 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4825 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4826 mHandler.post(new Runnable() { 4827 @Override 4828 public void run() { 4829 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4830 } 4831 }); 4832 } 4833 break; 4834 } 4835 4836 if (bp.isRuntime()) { 4837 logPermissionGranted(mContext, name, packageName); 4838 } 4839 4840 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4841 4842 // Not critical if that is lost - app has to request again. 4843 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4844 } 4845 4846 // Only need to do this if user is initialized. Otherwise it's a new user 4847 // and there are no processes running as the user yet and there's no need 4848 // to make an expensive call to remount processes for the changed permissions. 4849 if (READ_EXTERNAL_STORAGE.equals(name) 4850 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4851 final long token = Binder.clearCallingIdentity(); 4852 try { 4853 if (sUserManager.isInitialized(userId)) { 4854 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4855 StorageManagerInternal.class); 4856 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4857 } 4858 } finally { 4859 Binder.restoreCallingIdentity(token); 4860 } 4861 } 4862 } 4863 4864 @Override 4865 public void revokeRuntimePermission(String packageName, String name, int userId) { 4866 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4867 } 4868 4869 private void revokeRuntimePermission(String packageName, String name, int userId, 4870 boolean overridePolicy) { 4871 if (!sUserManager.exists(userId)) { 4872 Log.e(TAG, "No such user:" + userId); 4873 return; 4874 } 4875 4876 mContext.enforceCallingOrSelfPermission( 4877 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4878 "revokeRuntimePermission"); 4879 4880 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4881 true /* requireFullPermission */, true /* checkShell */, 4882 "revokeRuntimePermission"); 4883 4884 final int appId; 4885 4886 synchronized (mPackages) { 4887 final PackageParser.Package pkg = mPackages.get(packageName); 4888 if (pkg == null) { 4889 throw new IllegalArgumentException("Unknown package: " + packageName); 4890 } 4891 4892 final BasePermission bp = mSettings.mPermissions.get(name); 4893 if (bp == null) { 4894 throw new IllegalArgumentException("Unknown permission: " + name); 4895 } 4896 4897 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4898 4899 // If a permission review is required for legacy apps we represent 4900 // their permissions as always granted runtime ones since we need 4901 // to keep the review required permission flag per user while an 4902 // install permission's state is shared across all users. 4903 if (mPermissionReviewRequired 4904 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4905 && bp.isRuntime()) { 4906 return; 4907 } 4908 4909 SettingBase sb = (SettingBase) pkg.mExtras; 4910 if (sb == null) { 4911 throw new IllegalArgumentException("Unknown package: " + packageName); 4912 } 4913 4914 final PermissionsState permissionsState = sb.getPermissionsState(); 4915 4916 final int flags = permissionsState.getPermissionFlags(name, userId); 4917 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4918 throw new SecurityException("Cannot revoke system fixed permission " 4919 + name + " for package " + packageName); 4920 } 4921 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4922 throw new SecurityException("Cannot revoke policy fixed permission " 4923 + name + " for package " + packageName); 4924 } 4925 4926 if (bp.isDevelopment()) { 4927 // Development permissions must be handled specially, since they are not 4928 // normal runtime permissions. For now they apply to all users. 4929 if (permissionsState.revokeInstallPermission(bp) != 4930 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4931 scheduleWriteSettingsLocked(); 4932 } 4933 return; 4934 } 4935 4936 if (permissionsState.revokeRuntimePermission(bp, userId) == 4937 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4938 return; 4939 } 4940 4941 if (bp.isRuntime()) { 4942 logPermissionRevoked(mContext, name, packageName); 4943 } 4944 4945 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4946 4947 // Critical, after this call app should never have the permission. 4948 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4949 4950 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4951 } 4952 4953 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4954 } 4955 4956 /** 4957 * Get the first event id for the permission. 4958 * 4959 * <p>There are four events for each permission: <ul> 4960 * <li>Request permission: first id + 0</li> 4961 * <li>Grant permission: first id + 1</li> 4962 * <li>Request for permission denied: first id + 2</li> 4963 * <li>Revoke permission: first id + 3</li> 4964 * </ul></p> 4965 * 4966 * @param name name of the permission 4967 * 4968 * @return The first event id for the permission 4969 */ 4970 private static int getBaseEventId(@NonNull String name) { 4971 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4972 4973 if (eventIdIndex == -1) { 4974 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4975 || "user".equals(Build.TYPE)) { 4976 Log.i(TAG, "Unknown permission " + name); 4977 4978 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4979 } else { 4980 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4981 // 4982 // Also update 4983 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4984 // - metrics_constants.proto 4985 throw new IllegalStateException("Unknown permission " + name); 4986 } 4987 } 4988 4989 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4990 } 4991 4992 /** 4993 * Log that a permission was revoked. 4994 * 4995 * @param context Context of the caller 4996 * @param name name of the permission 4997 * @param packageName package permission if for 4998 */ 4999 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5000 @NonNull String packageName) { 5001 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5002 } 5003 5004 /** 5005 * Log that a permission request was granted. 5006 * 5007 * @param context Context of the caller 5008 * @param name name of the permission 5009 * @param packageName package permission if for 5010 */ 5011 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5012 @NonNull String packageName) { 5013 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5014 } 5015 5016 @Override 5017 public void resetRuntimePermissions() { 5018 mContext.enforceCallingOrSelfPermission( 5019 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5020 "revokeRuntimePermission"); 5021 5022 int callingUid = Binder.getCallingUid(); 5023 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5024 mContext.enforceCallingOrSelfPermission( 5025 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5026 "resetRuntimePermissions"); 5027 } 5028 5029 synchronized (mPackages) { 5030 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5031 for (int userId : UserManagerService.getInstance().getUserIds()) { 5032 final int packageCount = mPackages.size(); 5033 for (int i = 0; i < packageCount; i++) { 5034 PackageParser.Package pkg = mPackages.valueAt(i); 5035 if (!(pkg.mExtras instanceof PackageSetting)) { 5036 continue; 5037 } 5038 PackageSetting ps = (PackageSetting) pkg.mExtras; 5039 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5040 } 5041 } 5042 } 5043 } 5044 5045 @Override 5046 public int getPermissionFlags(String name, String packageName, int userId) { 5047 if (!sUserManager.exists(userId)) { 5048 return 0; 5049 } 5050 5051 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5052 5053 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5054 true /* requireFullPermission */, false /* checkShell */, 5055 "getPermissionFlags"); 5056 5057 synchronized (mPackages) { 5058 final PackageParser.Package pkg = mPackages.get(packageName); 5059 if (pkg == null) { 5060 return 0; 5061 } 5062 5063 final BasePermission bp = mSettings.mPermissions.get(name); 5064 if (bp == null) { 5065 return 0; 5066 } 5067 5068 SettingBase sb = (SettingBase) pkg.mExtras; 5069 if (sb == null) { 5070 return 0; 5071 } 5072 5073 PermissionsState permissionsState = sb.getPermissionsState(); 5074 return permissionsState.getPermissionFlags(name, userId); 5075 } 5076 } 5077 5078 @Override 5079 public void updatePermissionFlags(String name, String packageName, int flagMask, 5080 int flagValues, int userId) { 5081 if (!sUserManager.exists(userId)) { 5082 return; 5083 } 5084 5085 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5086 5087 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5088 true /* requireFullPermission */, true /* checkShell */, 5089 "updatePermissionFlags"); 5090 5091 // Only the system can change these flags and nothing else. 5092 if (getCallingUid() != Process.SYSTEM_UID) { 5093 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5094 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5095 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5096 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5097 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5098 } 5099 5100 synchronized (mPackages) { 5101 final PackageParser.Package pkg = mPackages.get(packageName); 5102 if (pkg == null) { 5103 throw new IllegalArgumentException("Unknown package: " + packageName); 5104 } 5105 5106 final BasePermission bp = mSettings.mPermissions.get(name); 5107 if (bp == null) { 5108 throw new IllegalArgumentException("Unknown permission: " + name); 5109 } 5110 5111 SettingBase sb = (SettingBase) pkg.mExtras; 5112 if (sb == null) { 5113 throw new IllegalArgumentException("Unknown package: " + packageName); 5114 } 5115 5116 PermissionsState permissionsState = sb.getPermissionsState(); 5117 5118 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5119 5120 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5121 // Install and runtime permissions are stored in different places, 5122 // so figure out what permission changed and persist the change. 5123 if (permissionsState.getInstallPermissionState(name) != null) { 5124 scheduleWriteSettingsLocked(); 5125 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5126 || hadState) { 5127 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5128 } 5129 } 5130 } 5131 } 5132 5133 /** 5134 * Update the permission flags for all packages and runtime permissions of a user in order 5135 * to allow device or profile owner to remove POLICY_FIXED. 5136 */ 5137 @Override 5138 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5139 if (!sUserManager.exists(userId)) { 5140 return; 5141 } 5142 5143 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5144 5145 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5146 true /* requireFullPermission */, true /* checkShell */, 5147 "updatePermissionFlagsForAllApps"); 5148 5149 // Only the system can change system fixed flags. 5150 if (getCallingUid() != Process.SYSTEM_UID) { 5151 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5152 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5153 } 5154 5155 synchronized (mPackages) { 5156 boolean changed = false; 5157 final int packageCount = mPackages.size(); 5158 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5159 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5160 SettingBase sb = (SettingBase) pkg.mExtras; 5161 if (sb == null) { 5162 continue; 5163 } 5164 PermissionsState permissionsState = sb.getPermissionsState(); 5165 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5166 userId, flagMask, flagValues); 5167 } 5168 if (changed) { 5169 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5170 } 5171 } 5172 } 5173 5174 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5175 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5176 != PackageManager.PERMISSION_GRANTED 5177 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5178 != PackageManager.PERMISSION_GRANTED) { 5179 throw new SecurityException(message + " requires " 5180 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5181 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5182 } 5183 } 5184 5185 @Override 5186 public boolean shouldShowRequestPermissionRationale(String permissionName, 5187 String packageName, int userId) { 5188 if (UserHandle.getCallingUserId() != userId) { 5189 mContext.enforceCallingPermission( 5190 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5191 "canShowRequestPermissionRationale for user " + userId); 5192 } 5193 5194 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5195 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5196 return false; 5197 } 5198 5199 if (checkPermission(permissionName, packageName, userId) 5200 == PackageManager.PERMISSION_GRANTED) { 5201 return false; 5202 } 5203 5204 final int flags; 5205 5206 final long identity = Binder.clearCallingIdentity(); 5207 try { 5208 flags = getPermissionFlags(permissionName, 5209 packageName, userId); 5210 } finally { 5211 Binder.restoreCallingIdentity(identity); 5212 } 5213 5214 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5215 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5216 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5217 5218 if ((flags & fixedFlags) != 0) { 5219 return false; 5220 } 5221 5222 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5223 } 5224 5225 @Override 5226 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5227 mContext.enforceCallingOrSelfPermission( 5228 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5229 "addOnPermissionsChangeListener"); 5230 5231 synchronized (mPackages) { 5232 mOnPermissionChangeListeners.addListenerLocked(listener); 5233 } 5234 } 5235 5236 @Override 5237 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5238 synchronized (mPackages) { 5239 mOnPermissionChangeListeners.removeListenerLocked(listener); 5240 } 5241 } 5242 5243 @Override 5244 public boolean isProtectedBroadcast(String actionName) { 5245 synchronized (mPackages) { 5246 if (mProtectedBroadcasts.contains(actionName)) { 5247 return true; 5248 } else if (actionName != null) { 5249 // TODO: remove these terrible hacks 5250 if (actionName.startsWith("android.net.netmon.lingerExpired") 5251 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5252 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5253 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5254 return true; 5255 } 5256 } 5257 } 5258 return false; 5259 } 5260 5261 @Override 5262 public int checkSignatures(String pkg1, String pkg2) { 5263 synchronized (mPackages) { 5264 final PackageParser.Package p1 = mPackages.get(pkg1); 5265 final PackageParser.Package p2 = mPackages.get(pkg2); 5266 if (p1 == null || p1.mExtras == null 5267 || p2 == null || p2.mExtras == null) { 5268 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5269 } 5270 return compareSignatures(p1.mSignatures, p2.mSignatures); 5271 } 5272 } 5273 5274 @Override 5275 public int checkUidSignatures(int uid1, int uid2) { 5276 // Map to base uids. 5277 uid1 = UserHandle.getAppId(uid1); 5278 uid2 = UserHandle.getAppId(uid2); 5279 // reader 5280 synchronized (mPackages) { 5281 Signature[] s1; 5282 Signature[] s2; 5283 Object obj = mSettings.getUserIdLPr(uid1); 5284 if (obj != null) { 5285 if (obj instanceof SharedUserSetting) { 5286 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5287 } else if (obj instanceof PackageSetting) { 5288 s1 = ((PackageSetting)obj).signatures.mSignatures; 5289 } else { 5290 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5291 } 5292 } else { 5293 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5294 } 5295 obj = mSettings.getUserIdLPr(uid2); 5296 if (obj != null) { 5297 if (obj instanceof SharedUserSetting) { 5298 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5299 } else if (obj instanceof PackageSetting) { 5300 s2 = ((PackageSetting)obj).signatures.mSignatures; 5301 } else { 5302 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5303 } 5304 } else { 5305 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5306 } 5307 return compareSignatures(s1, s2); 5308 } 5309 } 5310 5311 /** 5312 * This method should typically only be used when granting or revoking 5313 * permissions, since the app may immediately restart after this call. 5314 * <p> 5315 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5316 * guard your work against the app being relaunched. 5317 */ 5318 private void killUid(int appId, int userId, String reason) { 5319 final long identity = Binder.clearCallingIdentity(); 5320 try { 5321 IActivityManager am = ActivityManager.getService(); 5322 if (am != null) { 5323 try { 5324 am.killUid(appId, userId, reason); 5325 } catch (RemoteException e) { 5326 /* ignore - same process */ 5327 } 5328 } 5329 } finally { 5330 Binder.restoreCallingIdentity(identity); 5331 } 5332 } 5333 5334 /** 5335 * Compares two sets of signatures. Returns: 5336 * <br /> 5337 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5338 * <br /> 5339 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5340 * <br /> 5341 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5342 * <br /> 5343 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5344 * <br /> 5345 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5346 */ 5347 static int compareSignatures(Signature[] s1, Signature[] s2) { 5348 if (s1 == null) { 5349 return s2 == null 5350 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5351 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5352 } 5353 5354 if (s2 == null) { 5355 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5356 } 5357 5358 if (s1.length != s2.length) { 5359 return PackageManager.SIGNATURE_NO_MATCH; 5360 } 5361 5362 // Since both signature sets are of size 1, we can compare without HashSets. 5363 if (s1.length == 1) { 5364 return s1[0].equals(s2[0]) ? 5365 PackageManager.SIGNATURE_MATCH : 5366 PackageManager.SIGNATURE_NO_MATCH; 5367 } 5368 5369 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5370 for (Signature sig : s1) { 5371 set1.add(sig); 5372 } 5373 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5374 for (Signature sig : s2) { 5375 set2.add(sig); 5376 } 5377 // Make sure s2 contains all signatures in s1. 5378 if (set1.equals(set2)) { 5379 return PackageManager.SIGNATURE_MATCH; 5380 } 5381 return PackageManager.SIGNATURE_NO_MATCH; 5382 } 5383 5384 /** 5385 * If the database version for this type of package (internal storage or 5386 * external storage) is less than the version where package signatures 5387 * were updated, return true. 5388 */ 5389 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5390 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5391 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5392 } 5393 5394 /** 5395 * Used for backward compatibility to make sure any packages with 5396 * certificate chains get upgraded to the new style. {@code existingSigs} 5397 * will be in the old format (since they were stored on disk from before the 5398 * system upgrade) and {@code scannedSigs} will be in the newer format. 5399 */ 5400 private int compareSignaturesCompat(PackageSignatures existingSigs, 5401 PackageParser.Package scannedPkg) { 5402 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5403 return PackageManager.SIGNATURE_NO_MATCH; 5404 } 5405 5406 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5407 for (Signature sig : existingSigs.mSignatures) { 5408 existingSet.add(sig); 5409 } 5410 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5411 for (Signature sig : scannedPkg.mSignatures) { 5412 try { 5413 Signature[] chainSignatures = sig.getChainSignatures(); 5414 for (Signature chainSig : chainSignatures) { 5415 scannedCompatSet.add(chainSig); 5416 } 5417 } catch (CertificateEncodingException e) { 5418 scannedCompatSet.add(sig); 5419 } 5420 } 5421 /* 5422 * Make sure the expanded scanned set contains all signatures in the 5423 * existing one. 5424 */ 5425 if (scannedCompatSet.equals(existingSet)) { 5426 // Migrate the old signatures to the new scheme. 5427 existingSigs.assignSignatures(scannedPkg.mSignatures); 5428 // The new KeySets will be re-added later in the scanning process. 5429 synchronized (mPackages) { 5430 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5431 } 5432 return PackageManager.SIGNATURE_MATCH; 5433 } 5434 return PackageManager.SIGNATURE_NO_MATCH; 5435 } 5436 5437 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5438 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5439 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5440 } 5441 5442 private int compareSignaturesRecover(PackageSignatures existingSigs, 5443 PackageParser.Package scannedPkg) { 5444 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5445 return PackageManager.SIGNATURE_NO_MATCH; 5446 } 5447 5448 String msg = null; 5449 try { 5450 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5451 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5452 + scannedPkg.packageName); 5453 return PackageManager.SIGNATURE_MATCH; 5454 } 5455 } catch (CertificateException e) { 5456 msg = e.getMessage(); 5457 } 5458 5459 logCriticalInfo(Log.INFO, 5460 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5461 return PackageManager.SIGNATURE_NO_MATCH; 5462 } 5463 5464 @Override 5465 public List<String> getAllPackages() { 5466 synchronized (mPackages) { 5467 return new ArrayList<String>(mPackages.keySet()); 5468 } 5469 } 5470 5471 @Override 5472 public String[] getPackagesForUid(int uid) { 5473 final int userId = UserHandle.getUserId(uid); 5474 uid = UserHandle.getAppId(uid); 5475 // reader 5476 synchronized (mPackages) { 5477 Object obj = mSettings.getUserIdLPr(uid); 5478 if (obj instanceof SharedUserSetting) { 5479 final SharedUserSetting sus = (SharedUserSetting) obj; 5480 final int N = sus.packages.size(); 5481 String[] res = new String[N]; 5482 final Iterator<PackageSetting> it = sus.packages.iterator(); 5483 int i = 0; 5484 while (it.hasNext()) { 5485 PackageSetting ps = it.next(); 5486 if (ps.getInstalled(userId)) { 5487 res[i++] = ps.name; 5488 } else { 5489 res = ArrayUtils.removeElement(String.class, res, res[i]); 5490 } 5491 } 5492 return res; 5493 } else if (obj instanceof PackageSetting) { 5494 final PackageSetting ps = (PackageSetting) obj; 5495 if (ps.getInstalled(userId)) { 5496 return new String[]{ps.name}; 5497 } 5498 } 5499 } 5500 return null; 5501 } 5502 5503 @Override 5504 public String getNameForUid(int uid) { 5505 // reader 5506 synchronized (mPackages) { 5507 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5508 if (obj instanceof SharedUserSetting) { 5509 final SharedUserSetting sus = (SharedUserSetting) obj; 5510 return sus.name + ":" + sus.userId; 5511 } else if (obj instanceof PackageSetting) { 5512 final PackageSetting ps = (PackageSetting) obj; 5513 return ps.name; 5514 } 5515 } 5516 return null; 5517 } 5518 5519 @Override 5520 public int getUidForSharedUser(String sharedUserName) { 5521 if(sharedUserName == null) { 5522 return -1; 5523 } 5524 // reader 5525 synchronized (mPackages) { 5526 SharedUserSetting suid; 5527 try { 5528 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5529 if (suid != null) { 5530 return suid.userId; 5531 } 5532 } catch (PackageManagerException ignore) { 5533 // can't happen, but, still need to catch it 5534 } 5535 return -1; 5536 } 5537 } 5538 5539 @Override 5540 public int getFlagsForUid(int uid) { 5541 synchronized (mPackages) { 5542 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5543 if (obj instanceof SharedUserSetting) { 5544 final SharedUserSetting sus = (SharedUserSetting) obj; 5545 return sus.pkgFlags; 5546 } else if (obj instanceof PackageSetting) { 5547 final PackageSetting ps = (PackageSetting) obj; 5548 return ps.pkgFlags; 5549 } 5550 } 5551 return 0; 5552 } 5553 5554 @Override 5555 public int getPrivateFlagsForUid(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.pkgPrivateFlags; 5561 } else if (obj instanceof PackageSetting) { 5562 final PackageSetting ps = (PackageSetting) obj; 5563 return ps.pkgPrivateFlags; 5564 } 5565 } 5566 return 0; 5567 } 5568 5569 @Override 5570 public boolean isUidPrivileged(int uid) { 5571 uid = UserHandle.getAppId(uid); 5572 // reader 5573 synchronized (mPackages) { 5574 Object obj = mSettings.getUserIdLPr(uid); 5575 if (obj instanceof SharedUserSetting) { 5576 final SharedUserSetting sus = (SharedUserSetting) obj; 5577 final Iterator<PackageSetting> it = sus.packages.iterator(); 5578 while (it.hasNext()) { 5579 if (it.next().isPrivileged()) { 5580 return true; 5581 } 5582 } 5583 } else if (obj instanceof PackageSetting) { 5584 final PackageSetting ps = (PackageSetting) obj; 5585 return ps.isPrivileged(); 5586 } 5587 } 5588 return false; 5589 } 5590 5591 @Override 5592 public String[] getAppOpPermissionPackages(String permissionName) { 5593 synchronized (mPackages) { 5594 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5595 if (pkgs == null) { 5596 return null; 5597 } 5598 return pkgs.toArray(new String[pkgs.size()]); 5599 } 5600 } 5601 5602 @Override 5603 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5604 int flags, int userId) { 5605 return resolveIntentInternal( 5606 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5607 } 5608 5609 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5610 int flags, int userId, boolean includeInstantApp) { 5611 try { 5612 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5613 5614 if (!sUserManager.exists(userId)) return null; 5615 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5616 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5617 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5618 5619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5620 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5621 flags, userId, includeInstantApp); 5622 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5623 5624 final ResolveInfo bestChoice = 5625 chooseBestActivity(intent, resolvedType, flags, query, userId); 5626 return bestChoice; 5627 } finally { 5628 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5629 } 5630 } 5631 5632 @Override 5633 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5634 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5635 throw new SecurityException( 5636 "findPersistentPreferredActivity can only be run by the system"); 5637 } 5638 if (!sUserManager.exists(userId)) { 5639 return null; 5640 } 5641 intent = updateIntentForResolve(intent); 5642 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5643 final int flags = updateFlagsForResolve(0, userId, intent, false); 5644 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5645 userId); 5646 synchronized (mPackages) { 5647 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5648 userId); 5649 } 5650 } 5651 5652 @Override 5653 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5654 IntentFilter filter, int match, ComponentName activity) { 5655 final int userId = UserHandle.getCallingUserId(); 5656 if (DEBUG_PREFERRED) { 5657 Log.v(TAG, "setLastChosenActivity intent=" + intent 5658 + " resolvedType=" + resolvedType 5659 + " flags=" + flags 5660 + " filter=" + filter 5661 + " match=" + match 5662 + " activity=" + activity); 5663 filter.dump(new PrintStreamPrinter(System.out), " "); 5664 } 5665 intent.setComponent(null); 5666 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5667 userId); 5668 // Find any earlier preferred or last chosen entries and nuke them 5669 findPreferredActivity(intent, resolvedType, 5670 flags, query, 0, false, true, false, userId); 5671 // Add the new activity as the last chosen for this filter 5672 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5673 "Setting last chosen"); 5674 } 5675 5676 @Override 5677 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5678 final int userId = UserHandle.getCallingUserId(); 5679 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5680 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5681 userId); 5682 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5683 false, false, false, userId); 5684 } 5685 5686 /** 5687 * Returns whether or not instant apps have been disabled remotely. 5688 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5689 * held. Otherwise we run the risk of deadlock. 5690 */ 5691 private boolean isEphemeralDisabled() { 5692 // ephemeral apps have been disabled across the board 5693 if (DISABLE_EPHEMERAL_APPS) { 5694 return true; 5695 } 5696 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5697 if (!mSystemReady) { 5698 return true; 5699 } 5700 // we can't get a content resolver until the system is ready; these checks must happen last 5701 final ContentResolver resolver = mContext.getContentResolver(); 5702 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5703 return true; 5704 } 5705 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5706 } 5707 5708 private boolean isEphemeralAllowed( 5709 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5710 boolean skipPackageCheck) { 5711 final int callingUser = UserHandle.getCallingUserId(); 5712 if (callingUser != UserHandle.USER_SYSTEM) { 5713 return false; 5714 } 5715 if (mInstantAppResolverConnection == null) { 5716 return false; 5717 } 5718 if (mInstantAppInstallerComponent == null) { 5719 return false; 5720 } 5721 if (intent.getComponent() != null) { 5722 return false; 5723 } 5724 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5725 return false; 5726 } 5727 if (!skipPackageCheck && intent.getPackage() != null) { 5728 return false; 5729 } 5730 final boolean isWebUri = hasWebURI(intent); 5731 if (!isWebUri || intent.getData().getHost() == null) { 5732 return false; 5733 } 5734 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5735 // Or if there's already an ephemeral app installed that handles the action 5736 synchronized (mPackages) { 5737 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5738 for (int n = 0; n < count; n++) { 5739 ResolveInfo info = resolvedActivities.get(n); 5740 String packageName = info.activityInfo.packageName; 5741 PackageSetting ps = mSettings.mPackages.get(packageName); 5742 if (ps != null) { 5743 // Try to get the status from User settings first 5744 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5745 int status = (int) (packedStatus >> 32); 5746 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5747 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5748 if (DEBUG_EPHEMERAL) { 5749 Slog.v(TAG, "DENY ephemeral apps;" 5750 + " pkg: " + packageName + ", status: " + status); 5751 } 5752 return false; 5753 } 5754 if (ps.getInstantApp(userId)) { 5755 return false; 5756 } 5757 } 5758 } 5759 } 5760 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5761 return true; 5762 } 5763 5764 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5765 Intent origIntent, String resolvedType, String callingPackage, 5766 int userId) { 5767 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5768 new EphemeralRequest(responseObj, origIntent, resolvedType, 5769 callingPackage, userId)); 5770 mHandler.sendMessage(msg); 5771 } 5772 5773 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5774 int flags, List<ResolveInfo> query, int userId) { 5775 if (query != null) { 5776 final int N = query.size(); 5777 if (N == 1) { 5778 return query.get(0); 5779 } else if (N > 1) { 5780 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5781 // If there is more than one activity with the same priority, 5782 // then let the user decide between them. 5783 ResolveInfo r0 = query.get(0); 5784 ResolveInfo r1 = query.get(1); 5785 if (DEBUG_INTENT_MATCHING || debug) { 5786 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5787 + r1.activityInfo.name + "=" + r1.priority); 5788 } 5789 // If the first activity has a higher priority, or a different 5790 // default, then it is always desirable to pick it. 5791 if (r0.priority != r1.priority 5792 || r0.preferredOrder != r1.preferredOrder 5793 || r0.isDefault != r1.isDefault) { 5794 return query.get(0); 5795 } 5796 // If we have saved a preference for a preferred activity for 5797 // this Intent, use that. 5798 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5799 flags, query, r0.priority, true, false, debug, userId); 5800 if (ri != null) { 5801 return ri; 5802 } 5803 // If we have an ephemeral app, use it 5804 for (int i = 0; i < N; i++) { 5805 ri = query.get(i); 5806 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5807 return ri; 5808 } 5809 } 5810 ri = new ResolveInfo(mResolveInfo); 5811 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5812 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5813 // If all of the options come from the same package, show the application's 5814 // label and icon instead of the generic resolver's. 5815 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5816 // and then throw away the ResolveInfo itself, meaning that the caller loses 5817 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5818 // a fallback for this case; we only set the target package's resources on 5819 // the ResolveInfo, not the ActivityInfo. 5820 final String intentPackage = intent.getPackage(); 5821 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5822 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5823 ri.resolvePackageName = intentPackage; 5824 if (userNeedsBadging(userId)) { 5825 ri.noResourceId = true; 5826 } else { 5827 ri.icon = appi.icon; 5828 } 5829 ri.iconResourceId = appi.icon; 5830 ri.labelRes = appi.labelRes; 5831 } 5832 ri.activityInfo.applicationInfo = new ApplicationInfo( 5833 ri.activityInfo.applicationInfo); 5834 if (userId != 0) { 5835 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5836 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5837 } 5838 // Make sure that the resolver is displayable in car mode 5839 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5840 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5841 return ri; 5842 } 5843 } 5844 return null; 5845 } 5846 5847 /** 5848 * Return true if the given list is not empty and all of its contents have 5849 * an activityInfo with the given package name. 5850 */ 5851 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5852 if (ArrayUtils.isEmpty(list)) { 5853 return false; 5854 } 5855 for (int i = 0, N = list.size(); i < N; i++) { 5856 final ResolveInfo ri = list.get(i); 5857 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5858 if (ai == null || !packageName.equals(ai.packageName)) { 5859 return false; 5860 } 5861 } 5862 return true; 5863 } 5864 5865 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5866 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5867 final int N = query.size(); 5868 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5869 .get(userId); 5870 // Get the list of persistent preferred activities that handle the intent 5871 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5872 List<PersistentPreferredActivity> pprefs = ppir != null 5873 ? ppir.queryIntent(intent, resolvedType, 5874 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5875 userId) 5876 : null; 5877 if (pprefs != null && pprefs.size() > 0) { 5878 final int M = pprefs.size(); 5879 for (int i=0; i<M; i++) { 5880 final PersistentPreferredActivity ppa = pprefs.get(i); 5881 if (DEBUG_PREFERRED || debug) { 5882 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5883 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5884 + "\n component=" + ppa.mComponent); 5885 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5886 } 5887 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5888 flags | MATCH_DISABLED_COMPONENTS, userId); 5889 if (DEBUG_PREFERRED || debug) { 5890 Slog.v(TAG, "Found persistent preferred activity:"); 5891 if (ai != null) { 5892 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5893 } else { 5894 Slog.v(TAG, " null"); 5895 } 5896 } 5897 if (ai == null) { 5898 // This previously registered persistent preferred activity 5899 // component is no longer known. Ignore it and do NOT remove it. 5900 continue; 5901 } 5902 for (int j=0; j<N; j++) { 5903 final ResolveInfo ri = query.get(j); 5904 if (!ri.activityInfo.applicationInfo.packageName 5905 .equals(ai.applicationInfo.packageName)) { 5906 continue; 5907 } 5908 if (!ri.activityInfo.name.equals(ai.name)) { 5909 continue; 5910 } 5911 // Found a persistent preference that can handle the intent. 5912 if (DEBUG_PREFERRED || debug) { 5913 Slog.v(TAG, "Returning persistent preferred activity: " + 5914 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5915 } 5916 return ri; 5917 } 5918 } 5919 } 5920 return null; 5921 } 5922 5923 // TODO: handle preferred activities missing while user has amnesia 5924 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5925 List<ResolveInfo> query, int priority, boolean always, 5926 boolean removeMatches, boolean debug, int userId) { 5927 if (!sUserManager.exists(userId)) return null; 5928 flags = updateFlagsForResolve(flags, userId, intent, false); 5929 intent = updateIntentForResolve(intent); 5930 // writer 5931 synchronized (mPackages) { 5932 // Try to find a matching persistent preferred activity. 5933 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5934 debug, userId); 5935 5936 // If a persistent preferred activity matched, use it. 5937 if (pri != null) { 5938 return pri; 5939 } 5940 5941 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5942 // Get the list of preferred activities that handle the intent 5943 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5944 List<PreferredActivity> prefs = pir != null 5945 ? pir.queryIntent(intent, resolvedType, 5946 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5947 userId) 5948 : null; 5949 if (prefs != null && prefs.size() > 0) { 5950 boolean changed = false; 5951 try { 5952 // First figure out how good the original match set is. 5953 // We will only allow preferred activities that came 5954 // from the same match quality. 5955 int match = 0; 5956 5957 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5958 5959 final int N = query.size(); 5960 for (int j=0; j<N; j++) { 5961 final ResolveInfo ri = query.get(j); 5962 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5963 + ": 0x" + Integer.toHexString(match)); 5964 if (ri.match > match) { 5965 match = ri.match; 5966 } 5967 } 5968 5969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5970 + Integer.toHexString(match)); 5971 5972 match &= IntentFilter.MATCH_CATEGORY_MASK; 5973 final int M = prefs.size(); 5974 for (int i=0; i<M; i++) { 5975 final PreferredActivity pa = prefs.get(i); 5976 if (DEBUG_PREFERRED || debug) { 5977 Slog.v(TAG, "Checking PreferredActivity ds=" 5978 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5979 + "\n component=" + pa.mPref.mComponent); 5980 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5981 } 5982 if (pa.mPref.mMatch != match) { 5983 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5984 + Integer.toHexString(pa.mPref.mMatch)); 5985 continue; 5986 } 5987 // If it's not an "always" type preferred activity and that's what we're 5988 // looking for, skip it. 5989 if (always && !pa.mPref.mAlways) { 5990 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5991 continue; 5992 } 5993 final ActivityInfo ai = getActivityInfo( 5994 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5995 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5996 userId); 5997 if (DEBUG_PREFERRED || debug) { 5998 Slog.v(TAG, "Found preferred activity:"); 5999 if (ai != null) { 6000 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6001 } else { 6002 Slog.v(TAG, " null"); 6003 } 6004 } 6005 if (ai == null) { 6006 // This previously registered preferred activity 6007 // component is no longer known. Most likely an update 6008 // to the app was installed and in the new version this 6009 // component no longer exists. Clean it up by removing 6010 // it from the preferred activities list, and skip it. 6011 Slog.w(TAG, "Removing dangling preferred activity: " 6012 + pa.mPref.mComponent); 6013 pir.removeFilter(pa); 6014 changed = true; 6015 continue; 6016 } 6017 for (int j=0; j<N; j++) { 6018 final ResolveInfo ri = query.get(j); 6019 if (!ri.activityInfo.applicationInfo.packageName 6020 .equals(ai.applicationInfo.packageName)) { 6021 continue; 6022 } 6023 if (!ri.activityInfo.name.equals(ai.name)) { 6024 continue; 6025 } 6026 6027 if (removeMatches) { 6028 pir.removeFilter(pa); 6029 changed = true; 6030 if (DEBUG_PREFERRED) { 6031 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6032 } 6033 break; 6034 } 6035 6036 // Okay we found a previously set preferred or last chosen app. 6037 // If the result set is different from when this 6038 // was created, we need to clear it and re-ask the 6039 // user their preference, if we're looking for an "always" type entry. 6040 if (always && !pa.mPref.sameSet(query)) { 6041 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6042 + intent + " type " + resolvedType); 6043 if (DEBUG_PREFERRED) { 6044 Slog.v(TAG, "Removing preferred activity since set changed " 6045 + pa.mPref.mComponent); 6046 } 6047 pir.removeFilter(pa); 6048 // Re-add the filter as a "last chosen" entry (!always) 6049 PreferredActivity lastChosen = new PreferredActivity( 6050 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6051 pir.addFilter(lastChosen); 6052 changed = true; 6053 return null; 6054 } 6055 6056 // Yay! Either the set matched or we're looking for the last chosen 6057 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6058 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6059 return ri; 6060 } 6061 } 6062 } finally { 6063 if (changed) { 6064 if (DEBUG_PREFERRED) { 6065 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6066 } 6067 scheduleWritePackageRestrictionsLocked(userId); 6068 } 6069 } 6070 } 6071 } 6072 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6073 return null; 6074 } 6075 6076 /* 6077 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6078 */ 6079 @Override 6080 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6081 int targetUserId) { 6082 mContext.enforceCallingOrSelfPermission( 6083 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6084 List<CrossProfileIntentFilter> matches = 6085 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6086 if (matches != null) { 6087 int size = matches.size(); 6088 for (int i = 0; i < size; i++) { 6089 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6090 } 6091 } 6092 if (hasWebURI(intent)) { 6093 // cross-profile app linking works only towards the parent. 6094 final UserInfo parent = getProfileParent(sourceUserId); 6095 synchronized(mPackages) { 6096 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6097 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6098 intent, resolvedType, flags, sourceUserId, parent.id); 6099 return xpDomainInfo != null; 6100 } 6101 } 6102 return false; 6103 } 6104 6105 private UserInfo getProfileParent(int userId) { 6106 final long identity = Binder.clearCallingIdentity(); 6107 try { 6108 return sUserManager.getProfileParent(userId); 6109 } finally { 6110 Binder.restoreCallingIdentity(identity); 6111 } 6112 } 6113 6114 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6115 String resolvedType, int userId) { 6116 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6117 if (resolver != null) { 6118 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6119 } 6120 return null; 6121 } 6122 6123 @Override 6124 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6125 String resolvedType, int flags, int userId) { 6126 try { 6127 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6128 6129 return new ParceledListSlice<>( 6130 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6131 } finally { 6132 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6133 } 6134 } 6135 6136 /** 6137 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6138 * instant, returns {@code null}. 6139 */ 6140 private String getInstantAppPackageName(int callingUid) { 6141 final int appId = UserHandle.getAppId(callingUid); 6142 synchronized (mPackages) { 6143 final Object obj = mSettings.getUserIdLPr(appId); 6144 if (obj instanceof PackageSetting) { 6145 final PackageSetting ps = (PackageSetting) obj; 6146 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6147 return isInstantApp ? ps.pkg.packageName : null; 6148 } 6149 } 6150 return null; 6151 } 6152 6153 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6154 String resolvedType, int flags, int userId) { 6155 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6156 } 6157 6158 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6159 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6160 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6161 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6162 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6163 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6164 false /* requireFullPermission */, false /* checkShell */, 6165 "query intent activities"); 6166 ComponentName comp = intent.getComponent(); 6167 if (comp == null) { 6168 if (intent.getSelector() != null) { 6169 intent = intent.getSelector(); 6170 comp = intent.getComponent(); 6171 } 6172 } 6173 6174 if (comp != null) { 6175 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6176 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6177 if (ai != null) { 6178 // When specifying an explicit component, we prevent the activity from being 6179 // used when either 1) the calling package is normal and the activity is within 6180 // an ephemeral application or 2) the calling package is ephemeral and the 6181 // activity is not visible to ephemeral applications. 6182 final boolean matchInstantApp = 6183 (flags & PackageManager.MATCH_INSTANT) != 0; 6184 final boolean matchVisibleToInstantAppOnly = 6185 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6186 final boolean isCallerInstantApp = 6187 instantAppPkgName != null; 6188 final boolean isTargetSameInstantApp = 6189 comp.getPackageName().equals(instantAppPkgName); 6190 final boolean isTargetInstantApp = 6191 (ai.applicationInfo.privateFlags 6192 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6193 final boolean isTargetHiddenFromInstantApp = 6194 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6195 final boolean blockResolution = 6196 !isTargetSameInstantApp 6197 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6198 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6199 && isTargetHiddenFromInstantApp)); 6200 if (!blockResolution) { 6201 final ResolveInfo ri = new ResolveInfo(); 6202 ri.activityInfo = ai; 6203 list.add(ri); 6204 } 6205 } 6206 return applyPostResolutionFilter(list, instantAppPkgName); 6207 } 6208 6209 // reader 6210 boolean sortResult = false; 6211 boolean addEphemeral = false; 6212 List<ResolveInfo> result; 6213 final String pkgName = intent.getPackage(); 6214 final boolean ephemeralDisabled = isEphemeralDisabled(); 6215 synchronized (mPackages) { 6216 if (pkgName == null) { 6217 List<CrossProfileIntentFilter> matchingFilters = 6218 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6219 // Check for results that need to skip the current profile. 6220 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6221 resolvedType, flags, userId); 6222 if (xpResolveInfo != null) { 6223 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6224 xpResult.add(xpResolveInfo); 6225 return applyPostResolutionFilter( 6226 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6227 } 6228 6229 // Check for results in the current profile. 6230 result = filterIfNotSystemUser(mActivities.queryIntent( 6231 intent, resolvedType, flags, userId), userId); 6232 addEphemeral = !ephemeralDisabled 6233 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6234 6235 // Check for cross profile results. 6236 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6237 xpResolveInfo = queryCrossProfileIntents( 6238 matchingFilters, intent, resolvedType, flags, userId, 6239 hasNonNegativePriorityResult); 6240 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6241 boolean isVisibleToUser = filterIfNotSystemUser( 6242 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6243 if (isVisibleToUser) { 6244 result.add(xpResolveInfo); 6245 sortResult = true; 6246 } 6247 } 6248 if (hasWebURI(intent)) { 6249 CrossProfileDomainInfo xpDomainInfo = null; 6250 final UserInfo parent = getProfileParent(userId); 6251 if (parent != null) { 6252 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6253 flags, userId, parent.id); 6254 } 6255 if (xpDomainInfo != null) { 6256 if (xpResolveInfo != null) { 6257 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6258 // in the result. 6259 result.remove(xpResolveInfo); 6260 } 6261 if (result.size() == 0 && !addEphemeral) { 6262 // No result in current profile, but found candidate in parent user. 6263 // And we are not going to add emphemeral app, so we can return the 6264 // result straight away. 6265 result.add(xpDomainInfo.resolveInfo); 6266 return applyPostResolutionFilter(result, instantAppPkgName); 6267 } 6268 } else if (result.size() <= 1 && !addEphemeral) { 6269 // No result in parent user and <= 1 result in current profile, and we 6270 // are not going to add emphemeral app, so we can return the result without 6271 // further processing. 6272 return applyPostResolutionFilter(result, instantAppPkgName); 6273 } 6274 // We have more than one candidate (combining results from current and parent 6275 // profile), so we need filtering and sorting. 6276 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6277 intent, flags, result, xpDomainInfo, userId); 6278 sortResult = true; 6279 } 6280 } else { 6281 final PackageParser.Package pkg = mPackages.get(pkgName); 6282 if (pkg != null) { 6283 result = applyPostResolutionFilter(filterIfNotSystemUser( 6284 mActivities.queryIntentForPackage( 6285 intent, resolvedType, flags, pkg.activities, userId), 6286 userId), instantAppPkgName); 6287 } else { 6288 // the caller wants to resolve for a particular package; however, there 6289 // were no installed results, so, try to find an ephemeral result 6290 addEphemeral = !ephemeralDisabled 6291 && isEphemeralAllowed( 6292 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6293 result = new ArrayList<ResolveInfo>(); 6294 } 6295 } 6296 } 6297 if (addEphemeral) { 6298 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6299 final EphemeralRequest requestObject = new EphemeralRequest( 6300 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6301 null /*callingPackage*/, userId); 6302 final AuxiliaryResolveInfo auxiliaryResponse = 6303 EphemeralResolver.doEphemeralResolutionPhaseOne( 6304 mContext, mInstantAppResolverConnection, requestObject); 6305 if (auxiliaryResponse != null) { 6306 if (DEBUG_EPHEMERAL) { 6307 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6308 } 6309 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6310 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6311 // make sure this resolver is the default 6312 ephemeralInstaller.isDefault = true; 6313 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6314 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6315 // add a non-generic filter 6316 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6317 ephemeralInstaller.filter.addDataPath( 6318 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6319 ephemeralInstaller.instantAppAvailable = true; 6320 result.add(ephemeralInstaller); 6321 } 6322 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6323 } 6324 if (sortResult) { 6325 Collections.sort(result, mResolvePrioritySorter); 6326 } 6327 return applyPostResolutionFilter(result, instantAppPkgName); 6328 } 6329 6330 private static class CrossProfileDomainInfo { 6331 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6332 ResolveInfo resolveInfo; 6333 /* Best domain verification status of the activities found in the other profile */ 6334 int bestDomainVerificationStatus; 6335 } 6336 6337 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6338 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6339 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6340 sourceUserId)) { 6341 return null; 6342 } 6343 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6344 resolvedType, flags, parentUserId); 6345 6346 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6347 return null; 6348 } 6349 CrossProfileDomainInfo result = null; 6350 int size = resultTargetUser.size(); 6351 for (int i = 0; i < size; i++) { 6352 ResolveInfo riTargetUser = resultTargetUser.get(i); 6353 // Intent filter verification is only for filters that specify a host. So don't return 6354 // those that handle all web uris. 6355 if (riTargetUser.handleAllWebDataURI) { 6356 continue; 6357 } 6358 String packageName = riTargetUser.activityInfo.packageName; 6359 PackageSetting ps = mSettings.mPackages.get(packageName); 6360 if (ps == null) { 6361 continue; 6362 } 6363 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6364 int status = (int)(verificationState >> 32); 6365 if (result == null) { 6366 result = new CrossProfileDomainInfo(); 6367 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6368 sourceUserId, parentUserId); 6369 result.bestDomainVerificationStatus = status; 6370 } else { 6371 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6372 result.bestDomainVerificationStatus); 6373 } 6374 } 6375 // Don't consider matches with status NEVER across profiles. 6376 if (result != null && result.bestDomainVerificationStatus 6377 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6378 return null; 6379 } 6380 return result; 6381 } 6382 6383 /** 6384 * Verification statuses are ordered from the worse to the best, except for 6385 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6386 */ 6387 private int bestDomainVerificationStatus(int status1, int status2) { 6388 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6389 return status2; 6390 } 6391 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6392 return status1; 6393 } 6394 return (int) MathUtils.max(status1, status2); 6395 } 6396 6397 private boolean isUserEnabled(int userId) { 6398 long callingId = Binder.clearCallingIdentity(); 6399 try { 6400 UserInfo userInfo = sUserManager.getUserInfo(userId); 6401 return userInfo != null && userInfo.isEnabled(); 6402 } finally { 6403 Binder.restoreCallingIdentity(callingId); 6404 } 6405 } 6406 6407 /** 6408 * Filter out activities with systemUserOnly flag set, when current user is not System. 6409 * 6410 * @return filtered list 6411 */ 6412 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6413 if (userId == UserHandle.USER_SYSTEM) { 6414 return resolveInfos; 6415 } 6416 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6417 ResolveInfo info = resolveInfos.get(i); 6418 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6419 resolveInfos.remove(i); 6420 } 6421 } 6422 return resolveInfos; 6423 } 6424 6425 /** 6426 * Filters out ephemeral activities. 6427 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6428 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6429 * 6430 * @param resolveInfos The pre-filtered list of resolved activities 6431 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6432 * is performed. 6433 * @return A filtered list of resolved activities. 6434 */ 6435 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6436 String ephemeralPkgName) { 6437 // TODO: When adding on-demand split support for non-instant apps, remove this check 6438 // and always apply post filtering 6439 if (ephemeralPkgName == null) { 6440 return resolveInfos; 6441 } 6442 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6443 final ResolveInfo info = resolveInfos.get(i); 6444 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6445 // allow activities that are defined in the provided package 6446 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6447 if (info.activityInfo.splitName != null 6448 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6449 info.activityInfo.splitName)) { 6450 // requested activity is defined in a split that hasn't been installed yet. 6451 // add the installer to the resolve list 6452 if (DEBUG_EPHEMERAL) { 6453 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6454 } 6455 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6456 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6457 info.activityInfo.packageName, info.activityInfo.splitName, 6458 info.activityInfo.applicationInfo.versionCode); 6459 // make sure this resolver is the default 6460 installerInfo.isDefault = true; 6461 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6462 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6463 // add a non-generic filter 6464 installerInfo.filter = new IntentFilter(); 6465 // load resources from the correct package 6466 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6467 resolveInfos.set(i, installerInfo); 6468 } 6469 continue; 6470 } 6471 // allow activities that have been explicitly exposed to ephemeral apps 6472 if (!isEphemeralApp 6473 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6474 continue; 6475 } 6476 resolveInfos.remove(i); 6477 } 6478 return resolveInfos; 6479 } 6480 6481 /** 6482 * @param resolveInfos list of resolve infos in descending priority order 6483 * @return if the list contains a resolve info with non-negative priority 6484 */ 6485 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6486 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6487 } 6488 6489 private static boolean hasWebURI(Intent intent) { 6490 if (intent.getData() == null) { 6491 return false; 6492 } 6493 final String scheme = intent.getScheme(); 6494 if (TextUtils.isEmpty(scheme)) { 6495 return false; 6496 } 6497 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6498 } 6499 6500 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6501 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6502 int userId) { 6503 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6504 6505 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6506 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6507 candidates.size()); 6508 } 6509 6510 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6511 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6512 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6513 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6514 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6515 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6516 6517 synchronized (mPackages) { 6518 final int count = candidates.size(); 6519 // First, try to use linked apps. Partition the candidates into four lists: 6520 // one for the final results, one for the "do not use ever", one for "undefined status" 6521 // and finally one for "browser app type". 6522 for (int n=0; n<count; n++) { 6523 ResolveInfo info = candidates.get(n); 6524 String packageName = info.activityInfo.packageName; 6525 PackageSetting ps = mSettings.mPackages.get(packageName); 6526 if (ps != null) { 6527 // Add to the special match all list (Browser use case) 6528 if (info.handleAllWebDataURI) { 6529 matchAllList.add(info); 6530 continue; 6531 } 6532 // Try to get the status from User settings first 6533 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6534 int status = (int)(packedStatus >> 32); 6535 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6536 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6537 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6538 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6539 + " : linkgen=" + linkGeneration); 6540 } 6541 // Use link-enabled generation as preferredOrder, i.e. 6542 // prefer newly-enabled over earlier-enabled. 6543 info.preferredOrder = linkGeneration; 6544 alwaysList.add(info); 6545 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6546 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6547 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6548 } 6549 neverList.add(info); 6550 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6551 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6552 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6553 } 6554 alwaysAskList.add(info); 6555 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6556 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6557 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6558 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6559 } 6560 undefinedList.add(info); 6561 } 6562 } 6563 } 6564 6565 // We'll want to include browser possibilities in a few cases 6566 boolean includeBrowser = false; 6567 6568 // First try to add the "always" resolution(s) for the current user, if any 6569 if (alwaysList.size() > 0) { 6570 result.addAll(alwaysList); 6571 } else { 6572 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6573 result.addAll(undefinedList); 6574 // Maybe add one for the other profile. 6575 if (xpDomainInfo != null && ( 6576 xpDomainInfo.bestDomainVerificationStatus 6577 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6578 result.add(xpDomainInfo.resolveInfo); 6579 } 6580 includeBrowser = true; 6581 } 6582 6583 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6584 // If there were 'always' entries their preferred order has been set, so we also 6585 // back that off to make the alternatives equivalent 6586 if (alwaysAskList.size() > 0) { 6587 for (ResolveInfo i : result) { 6588 i.preferredOrder = 0; 6589 } 6590 result.addAll(alwaysAskList); 6591 includeBrowser = true; 6592 } 6593 6594 if (includeBrowser) { 6595 // Also add browsers (all of them or only the default one) 6596 if (DEBUG_DOMAIN_VERIFICATION) { 6597 Slog.v(TAG, " ...including browsers in candidate set"); 6598 } 6599 if ((matchFlags & MATCH_ALL) != 0) { 6600 result.addAll(matchAllList); 6601 } else { 6602 // Browser/generic handling case. If there's a default browser, go straight 6603 // to that (but only if there is no other higher-priority match). 6604 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6605 int maxMatchPrio = 0; 6606 ResolveInfo defaultBrowserMatch = null; 6607 final int numCandidates = matchAllList.size(); 6608 for (int n = 0; n < numCandidates; n++) { 6609 ResolveInfo info = matchAllList.get(n); 6610 // track the highest overall match priority... 6611 if (info.priority > maxMatchPrio) { 6612 maxMatchPrio = info.priority; 6613 } 6614 // ...and the highest-priority default browser match 6615 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6616 if (defaultBrowserMatch == null 6617 || (defaultBrowserMatch.priority < info.priority)) { 6618 if (debug) { 6619 Slog.v(TAG, "Considering default browser match " + info); 6620 } 6621 defaultBrowserMatch = info; 6622 } 6623 } 6624 } 6625 if (defaultBrowserMatch != null 6626 && defaultBrowserMatch.priority >= maxMatchPrio 6627 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6628 { 6629 if (debug) { 6630 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6631 } 6632 result.add(defaultBrowserMatch); 6633 } else { 6634 result.addAll(matchAllList); 6635 } 6636 } 6637 6638 // If there is nothing selected, add all candidates and remove the ones that the user 6639 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6640 if (result.size() == 0) { 6641 result.addAll(candidates); 6642 result.removeAll(neverList); 6643 } 6644 } 6645 } 6646 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6647 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6648 result.size()); 6649 for (ResolveInfo info : result) { 6650 Slog.v(TAG, " + " + info.activityInfo); 6651 } 6652 } 6653 return result; 6654 } 6655 6656 // Returns a packed value as a long: 6657 // 6658 // high 'int'-sized word: link status: undefined/ask/never/always. 6659 // low 'int'-sized word: relative priority among 'always' results. 6660 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6661 long result = ps.getDomainVerificationStatusForUser(userId); 6662 // if none available, get the master status 6663 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6664 if (ps.getIntentFilterVerificationInfo() != null) { 6665 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6666 } 6667 } 6668 return result; 6669 } 6670 6671 private ResolveInfo querySkipCurrentProfileIntents( 6672 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6673 int flags, int sourceUserId) { 6674 if (matchingFilters != null) { 6675 int size = matchingFilters.size(); 6676 for (int i = 0; i < size; i ++) { 6677 CrossProfileIntentFilter filter = matchingFilters.get(i); 6678 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6679 // Checking if there are activities in the target user that can handle the 6680 // intent. 6681 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6682 resolvedType, flags, sourceUserId); 6683 if (resolveInfo != null) { 6684 return resolveInfo; 6685 } 6686 } 6687 } 6688 } 6689 return null; 6690 } 6691 6692 // Return matching ResolveInfo in target user if any. 6693 private ResolveInfo queryCrossProfileIntents( 6694 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6695 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6696 if (matchingFilters != null) { 6697 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6698 // match the same intent. For performance reasons, it is better not to 6699 // run queryIntent twice for the same userId 6700 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6701 int size = matchingFilters.size(); 6702 for (int i = 0; i < size; i++) { 6703 CrossProfileIntentFilter filter = matchingFilters.get(i); 6704 int targetUserId = filter.getTargetUserId(); 6705 boolean skipCurrentProfile = 6706 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6707 boolean skipCurrentProfileIfNoMatchFound = 6708 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6709 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6710 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6711 // Checking if there are activities in the target user that can handle the 6712 // intent. 6713 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6714 resolvedType, flags, sourceUserId); 6715 if (resolveInfo != null) return resolveInfo; 6716 alreadyTriedUserIds.put(targetUserId, true); 6717 } 6718 } 6719 } 6720 return null; 6721 } 6722 6723 /** 6724 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6725 * will forward the intent to the filter's target user. 6726 * Otherwise, returns null. 6727 */ 6728 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6729 String resolvedType, int flags, int sourceUserId) { 6730 int targetUserId = filter.getTargetUserId(); 6731 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6732 resolvedType, flags, targetUserId); 6733 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6734 // If all the matches in the target profile are suspended, return null. 6735 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6736 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6737 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6738 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6739 targetUserId); 6740 } 6741 } 6742 } 6743 return null; 6744 } 6745 6746 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6747 int sourceUserId, int targetUserId) { 6748 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6749 long ident = Binder.clearCallingIdentity(); 6750 boolean targetIsProfile; 6751 try { 6752 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6753 } finally { 6754 Binder.restoreCallingIdentity(ident); 6755 } 6756 String className; 6757 if (targetIsProfile) { 6758 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6759 } else { 6760 className = FORWARD_INTENT_TO_PARENT; 6761 } 6762 ComponentName forwardingActivityComponentName = new ComponentName( 6763 mAndroidApplication.packageName, className); 6764 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6765 sourceUserId); 6766 if (!targetIsProfile) { 6767 forwardingActivityInfo.showUserIcon = targetUserId; 6768 forwardingResolveInfo.noResourceId = true; 6769 } 6770 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6771 forwardingResolveInfo.priority = 0; 6772 forwardingResolveInfo.preferredOrder = 0; 6773 forwardingResolveInfo.match = 0; 6774 forwardingResolveInfo.isDefault = true; 6775 forwardingResolveInfo.filter = filter; 6776 forwardingResolveInfo.targetUserId = targetUserId; 6777 return forwardingResolveInfo; 6778 } 6779 6780 @Override 6781 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6782 Intent[] specifics, String[] specificTypes, Intent intent, 6783 String resolvedType, int flags, int userId) { 6784 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6785 specificTypes, intent, resolvedType, flags, userId)); 6786 } 6787 6788 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6789 Intent[] specifics, String[] specificTypes, Intent intent, 6790 String resolvedType, int flags, int userId) { 6791 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6792 flags = updateFlagsForResolve(flags, userId, intent, false); 6793 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6794 false /* requireFullPermission */, false /* checkShell */, 6795 "query intent activity options"); 6796 final String resultsAction = intent.getAction(); 6797 6798 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6799 | PackageManager.GET_RESOLVED_FILTER, userId); 6800 6801 if (DEBUG_INTENT_MATCHING) { 6802 Log.v(TAG, "Query " + intent + ": " + results); 6803 } 6804 6805 int specificsPos = 0; 6806 int N; 6807 6808 // todo: note that the algorithm used here is O(N^2). This 6809 // isn't a problem in our current environment, but if we start running 6810 // into situations where we have more than 5 or 10 matches then this 6811 // should probably be changed to something smarter... 6812 6813 // First we go through and resolve each of the specific items 6814 // that were supplied, taking care of removing any corresponding 6815 // duplicate items in the generic resolve list. 6816 if (specifics != null) { 6817 for (int i=0; i<specifics.length; i++) { 6818 final Intent sintent = specifics[i]; 6819 if (sintent == null) { 6820 continue; 6821 } 6822 6823 if (DEBUG_INTENT_MATCHING) { 6824 Log.v(TAG, "Specific #" + i + ": " + sintent); 6825 } 6826 6827 String action = sintent.getAction(); 6828 if (resultsAction != null && resultsAction.equals(action)) { 6829 // If this action was explicitly requested, then don't 6830 // remove things that have it. 6831 action = null; 6832 } 6833 6834 ResolveInfo ri = null; 6835 ActivityInfo ai = null; 6836 6837 ComponentName comp = sintent.getComponent(); 6838 if (comp == null) { 6839 ri = resolveIntent( 6840 sintent, 6841 specificTypes != null ? specificTypes[i] : null, 6842 flags, userId); 6843 if (ri == null) { 6844 continue; 6845 } 6846 if (ri == mResolveInfo) { 6847 // ACK! Must do something better with this. 6848 } 6849 ai = ri.activityInfo; 6850 comp = new ComponentName(ai.applicationInfo.packageName, 6851 ai.name); 6852 } else { 6853 ai = getActivityInfo(comp, flags, userId); 6854 if (ai == null) { 6855 continue; 6856 } 6857 } 6858 6859 // Look for any generic query activities that are duplicates 6860 // of this specific one, and remove them from the results. 6861 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6862 N = results.size(); 6863 int j; 6864 for (j=specificsPos; j<N; j++) { 6865 ResolveInfo sri = results.get(j); 6866 if ((sri.activityInfo.name.equals(comp.getClassName()) 6867 && sri.activityInfo.applicationInfo.packageName.equals( 6868 comp.getPackageName())) 6869 || (action != null && sri.filter.matchAction(action))) { 6870 results.remove(j); 6871 if (DEBUG_INTENT_MATCHING) Log.v( 6872 TAG, "Removing duplicate item from " + j 6873 + " due to specific " + specificsPos); 6874 if (ri == null) { 6875 ri = sri; 6876 } 6877 j--; 6878 N--; 6879 } 6880 } 6881 6882 // Add this specific item to its proper place. 6883 if (ri == null) { 6884 ri = new ResolveInfo(); 6885 ri.activityInfo = ai; 6886 } 6887 results.add(specificsPos, ri); 6888 ri.specificIndex = i; 6889 specificsPos++; 6890 } 6891 } 6892 6893 // Now we go through the remaining generic results and remove any 6894 // duplicate actions that are found here. 6895 N = results.size(); 6896 for (int i=specificsPos; i<N-1; i++) { 6897 final ResolveInfo rii = results.get(i); 6898 if (rii.filter == null) { 6899 continue; 6900 } 6901 6902 // Iterate over all of the actions of this result's intent 6903 // filter... typically this should be just one. 6904 final Iterator<String> it = rii.filter.actionsIterator(); 6905 if (it == null) { 6906 continue; 6907 } 6908 while (it.hasNext()) { 6909 final String action = it.next(); 6910 if (resultsAction != null && resultsAction.equals(action)) { 6911 // If this action was explicitly requested, then don't 6912 // remove things that have it. 6913 continue; 6914 } 6915 for (int j=i+1; j<N; j++) { 6916 final ResolveInfo rij = results.get(j); 6917 if (rij.filter != null && rij.filter.hasAction(action)) { 6918 results.remove(j); 6919 if (DEBUG_INTENT_MATCHING) Log.v( 6920 TAG, "Removing duplicate item from " + j 6921 + " due to action " + action + " at " + i); 6922 j--; 6923 N--; 6924 } 6925 } 6926 } 6927 6928 // If the caller didn't request filter information, drop it now 6929 // so we don't have to marshall/unmarshall it. 6930 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6931 rii.filter = null; 6932 } 6933 } 6934 6935 // Filter out the caller activity if so requested. 6936 if (caller != null) { 6937 N = results.size(); 6938 for (int i=0; i<N; i++) { 6939 ActivityInfo ainfo = results.get(i).activityInfo; 6940 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6941 && caller.getClassName().equals(ainfo.name)) { 6942 results.remove(i); 6943 break; 6944 } 6945 } 6946 } 6947 6948 // If the caller didn't request filter information, 6949 // drop them now so we don't have to 6950 // marshall/unmarshall it. 6951 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6952 N = results.size(); 6953 for (int i=0; i<N; i++) { 6954 results.get(i).filter = null; 6955 } 6956 } 6957 6958 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6959 return results; 6960 } 6961 6962 @Override 6963 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6964 String resolvedType, int flags, int userId) { 6965 return new ParceledListSlice<>( 6966 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6967 } 6968 6969 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6970 String resolvedType, int flags, int userId) { 6971 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6972 flags = updateFlagsForResolve(flags, userId, intent, false); 6973 ComponentName comp = intent.getComponent(); 6974 if (comp == null) { 6975 if (intent.getSelector() != null) { 6976 intent = intent.getSelector(); 6977 comp = intent.getComponent(); 6978 } 6979 } 6980 if (comp != null) { 6981 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6982 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6983 if (ai != null) { 6984 ResolveInfo ri = new ResolveInfo(); 6985 ri.activityInfo = ai; 6986 list.add(ri); 6987 } 6988 return list; 6989 } 6990 6991 // reader 6992 synchronized (mPackages) { 6993 String pkgName = intent.getPackage(); 6994 if (pkgName == null) { 6995 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6996 } 6997 final PackageParser.Package pkg = mPackages.get(pkgName); 6998 if (pkg != null) { 6999 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7000 userId); 7001 } 7002 return Collections.emptyList(); 7003 } 7004 } 7005 7006 @Override 7007 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7008 if (!sUserManager.exists(userId)) return null; 7009 flags = updateFlagsForResolve(flags, userId, intent, false); 7010 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 7011 if (query != null) { 7012 if (query.size() >= 1) { 7013 // If there is more than one service with the same priority, 7014 // just arbitrarily pick the first one. 7015 return query.get(0); 7016 } 7017 } 7018 return null; 7019 } 7020 7021 @Override 7022 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7023 String resolvedType, int flags, int userId) { 7024 return new ParceledListSlice<>( 7025 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 7026 } 7027 7028 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7029 String resolvedType, int flags, int userId) { 7030 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7031 flags = updateFlagsForResolve(flags, userId, intent, false); 7032 ComponentName comp = intent.getComponent(); 7033 if (comp == null) { 7034 if (intent.getSelector() != null) { 7035 intent = intent.getSelector(); 7036 comp = intent.getComponent(); 7037 } 7038 } 7039 if (comp != null) { 7040 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7041 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7042 if (si != null) { 7043 final ResolveInfo ri = new ResolveInfo(); 7044 ri.serviceInfo = si; 7045 list.add(ri); 7046 } 7047 return list; 7048 } 7049 7050 // reader 7051 synchronized (mPackages) { 7052 String pkgName = intent.getPackage(); 7053 if (pkgName == null) { 7054 return mServices.queryIntent(intent, resolvedType, flags, userId); 7055 } 7056 final PackageParser.Package pkg = mPackages.get(pkgName); 7057 if (pkg != null) { 7058 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7059 userId); 7060 } 7061 return Collections.emptyList(); 7062 } 7063 } 7064 7065 @Override 7066 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7067 String resolvedType, int flags, int userId) { 7068 return new ParceledListSlice<>( 7069 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7070 } 7071 7072 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7073 Intent intent, String resolvedType, int flags, int userId) { 7074 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7075 flags = updateFlagsForResolve(flags, userId, intent, false); 7076 ComponentName comp = intent.getComponent(); 7077 if (comp == null) { 7078 if (intent.getSelector() != null) { 7079 intent = intent.getSelector(); 7080 comp = intent.getComponent(); 7081 } 7082 } 7083 if (comp != null) { 7084 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7085 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7086 if (pi != null) { 7087 final ResolveInfo ri = new ResolveInfo(); 7088 ri.providerInfo = pi; 7089 list.add(ri); 7090 } 7091 return list; 7092 } 7093 7094 // reader 7095 synchronized (mPackages) { 7096 String pkgName = intent.getPackage(); 7097 if (pkgName == null) { 7098 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7099 } 7100 final PackageParser.Package pkg = mPackages.get(pkgName); 7101 if (pkg != null) { 7102 return mProviders.queryIntentForPackage( 7103 intent, resolvedType, flags, pkg.providers, userId); 7104 } 7105 return Collections.emptyList(); 7106 } 7107 } 7108 7109 @Override 7110 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7111 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7112 flags = updateFlagsForPackage(flags, userId, null); 7113 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7114 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7115 true /* requireFullPermission */, false /* checkShell */, 7116 "get installed packages"); 7117 7118 // writer 7119 synchronized (mPackages) { 7120 ArrayList<PackageInfo> list; 7121 if (listUninstalled) { 7122 list = new ArrayList<>(mSettings.mPackages.size()); 7123 for (PackageSetting ps : mSettings.mPackages.values()) { 7124 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7125 continue; 7126 } 7127 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7128 if (pi != null) { 7129 list.add(pi); 7130 } 7131 } 7132 } else { 7133 list = new ArrayList<>(mPackages.size()); 7134 for (PackageParser.Package p : mPackages.values()) { 7135 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7136 Binder.getCallingUid(), userId)) { 7137 continue; 7138 } 7139 final PackageInfo pi = generatePackageInfo((PackageSetting) 7140 p.mExtras, flags, userId); 7141 if (pi != null) { 7142 list.add(pi); 7143 } 7144 } 7145 } 7146 7147 return new ParceledListSlice<>(list); 7148 } 7149 } 7150 7151 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7152 String[] permissions, boolean[] tmp, int flags, int userId) { 7153 int numMatch = 0; 7154 final PermissionsState permissionsState = ps.getPermissionsState(); 7155 for (int i=0; i<permissions.length; i++) { 7156 final String permission = permissions[i]; 7157 if (permissionsState.hasPermission(permission, userId)) { 7158 tmp[i] = true; 7159 numMatch++; 7160 } else { 7161 tmp[i] = false; 7162 } 7163 } 7164 if (numMatch == 0) { 7165 return; 7166 } 7167 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7168 7169 // The above might return null in cases of uninstalled apps or install-state 7170 // skew across users/profiles. 7171 if (pi != null) { 7172 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7173 if (numMatch == permissions.length) { 7174 pi.requestedPermissions = permissions; 7175 } else { 7176 pi.requestedPermissions = new String[numMatch]; 7177 numMatch = 0; 7178 for (int i=0; i<permissions.length; i++) { 7179 if (tmp[i]) { 7180 pi.requestedPermissions[numMatch] = permissions[i]; 7181 numMatch++; 7182 } 7183 } 7184 } 7185 } 7186 list.add(pi); 7187 } 7188 } 7189 7190 @Override 7191 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7192 String[] permissions, int flags, int userId) { 7193 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7194 flags = updateFlagsForPackage(flags, userId, permissions); 7195 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7196 true /* requireFullPermission */, false /* checkShell */, 7197 "get packages holding permissions"); 7198 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7199 7200 // writer 7201 synchronized (mPackages) { 7202 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7203 boolean[] tmpBools = new boolean[permissions.length]; 7204 if (listUninstalled) { 7205 for (PackageSetting ps : mSettings.mPackages.values()) { 7206 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7207 userId); 7208 } 7209 } else { 7210 for (PackageParser.Package pkg : mPackages.values()) { 7211 PackageSetting ps = (PackageSetting)pkg.mExtras; 7212 if (ps != null) { 7213 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7214 userId); 7215 } 7216 } 7217 } 7218 7219 return new ParceledListSlice<PackageInfo>(list); 7220 } 7221 } 7222 7223 @Override 7224 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7225 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7226 flags = updateFlagsForApplication(flags, userId, null); 7227 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7228 7229 // writer 7230 synchronized (mPackages) { 7231 ArrayList<ApplicationInfo> list; 7232 if (listUninstalled) { 7233 list = new ArrayList<>(mSettings.mPackages.size()); 7234 for (PackageSetting ps : mSettings.mPackages.values()) { 7235 ApplicationInfo ai; 7236 int effectiveFlags = flags; 7237 if (ps.isSystem()) { 7238 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7239 } 7240 if (ps.pkg != null) { 7241 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7242 continue; 7243 } 7244 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7245 ps.readUserState(userId), userId); 7246 if (ai != null) { 7247 rebaseEnabledOverlays(ai, userId); 7248 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7249 } 7250 } else { 7251 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7252 // and already converts to externally visible package name 7253 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7254 Binder.getCallingUid(), effectiveFlags, userId); 7255 } 7256 if (ai != null) { 7257 list.add(ai); 7258 } 7259 } 7260 } else { 7261 list = new ArrayList<>(mPackages.size()); 7262 for (PackageParser.Package p : mPackages.values()) { 7263 if (p.mExtras != null) { 7264 PackageSetting ps = (PackageSetting) p.mExtras; 7265 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7266 continue; 7267 } 7268 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7269 ps.readUserState(userId), userId); 7270 if (ai != null) { 7271 rebaseEnabledOverlays(ai, userId); 7272 ai.packageName = resolveExternalPackageNameLPr(p); 7273 list.add(ai); 7274 } 7275 } 7276 } 7277 } 7278 7279 return new ParceledListSlice<>(list); 7280 } 7281 } 7282 7283 @Override 7284 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7285 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7286 return null; 7287 } 7288 7289 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7290 "getEphemeralApplications"); 7291 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7292 true /* requireFullPermission */, false /* checkShell */, 7293 "getEphemeralApplications"); 7294 synchronized (mPackages) { 7295 List<InstantAppInfo> instantApps = mInstantAppRegistry 7296 .getInstantAppsLPr(userId); 7297 if (instantApps != null) { 7298 return new ParceledListSlice<>(instantApps); 7299 } 7300 } 7301 return null; 7302 } 7303 7304 @Override 7305 public boolean isInstantApp(String packageName, int userId) { 7306 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7307 true /* requireFullPermission */, false /* checkShell */, 7308 "isInstantApp"); 7309 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7310 return false; 7311 } 7312 7313 synchronized (mPackages) { 7314 final PackageSetting ps = mSettings.mPackages.get(packageName); 7315 final boolean returnAllowed = 7316 ps != null 7317 && (isCallerSameApp(packageName) 7318 || mContext.checkCallingOrSelfPermission( 7319 android.Manifest.permission.ACCESS_INSTANT_APPS) 7320 == PERMISSION_GRANTED 7321 || mInstantAppRegistry.isInstantAccessGranted( 7322 userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId)); 7323 if (returnAllowed) { 7324 return ps.getInstantApp(userId); 7325 } 7326 } 7327 return false; 7328 } 7329 7330 @Override 7331 public byte[] getInstantAppCookie(String packageName, int userId) { 7332 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7333 return null; 7334 } 7335 7336 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7337 true /* requireFullPermission */, false /* checkShell */, 7338 "getInstantAppCookie"); 7339 if (!isCallerSameApp(packageName)) { 7340 return null; 7341 } 7342 synchronized (mPackages) { 7343 return mInstantAppRegistry.getInstantAppCookieLPw( 7344 packageName, userId); 7345 } 7346 } 7347 7348 @Override 7349 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7350 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7351 return true; 7352 } 7353 7354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7355 true /* requireFullPermission */, true /* checkShell */, 7356 "setInstantAppCookie"); 7357 if (!isCallerSameApp(packageName)) { 7358 return false; 7359 } 7360 synchronized (mPackages) { 7361 return mInstantAppRegistry.setInstantAppCookieLPw( 7362 packageName, cookie, userId); 7363 } 7364 } 7365 7366 @Override 7367 public Bitmap getInstantAppIcon(String packageName, int userId) { 7368 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7369 return null; 7370 } 7371 7372 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7373 "getInstantAppIcon"); 7374 7375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7376 true /* requireFullPermission */, false /* checkShell */, 7377 "getInstantAppIcon"); 7378 7379 synchronized (mPackages) { 7380 return mInstantAppRegistry.getInstantAppIconLPw( 7381 packageName, userId); 7382 } 7383 } 7384 7385 private boolean isCallerSameApp(String packageName) { 7386 PackageParser.Package pkg = mPackages.get(packageName); 7387 return pkg != null 7388 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7389 } 7390 7391 @Override 7392 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7393 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7394 } 7395 7396 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7397 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7398 7399 // reader 7400 synchronized (mPackages) { 7401 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7402 final int userId = UserHandle.getCallingUserId(); 7403 while (i.hasNext()) { 7404 final PackageParser.Package p = i.next(); 7405 if (p.applicationInfo == null) continue; 7406 7407 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7408 && !p.applicationInfo.isDirectBootAware(); 7409 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7410 && p.applicationInfo.isDirectBootAware(); 7411 7412 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7413 && (!mSafeMode || isSystemApp(p)) 7414 && (matchesUnaware || matchesAware)) { 7415 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7416 if (ps != null) { 7417 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7418 ps.readUserState(userId), userId); 7419 if (ai != null) { 7420 rebaseEnabledOverlays(ai, userId); 7421 finalList.add(ai); 7422 } 7423 } 7424 } 7425 } 7426 } 7427 7428 return finalList; 7429 } 7430 7431 @Override 7432 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7433 if (!sUserManager.exists(userId)) return null; 7434 flags = updateFlagsForComponent(flags, userId, name); 7435 // reader 7436 synchronized (mPackages) { 7437 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7438 PackageSetting ps = provider != null 7439 ? mSettings.mPackages.get(provider.owner.packageName) 7440 : null; 7441 return ps != null 7442 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7443 ? PackageParser.generateProviderInfo(provider, flags, 7444 ps.readUserState(userId), userId) 7445 : null; 7446 } 7447 } 7448 7449 /** 7450 * @deprecated 7451 */ 7452 @Deprecated 7453 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7454 // reader 7455 synchronized (mPackages) { 7456 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7457 .entrySet().iterator(); 7458 final int userId = UserHandle.getCallingUserId(); 7459 while (i.hasNext()) { 7460 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7461 PackageParser.Provider p = entry.getValue(); 7462 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7463 7464 if (ps != null && p.syncable 7465 && (!mSafeMode || (p.info.applicationInfo.flags 7466 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7467 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7468 ps.readUserState(userId), userId); 7469 if (info != null) { 7470 outNames.add(entry.getKey()); 7471 outInfo.add(info); 7472 } 7473 } 7474 } 7475 } 7476 } 7477 7478 @Override 7479 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7480 int uid, int flags, String metaDataKey) { 7481 final int userId = processName != null ? UserHandle.getUserId(uid) 7482 : UserHandle.getCallingUserId(); 7483 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7484 flags = updateFlagsForComponent(flags, userId, processName); 7485 7486 ArrayList<ProviderInfo> finalList = null; 7487 // reader 7488 synchronized (mPackages) { 7489 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7490 while (i.hasNext()) { 7491 final PackageParser.Provider p = i.next(); 7492 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7493 if (ps != null && p.info.authority != null 7494 && (processName == null 7495 || (p.info.processName.equals(processName) 7496 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7497 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7498 7499 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7500 // parameter. 7501 if (metaDataKey != null 7502 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7503 continue; 7504 } 7505 7506 if (finalList == null) { 7507 finalList = new ArrayList<ProviderInfo>(3); 7508 } 7509 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7510 ps.readUserState(userId), userId); 7511 if (info != null) { 7512 finalList.add(info); 7513 } 7514 } 7515 } 7516 } 7517 7518 if (finalList != null) { 7519 Collections.sort(finalList, mProviderInitOrderSorter); 7520 return new ParceledListSlice<ProviderInfo>(finalList); 7521 } 7522 7523 return ParceledListSlice.emptyList(); 7524 } 7525 7526 @Override 7527 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7528 // reader 7529 synchronized (mPackages) { 7530 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7531 return PackageParser.generateInstrumentationInfo(i, flags); 7532 } 7533 } 7534 7535 @Override 7536 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7537 String targetPackage, int flags) { 7538 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7539 } 7540 7541 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7542 int flags) { 7543 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7544 7545 // reader 7546 synchronized (mPackages) { 7547 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7548 while (i.hasNext()) { 7549 final PackageParser.Instrumentation p = i.next(); 7550 if (targetPackage == null 7551 || targetPackage.equals(p.info.targetPackage)) { 7552 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7553 flags); 7554 if (ii != null) { 7555 finalList.add(ii); 7556 } 7557 } 7558 } 7559 } 7560 7561 return finalList; 7562 } 7563 7564 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7565 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7566 try { 7567 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7568 } finally { 7569 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7570 } 7571 } 7572 7573 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7574 final File[] files = dir.listFiles(); 7575 if (ArrayUtils.isEmpty(files)) { 7576 Log.d(TAG, "No files in app dir " + dir); 7577 return; 7578 } 7579 7580 if (DEBUG_PACKAGE_SCANNING) { 7581 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7582 + " flags=0x" + Integer.toHexString(parseFlags)); 7583 } 7584 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7585 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7586 7587 // Submit files for parsing in parallel 7588 int fileCount = 0; 7589 for (File file : files) { 7590 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7591 && !PackageInstallerService.isStageName(file.getName()); 7592 if (!isPackage) { 7593 // Ignore entries which are not packages 7594 continue; 7595 } 7596 parallelPackageParser.submit(file, parseFlags); 7597 fileCount++; 7598 } 7599 7600 // Process results one by one 7601 for (; fileCount > 0; fileCount--) { 7602 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7603 Throwable throwable = parseResult.throwable; 7604 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7605 7606 if (throwable == null) { 7607 // Static shared libraries have synthetic package names 7608 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7609 renameStaticSharedLibraryPackage(parseResult.pkg); 7610 } 7611 try { 7612 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7613 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7614 currentTime, null); 7615 } 7616 } catch (PackageManagerException e) { 7617 errorCode = e.error; 7618 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7619 } 7620 } else if (throwable instanceof PackageParser.PackageParserException) { 7621 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7622 throwable; 7623 errorCode = e.error; 7624 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7625 } else { 7626 throw new IllegalStateException("Unexpected exception occurred while parsing " 7627 + parseResult.scanFile, throwable); 7628 } 7629 7630 // Delete invalid userdata apps 7631 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7632 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7633 logCriticalInfo(Log.WARN, 7634 "Deleting invalid package at " + parseResult.scanFile); 7635 removeCodePathLI(parseResult.scanFile); 7636 } 7637 } 7638 parallelPackageParser.close(); 7639 } 7640 7641 private static File getSettingsProblemFile() { 7642 File dataDir = Environment.getDataDirectory(); 7643 File systemDir = new File(dataDir, "system"); 7644 File fname = new File(systemDir, "uiderrors.txt"); 7645 return fname; 7646 } 7647 7648 static void reportSettingsProblem(int priority, String msg) { 7649 logCriticalInfo(priority, msg); 7650 } 7651 7652 static void logCriticalInfo(int priority, String msg) { 7653 Slog.println(priority, TAG, msg); 7654 EventLogTags.writePmCriticalInfo(msg); 7655 try { 7656 File fname = getSettingsProblemFile(); 7657 FileOutputStream out = new FileOutputStream(fname, true); 7658 PrintWriter pw = new FastPrintWriter(out); 7659 SimpleDateFormat formatter = new SimpleDateFormat(); 7660 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7661 pw.println(dateString + ": " + msg); 7662 pw.close(); 7663 FileUtils.setPermissions( 7664 fname.toString(), 7665 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7666 -1, -1); 7667 } catch (java.io.IOException e) { 7668 } 7669 } 7670 7671 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7672 if (srcFile.isDirectory()) { 7673 final File baseFile = new File(pkg.baseCodePath); 7674 long maxModifiedTime = baseFile.lastModified(); 7675 if (pkg.splitCodePaths != null) { 7676 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7677 final File splitFile = new File(pkg.splitCodePaths[i]); 7678 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7679 } 7680 } 7681 return maxModifiedTime; 7682 } 7683 return srcFile.lastModified(); 7684 } 7685 7686 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7687 final int policyFlags) throws PackageManagerException { 7688 // When upgrading from pre-N MR1, verify the package time stamp using the package 7689 // directory and not the APK file. 7690 final long lastModifiedTime = mIsPreNMR1Upgrade 7691 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7692 if (ps != null 7693 && ps.codePath.equals(srcFile) 7694 && ps.timeStamp == lastModifiedTime 7695 && !isCompatSignatureUpdateNeeded(pkg) 7696 && !isRecoverSignatureUpdateNeeded(pkg)) { 7697 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7698 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7699 ArraySet<PublicKey> signingKs; 7700 synchronized (mPackages) { 7701 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7702 } 7703 if (ps.signatures.mSignatures != null 7704 && ps.signatures.mSignatures.length != 0 7705 && signingKs != null) { 7706 // Optimization: reuse the existing cached certificates 7707 // if the package appears to be unchanged. 7708 pkg.mSignatures = ps.signatures.mSignatures; 7709 pkg.mSigningKeys = signingKs; 7710 return; 7711 } 7712 7713 Slog.w(TAG, "PackageSetting for " + ps.name 7714 + " is missing signatures. Collecting certs again to recover them."); 7715 } else { 7716 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7717 } 7718 7719 try { 7720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7721 PackageParser.collectCertificates(pkg, policyFlags); 7722 } catch (PackageParserException e) { 7723 throw PackageManagerException.from(e); 7724 } finally { 7725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7726 } 7727 } 7728 7729 /** 7730 * Traces a package scan. 7731 * @see #scanPackageLI(File, int, int, long, UserHandle) 7732 */ 7733 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7734 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7735 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7736 try { 7737 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7738 } finally { 7739 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7740 } 7741 } 7742 7743 /** 7744 * Scans a package and returns the newly parsed package. 7745 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7746 */ 7747 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7748 long currentTime, UserHandle user) throws PackageManagerException { 7749 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7750 PackageParser pp = new PackageParser(); 7751 pp.setSeparateProcesses(mSeparateProcesses); 7752 pp.setOnlyCoreApps(mOnlyCore); 7753 pp.setDisplayMetrics(mMetrics); 7754 pp.setCallback(mPackageParserCallback); 7755 7756 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7757 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7758 } 7759 7760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7761 final PackageParser.Package pkg; 7762 try { 7763 pkg = pp.parsePackage(scanFile, parseFlags); 7764 } catch (PackageParserException e) { 7765 throw PackageManagerException.from(e); 7766 } finally { 7767 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7768 } 7769 7770 // Static shared libraries have synthetic package names 7771 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7772 renameStaticSharedLibraryPackage(pkg); 7773 } 7774 7775 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7776 } 7777 7778 /** 7779 * Scans a package and returns the newly parsed package. 7780 * @throws PackageManagerException on a parse error. 7781 */ 7782 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7783 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7784 throws PackageManagerException { 7785 // If the package has children and this is the first dive in the function 7786 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7787 // packages (parent and children) would be successfully scanned before the 7788 // actual scan since scanning mutates internal state and we want to atomically 7789 // install the package and its children. 7790 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7791 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7792 scanFlags |= SCAN_CHECK_ONLY; 7793 } 7794 } else { 7795 scanFlags &= ~SCAN_CHECK_ONLY; 7796 } 7797 7798 // Scan the parent 7799 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7800 scanFlags, currentTime, user); 7801 7802 // Scan the children 7803 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7804 for (int i = 0; i < childCount; i++) { 7805 PackageParser.Package childPackage = pkg.childPackages.get(i); 7806 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7807 currentTime, user); 7808 } 7809 7810 7811 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7812 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7813 } 7814 7815 return scannedPkg; 7816 } 7817 7818 /** 7819 * Scans a package and returns the newly parsed package. 7820 * @throws PackageManagerException on a parse error. 7821 */ 7822 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7823 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7824 throws PackageManagerException { 7825 PackageSetting ps = null; 7826 PackageSetting updatedPkg; 7827 // reader 7828 synchronized (mPackages) { 7829 // Look to see if we already know about this package. 7830 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7831 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7832 // This package has been renamed to its original name. Let's 7833 // use that. 7834 ps = mSettings.getPackageLPr(oldName); 7835 } 7836 // If there was no original package, see one for the real package name. 7837 if (ps == null) { 7838 ps = mSettings.getPackageLPr(pkg.packageName); 7839 } 7840 // Check to see if this package could be hiding/updating a system 7841 // package. Must look for it either under the original or real 7842 // package name depending on our state. 7843 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7844 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7845 7846 // If this is a package we don't know about on the system partition, we 7847 // may need to remove disabled child packages on the system partition 7848 // or may need to not add child packages if the parent apk is updated 7849 // on the data partition and no longer defines this child package. 7850 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7851 // If this is a parent package for an updated system app and this system 7852 // app got an OTA update which no longer defines some of the child packages 7853 // we have to prune them from the disabled system packages. 7854 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7855 if (disabledPs != null) { 7856 final int scannedChildCount = (pkg.childPackages != null) 7857 ? pkg.childPackages.size() : 0; 7858 final int disabledChildCount = disabledPs.childPackageNames != null 7859 ? disabledPs.childPackageNames.size() : 0; 7860 for (int i = 0; i < disabledChildCount; i++) { 7861 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7862 boolean disabledPackageAvailable = false; 7863 for (int j = 0; j < scannedChildCount; j++) { 7864 PackageParser.Package childPkg = pkg.childPackages.get(j); 7865 if (childPkg.packageName.equals(disabledChildPackageName)) { 7866 disabledPackageAvailable = true; 7867 break; 7868 } 7869 } 7870 if (!disabledPackageAvailable) { 7871 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7872 } 7873 } 7874 } 7875 } 7876 } 7877 7878 boolean updatedPkgBetter = false; 7879 // First check if this is a system package that may involve an update 7880 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7881 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7882 // it needs to drop FLAG_PRIVILEGED. 7883 if (locationIsPrivileged(scanFile)) { 7884 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7885 } else { 7886 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7887 } 7888 7889 if (ps != null && !ps.codePath.equals(scanFile)) { 7890 // The path has changed from what was last scanned... check the 7891 // version of the new path against what we have stored to determine 7892 // what to do. 7893 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7894 if (pkg.mVersionCode <= ps.versionCode) { 7895 // The system package has been updated and the code path does not match 7896 // Ignore entry. Skip it. 7897 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7898 + " ignored: updated version " + ps.versionCode 7899 + " better than this " + pkg.mVersionCode); 7900 if (!updatedPkg.codePath.equals(scanFile)) { 7901 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7902 + ps.name + " changing from " + updatedPkg.codePathString 7903 + " to " + scanFile); 7904 updatedPkg.codePath = scanFile; 7905 updatedPkg.codePathString = scanFile.toString(); 7906 updatedPkg.resourcePath = scanFile; 7907 updatedPkg.resourcePathString = scanFile.toString(); 7908 } 7909 updatedPkg.pkg = pkg; 7910 updatedPkg.versionCode = pkg.mVersionCode; 7911 7912 // Update the disabled system child packages to point to the package too. 7913 final int childCount = updatedPkg.childPackageNames != null 7914 ? updatedPkg.childPackageNames.size() : 0; 7915 for (int i = 0; i < childCount; i++) { 7916 String childPackageName = updatedPkg.childPackageNames.get(i); 7917 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7918 childPackageName); 7919 if (updatedChildPkg != null) { 7920 updatedChildPkg.pkg = pkg; 7921 updatedChildPkg.versionCode = pkg.mVersionCode; 7922 } 7923 } 7924 7925 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7926 + scanFile + " ignored: updated version " + ps.versionCode 7927 + " better than this " + pkg.mVersionCode); 7928 } else { 7929 // The current app on the system partition is better than 7930 // what we have updated to on the data partition; switch 7931 // back to the system partition version. 7932 // At this point, its safely assumed that package installation for 7933 // apps in system partition will go through. If not there won't be a working 7934 // version of the app 7935 // writer 7936 synchronized (mPackages) { 7937 // Just remove the loaded entries from package lists. 7938 mPackages.remove(ps.name); 7939 } 7940 7941 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7942 + " reverting from " + ps.codePathString 7943 + ": new version " + pkg.mVersionCode 7944 + " better than installed " + ps.versionCode); 7945 7946 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7947 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7948 synchronized (mInstallLock) { 7949 args.cleanUpResourcesLI(); 7950 } 7951 synchronized (mPackages) { 7952 mSettings.enableSystemPackageLPw(ps.name); 7953 } 7954 updatedPkgBetter = true; 7955 } 7956 } 7957 } 7958 7959 if (updatedPkg != null) { 7960 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7961 // initially 7962 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7963 7964 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7965 // flag set initially 7966 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7967 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7968 } 7969 } 7970 7971 // Verify certificates against what was last scanned 7972 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7973 7974 /* 7975 * A new system app appeared, but we already had a non-system one of the 7976 * same name installed earlier. 7977 */ 7978 boolean shouldHideSystemApp = false; 7979 if (updatedPkg == null && ps != null 7980 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7981 /* 7982 * Check to make sure the signatures match first. If they don't, 7983 * wipe the installed application and its data. 7984 */ 7985 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7986 != PackageManager.SIGNATURE_MATCH) { 7987 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7988 + " signatures don't match existing userdata copy; removing"); 7989 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7990 "scanPackageInternalLI")) { 7991 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7992 } 7993 ps = null; 7994 } else { 7995 /* 7996 * If the newly-added system app is an older version than the 7997 * already installed version, hide it. It will be scanned later 7998 * and re-added like an update. 7999 */ 8000 if (pkg.mVersionCode <= ps.versionCode) { 8001 shouldHideSystemApp = true; 8002 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8003 + " but new version " + pkg.mVersionCode + " better than installed " 8004 + ps.versionCode + "; hiding system"); 8005 } else { 8006 /* 8007 * The newly found system app is a newer version that the 8008 * one previously installed. Simply remove the 8009 * already-installed application and replace it with our own 8010 * while keeping the application data. 8011 */ 8012 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8013 + " reverting from " + ps.codePathString + ": new version " 8014 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8015 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8016 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8017 synchronized (mInstallLock) { 8018 args.cleanUpResourcesLI(); 8019 } 8020 } 8021 } 8022 } 8023 8024 // The apk is forward locked (not public) if its code and resources 8025 // are kept in different files. (except for app in either system or 8026 // vendor path). 8027 // TODO grab this value from PackageSettings 8028 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8029 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8030 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8031 } 8032 } 8033 8034 // TODO: extend to support forward-locked splits 8035 String resourcePath = null; 8036 String baseResourcePath = null; 8037 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8038 if (ps != null && ps.resourcePathString != null) { 8039 resourcePath = ps.resourcePathString; 8040 baseResourcePath = ps.resourcePathString; 8041 } else { 8042 // Should not happen at all. Just log an error. 8043 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8044 } 8045 } else { 8046 resourcePath = pkg.codePath; 8047 baseResourcePath = pkg.baseCodePath; 8048 } 8049 8050 // Set application objects path explicitly. 8051 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8052 pkg.setApplicationInfoCodePath(pkg.codePath); 8053 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8054 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8055 pkg.setApplicationInfoResourcePath(resourcePath); 8056 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8057 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8058 8059 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8060 if (ps != null && ps.getInstantApp(userId)) { 8061 scanFlags |= SCAN_AS_INSTANT_APP; 8062 } 8063 8064 // Note that we invoke the following method only if we are about to unpack an application 8065 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8066 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8067 8068 /* 8069 * If the system app should be overridden by a previously installed 8070 * data, hide the system app now and let the /data/app scan pick it up 8071 * again. 8072 */ 8073 if (shouldHideSystemApp) { 8074 synchronized (mPackages) { 8075 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8076 } 8077 } 8078 8079 return scannedPkg; 8080 } 8081 8082 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8083 // Derive the new package synthetic package name 8084 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8085 + pkg.staticSharedLibVersion); 8086 } 8087 8088 private static String fixProcessName(String defProcessName, 8089 String processName) { 8090 if (processName == null) { 8091 return defProcessName; 8092 } 8093 return processName; 8094 } 8095 8096 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8097 throws PackageManagerException { 8098 if (pkgSetting.signatures.mSignatures != null) { 8099 // Already existing package. Make sure signatures match 8100 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8101 == PackageManager.SIGNATURE_MATCH; 8102 if (!match) { 8103 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8104 == PackageManager.SIGNATURE_MATCH; 8105 } 8106 if (!match) { 8107 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8108 == PackageManager.SIGNATURE_MATCH; 8109 } 8110 if (!match) { 8111 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8112 + pkg.packageName + " signatures do not match the " 8113 + "previously installed version; ignoring!"); 8114 } 8115 } 8116 8117 // Check for shared user signatures 8118 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8119 // Already existing package. Make sure signatures match 8120 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8121 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8122 if (!match) { 8123 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8124 == PackageManager.SIGNATURE_MATCH; 8125 } 8126 if (!match) { 8127 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8128 == PackageManager.SIGNATURE_MATCH; 8129 } 8130 if (!match) { 8131 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8132 "Package " + pkg.packageName 8133 + " has no signatures that match those in shared user " 8134 + pkgSetting.sharedUser.name + "; ignoring!"); 8135 } 8136 } 8137 } 8138 8139 /** 8140 * Enforces that only the system UID or root's UID can call a method exposed 8141 * via Binder. 8142 * 8143 * @param message used as message if SecurityException is thrown 8144 * @throws SecurityException if the caller is not system or root 8145 */ 8146 private static final void enforceSystemOrRoot(String message) { 8147 final int uid = Binder.getCallingUid(); 8148 if (uid != Process.SYSTEM_UID && uid != 0) { 8149 throw new SecurityException(message); 8150 } 8151 } 8152 8153 @Override 8154 public void performFstrimIfNeeded() { 8155 enforceSystemOrRoot("Only the system can request fstrim"); 8156 8157 // Before everything else, see whether we need to fstrim. 8158 try { 8159 IStorageManager sm = PackageHelper.getStorageManager(); 8160 if (sm != null) { 8161 boolean doTrim = false; 8162 final long interval = android.provider.Settings.Global.getLong( 8163 mContext.getContentResolver(), 8164 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8165 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8166 if (interval > 0) { 8167 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8168 if (timeSinceLast > interval) { 8169 doTrim = true; 8170 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8171 + "; running immediately"); 8172 } 8173 } 8174 if (doTrim) { 8175 final boolean dexOptDialogShown; 8176 synchronized (mPackages) { 8177 dexOptDialogShown = mDexOptDialogShown; 8178 } 8179 if (!isFirstBoot() && dexOptDialogShown) { 8180 try { 8181 ActivityManager.getService().showBootMessage( 8182 mContext.getResources().getString( 8183 R.string.android_upgrading_fstrim), true); 8184 } catch (RemoteException e) { 8185 } 8186 } 8187 sm.runMaintenance(); 8188 } 8189 } else { 8190 Slog.e(TAG, "storageManager service unavailable!"); 8191 } 8192 } catch (RemoteException e) { 8193 // Can't happen; StorageManagerService is local 8194 } 8195 } 8196 8197 @Override 8198 public void updatePackagesIfNeeded() { 8199 enforceSystemOrRoot("Only the system can request package update"); 8200 8201 // We need to re-extract after an OTA. 8202 boolean causeUpgrade = isUpgrade(); 8203 8204 // First boot or factory reset. 8205 // Note: we also handle devices that are upgrading to N right now as if it is their 8206 // first boot, as they do not have profile data. 8207 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8208 8209 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8210 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8211 8212 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8213 return; 8214 } 8215 8216 List<PackageParser.Package> pkgs; 8217 synchronized (mPackages) { 8218 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8219 } 8220 8221 final long startTime = System.nanoTime(); 8222 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8223 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8224 8225 final int elapsedTimeSeconds = 8226 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8227 8228 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8229 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8230 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8231 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8232 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8233 } 8234 8235 /** 8236 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8237 * containing statistics about the invocation. The array consists of three elements, 8238 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8239 * and {@code numberOfPackagesFailed}. 8240 */ 8241 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8242 String compilerFilter) { 8243 8244 int numberOfPackagesVisited = 0; 8245 int numberOfPackagesOptimized = 0; 8246 int numberOfPackagesSkipped = 0; 8247 int numberOfPackagesFailed = 0; 8248 final int numberOfPackagesToDexopt = pkgs.size(); 8249 8250 for (PackageParser.Package pkg : pkgs) { 8251 numberOfPackagesVisited++; 8252 8253 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8254 if (DEBUG_DEXOPT) { 8255 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8256 } 8257 numberOfPackagesSkipped++; 8258 continue; 8259 } 8260 8261 if (DEBUG_DEXOPT) { 8262 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8263 numberOfPackagesToDexopt + ": " + pkg.packageName); 8264 } 8265 8266 if (showDialog) { 8267 try { 8268 ActivityManager.getService().showBootMessage( 8269 mContext.getResources().getString(R.string.android_upgrading_apk, 8270 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8271 } catch (RemoteException e) { 8272 } 8273 synchronized (mPackages) { 8274 mDexOptDialogShown = true; 8275 } 8276 } 8277 8278 // If the OTA updates a system app which was previously preopted to a non-preopted state 8279 // the app might end up being verified at runtime. That's because by default the apps 8280 // are verify-profile but for preopted apps there's no profile. 8281 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8282 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8283 // filter (by default interpret-only). 8284 // Note that at this stage unused apps are already filtered. 8285 if (isSystemApp(pkg) && 8286 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8287 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8288 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8289 } 8290 8291 // checkProfiles is false to avoid merging profiles during boot which 8292 // might interfere with background compilation (b/28612421). 8293 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8294 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8295 // trade-off worth doing to save boot time work. 8296 int dexOptStatus = performDexOptTraced(pkg.packageName, 8297 false /* checkProfiles */, 8298 compilerFilter, 8299 false /* force */); 8300 switch (dexOptStatus) { 8301 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8302 numberOfPackagesOptimized++; 8303 break; 8304 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8305 numberOfPackagesSkipped++; 8306 break; 8307 case PackageDexOptimizer.DEX_OPT_FAILED: 8308 numberOfPackagesFailed++; 8309 break; 8310 default: 8311 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8312 break; 8313 } 8314 } 8315 8316 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8317 numberOfPackagesFailed }; 8318 } 8319 8320 @Override 8321 public void notifyPackageUse(String packageName, int reason) { 8322 synchronized (mPackages) { 8323 PackageParser.Package p = mPackages.get(packageName); 8324 if (p == null) { 8325 return; 8326 } 8327 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8328 } 8329 } 8330 8331 @Override 8332 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8333 int userId = UserHandle.getCallingUserId(); 8334 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8335 if (ai == null) { 8336 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8337 + loadingPackageName + ", user=" + userId); 8338 return; 8339 } 8340 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8341 } 8342 8343 // TODO: this is not used nor needed. Delete it. 8344 @Override 8345 public boolean performDexOptIfNeeded(String packageName) { 8346 int dexOptStatus = performDexOptTraced(packageName, 8347 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8348 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8349 } 8350 8351 @Override 8352 public boolean performDexOpt(String packageName, 8353 boolean checkProfiles, int compileReason, boolean force) { 8354 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8355 getCompilerFilterForReason(compileReason), force); 8356 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8357 } 8358 8359 @Override 8360 public boolean performDexOptMode(String packageName, 8361 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8362 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8363 targetCompilerFilter, force); 8364 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8365 } 8366 8367 private int performDexOptTraced(String packageName, 8368 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8369 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8370 try { 8371 return performDexOptInternal(packageName, checkProfiles, 8372 targetCompilerFilter, force); 8373 } finally { 8374 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8375 } 8376 } 8377 8378 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8379 // if the package can now be considered up to date for the given filter. 8380 private int performDexOptInternal(String packageName, 8381 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8382 PackageParser.Package p; 8383 synchronized (mPackages) { 8384 p = mPackages.get(packageName); 8385 if (p == null) { 8386 // Package could not be found. Report failure. 8387 return PackageDexOptimizer.DEX_OPT_FAILED; 8388 } 8389 mPackageUsage.maybeWriteAsync(mPackages); 8390 mCompilerStats.maybeWriteAsync(); 8391 } 8392 long callingId = Binder.clearCallingIdentity(); 8393 try { 8394 synchronized (mInstallLock) { 8395 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8396 targetCompilerFilter, force); 8397 } 8398 } finally { 8399 Binder.restoreCallingIdentity(callingId); 8400 } 8401 } 8402 8403 public ArraySet<String> getOptimizablePackages() { 8404 ArraySet<String> pkgs = new ArraySet<String>(); 8405 synchronized (mPackages) { 8406 for (PackageParser.Package p : mPackages.values()) { 8407 if (PackageDexOptimizer.canOptimizePackage(p)) { 8408 pkgs.add(p.packageName); 8409 } 8410 } 8411 } 8412 return pkgs; 8413 } 8414 8415 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8416 boolean checkProfiles, String targetCompilerFilter, 8417 boolean force) { 8418 // Select the dex optimizer based on the force parameter. 8419 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8420 // allocate an object here. 8421 PackageDexOptimizer pdo = force 8422 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8423 : mPackageDexOptimizer; 8424 8425 // Optimize all dependencies first. Note: we ignore the return value and march on 8426 // on errors. 8427 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8428 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8429 if (!deps.isEmpty()) { 8430 for (PackageParser.Package depPackage : deps) { 8431 // TODO: Analyze and investigate if we (should) profile libraries. 8432 // Currently this will do a full compilation of the library by default. 8433 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8434 false /* checkProfiles */, 8435 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8436 getOrCreateCompilerPackageStats(depPackage), 8437 mDexManager.isUsedByOtherApps(p.packageName)); 8438 } 8439 } 8440 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8441 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8442 mDexManager.isUsedByOtherApps(p.packageName)); 8443 } 8444 8445 // Performs dexopt on the used secondary dex files belonging to the given package. 8446 // Returns true if all dex files were process successfully (which could mean either dexopt or 8447 // skip). Returns false if any of the files caused errors. 8448 @Override 8449 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8450 boolean force) { 8451 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8452 } 8453 8454 /** 8455 * Reconcile the information we have about the secondary dex files belonging to 8456 * {@code packagName} and the actual dex files. For all dex files that were 8457 * deleted, update the internal records and delete the generated oat files. 8458 */ 8459 @Override 8460 public void reconcileSecondaryDexFiles(String packageName) { 8461 mDexManager.reconcileSecondaryDexFiles(packageName); 8462 } 8463 8464 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8465 // a reference there. 8466 /*package*/ DexManager getDexManager() { 8467 return mDexManager; 8468 } 8469 8470 /** 8471 * Execute the background dexopt job immediately. 8472 */ 8473 @Override 8474 public boolean runBackgroundDexoptJob() { 8475 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8476 } 8477 8478 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8479 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8480 || p.usesStaticLibraries != null) { 8481 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8482 Set<String> collectedNames = new HashSet<>(); 8483 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8484 8485 retValue.remove(p); 8486 8487 return retValue; 8488 } else { 8489 return Collections.emptyList(); 8490 } 8491 } 8492 8493 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8494 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8495 if (!collectedNames.contains(p.packageName)) { 8496 collectedNames.add(p.packageName); 8497 collected.add(p); 8498 8499 if (p.usesLibraries != null) { 8500 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8501 null, collected, collectedNames); 8502 } 8503 if (p.usesOptionalLibraries != null) { 8504 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8505 null, collected, collectedNames); 8506 } 8507 if (p.usesStaticLibraries != null) { 8508 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8509 p.usesStaticLibrariesVersions, collected, collectedNames); 8510 } 8511 } 8512 } 8513 8514 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8515 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8516 final int libNameCount = libs.size(); 8517 for (int i = 0; i < libNameCount; i++) { 8518 String libName = libs.get(i); 8519 int version = (versions != null && versions.length == libNameCount) 8520 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8521 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8522 if (libPkg != null) { 8523 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8524 } 8525 } 8526 } 8527 8528 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8529 synchronized (mPackages) { 8530 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8531 if (libEntry != null) { 8532 return mPackages.get(libEntry.apk); 8533 } 8534 return null; 8535 } 8536 } 8537 8538 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8539 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8540 if (versionedLib == null) { 8541 return null; 8542 } 8543 return versionedLib.get(version); 8544 } 8545 8546 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8547 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8548 pkg.staticSharedLibName); 8549 if (versionedLib == null) { 8550 return null; 8551 } 8552 int previousLibVersion = -1; 8553 final int versionCount = versionedLib.size(); 8554 for (int i = 0; i < versionCount; i++) { 8555 final int libVersion = versionedLib.keyAt(i); 8556 if (libVersion < pkg.staticSharedLibVersion) { 8557 previousLibVersion = Math.max(previousLibVersion, libVersion); 8558 } 8559 } 8560 if (previousLibVersion >= 0) { 8561 return versionedLib.get(previousLibVersion); 8562 } 8563 return null; 8564 } 8565 8566 public void shutdown() { 8567 mPackageUsage.writeNow(mPackages); 8568 mCompilerStats.writeNow(); 8569 } 8570 8571 @Override 8572 public void dumpProfiles(String packageName) { 8573 PackageParser.Package pkg; 8574 synchronized (mPackages) { 8575 pkg = mPackages.get(packageName); 8576 if (pkg == null) { 8577 throw new IllegalArgumentException("Unknown package: " + packageName); 8578 } 8579 } 8580 /* Only the shell, root, or the app user should be able to dump profiles. */ 8581 int callingUid = Binder.getCallingUid(); 8582 if (callingUid != Process.SHELL_UID && 8583 callingUid != Process.ROOT_UID && 8584 callingUid != pkg.applicationInfo.uid) { 8585 throw new SecurityException("dumpProfiles"); 8586 } 8587 8588 synchronized (mInstallLock) { 8589 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8590 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8591 try { 8592 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8593 String codePaths = TextUtils.join(";", allCodePaths); 8594 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8595 } catch (InstallerException e) { 8596 Slog.w(TAG, "Failed to dump profiles", e); 8597 } 8598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8599 } 8600 } 8601 8602 @Override 8603 public void forceDexOpt(String packageName) { 8604 enforceSystemOrRoot("forceDexOpt"); 8605 8606 PackageParser.Package pkg; 8607 synchronized (mPackages) { 8608 pkg = mPackages.get(packageName); 8609 if (pkg == null) { 8610 throw new IllegalArgumentException("Unknown package: " + packageName); 8611 } 8612 } 8613 8614 synchronized (mInstallLock) { 8615 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8616 8617 // Whoever is calling forceDexOpt wants a fully compiled package. 8618 // Don't use profiles since that may cause compilation to be skipped. 8619 final int res = performDexOptInternalWithDependenciesLI(pkg, 8620 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8621 true /* force */); 8622 8623 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8624 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8625 throw new IllegalStateException("Failed to dexopt: " + res); 8626 } 8627 } 8628 } 8629 8630 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8631 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8632 Slog.w(TAG, "Unable to update from " + oldPkg.name 8633 + " to " + newPkg.packageName 8634 + ": old package not in system partition"); 8635 return false; 8636 } else if (mPackages.get(oldPkg.name) != null) { 8637 Slog.w(TAG, "Unable to update from " + oldPkg.name 8638 + " to " + newPkg.packageName 8639 + ": old package still exists"); 8640 return false; 8641 } 8642 return true; 8643 } 8644 8645 void removeCodePathLI(File codePath) { 8646 if (codePath.isDirectory()) { 8647 try { 8648 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8649 } catch (InstallerException e) { 8650 Slog.w(TAG, "Failed to remove code path", e); 8651 } 8652 } else { 8653 codePath.delete(); 8654 } 8655 } 8656 8657 private int[] resolveUserIds(int userId) { 8658 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8659 } 8660 8661 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8662 if (pkg == null) { 8663 Slog.wtf(TAG, "Package was null!", new Throwable()); 8664 return; 8665 } 8666 clearAppDataLeafLIF(pkg, userId, flags); 8667 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8668 for (int i = 0; i < childCount; i++) { 8669 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8670 } 8671 } 8672 8673 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8674 final PackageSetting ps; 8675 synchronized (mPackages) { 8676 ps = mSettings.mPackages.get(pkg.packageName); 8677 } 8678 for (int realUserId : resolveUserIds(userId)) { 8679 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8680 try { 8681 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8682 ceDataInode); 8683 } catch (InstallerException e) { 8684 Slog.w(TAG, String.valueOf(e)); 8685 } 8686 } 8687 } 8688 8689 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8690 if (pkg == null) { 8691 Slog.wtf(TAG, "Package was null!", new Throwable()); 8692 return; 8693 } 8694 destroyAppDataLeafLIF(pkg, userId, flags); 8695 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8696 for (int i = 0; i < childCount; i++) { 8697 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8698 } 8699 } 8700 8701 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8702 final PackageSetting ps; 8703 synchronized (mPackages) { 8704 ps = mSettings.mPackages.get(pkg.packageName); 8705 } 8706 for (int realUserId : resolveUserIds(userId)) { 8707 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8708 try { 8709 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8710 ceDataInode); 8711 } catch (InstallerException e) { 8712 Slog.w(TAG, String.valueOf(e)); 8713 } 8714 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8715 } 8716 } 8717 8718 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8719 if (pkg == null) { 8720 Slog.wtf(TAG, "Package was null!", new Throwable()); 8721 return; 8722 } 8723 destroyAppProfilesLeafLIF(pkg); 8724 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 8725 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8726 for (int i = 0; i < childCount; i++) { 8727 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8728 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 8729 true /* removeBaseMarker */); 8730 } 8731 } 8732 8733 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 8734 boolean removeBaseMarker) { 8735 if (pkg.isForwardLocked()) { 8736 return; 8737 } 8738 8739 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 8740 try { 8741 path = PackageManagerServiceUtils.realpath(new File(path)); 8742 } catch (IOException e) { 8743 // TODO: Should we return early here ? 8744 Slog.w(TAG, "Failed to get canonical path", e); 8745 continue; 8746 } 8747 8748 final String useMarker = path.replace('/', '@'); 8749 for (int realUserId : resolveUserIds(userId)) { 8750 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 8751 if (removeBaseMarker) { 8752 File foreignUseMark = new File(profileDir, useMarker); 8753 if (foreignUseMark.exists()) { 8754 if (!foreignUseMark.delete()) { 8755 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8756 + pkg.packageName); 8757 } 8758 } 8759 } 8760 8761 File[] markers = profileDir.listFiles(); 8762 if (markers != null) { 8763 final String searchString = "@" + pkg.packageName + "@"; 8764 // We also delete all markers that contain the package name we're 8765 // uninstalling. These are associated with secondary dex-files belonging 8766 // to the package. Reconstructing the path of these dex files is messy 8767 // in general. 8768 for (File marker : markers) { 8769 if (marker.getName().indexOf(searchString) > 0) { 8770 if (!marker.delete()) { 8771 Slog.w(TAG, "Unable to delete foreign user mark for package: " 8772 + pkg.packageName); 8773 } 8774 } 8775 } 8776 } 8777 } 8778 } 8779 } 8780 8781 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8782 try { 8783 mInstaller.destroyAppProfiles(pkg.packageName); 8784 } catch (InstallerException e) { 8785 Slog.w(TAG, String.valueOf(e)); 8786 } 8787 } 8788 8789 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8790 if (pkg == null) { 8791 Slog.wtf(TAG, "Package was null!", new Throwable()); 8792 return; 8793 } 8794 clearAppProfilesLeafLIF(pkg); 8795 // We don't remove the base foreign use marker when clearing profiles because 8796 // we will rename it when the app is updated. Unlike the actual profile contents, 8797 // the foreign use marker is good across installs. 8798 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 8799 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8800 for (int i = 0; i < childCount; i++) { 8801 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8802 } 8803 } 8804 8805 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8806 try { 8807 mInstaller.clearAppProfiles(pkg.packageName); 8808 } catch (InstallerException e) { 8809 Slog.w(TAG, String.valueOf(e)); 8810 } 8811 } 8812 8813 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8814 long lastUpdateTime) { 8815 // Set parent install/update time 8816 PackageSetting ps = (PackageSetting) pkg.mExtras; 8817 if (ps != null) { 8818 ps.firstInstallTime = firstInstallTime; 8819 ps.lastUpdateTime = lastUpdateTime; 8820 } 8821 // Set children install/update time 8822 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8823 for (int i = 0; i < childCount; i++) { 8824 PackageParser.Package childPkg = pkg.childPackages.get(i); 8825 ps = (PackageSetting) childPkg.mExtras; 8826 if (ps != null) { 8827 ps.firstInstallTime = firstInstallTime; 8828 ps.lastUpdateTime = lastUpdateTime; 8829 } 8830 } 8831 } 8832 8833 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8834 PackageParser.Package changingLib) { 8835 if (file.path != null) { 8836 usesLibraryFiles.add(file.path); 8837 return; 8838 } 8839 PackageParser.Package p = mPackages.get(file.apk); 8840 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8841 // If we are doing this while in the middle of updating a library apk, 8842 // then we need to make sure to use that new apk for determining the 8843 // dependencies here. (We haven't yet finished committing the new apk 8844 // to the package manager state.) 8845 if (p == null || p.packageName.equals(changingLib.packageName)) { 8846 p = changingLib; 8847 } 8848 } 8849 if (p != null) { 8850 usesLibraryFiles.addAll(p.getAllCodePaths()); 8851 } 8852 } 8853 8854 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8855 PackageParser.Package changingLib) throws PackageManagerException { 8856 if (pkg == null) { 8857 return; 8858 } 8859 ArraySet<String> usesLibraryFiles = null; 8860 if (pkg.usesLibraries != null) { 8861 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8862 null, null, pkg.packageName, changingLib, true, null); 8863 } 8864 if (pkg.usesStaticLibraries != null) { 8865 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8866 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8867 pkg.packageName, changingLib, true, usesLibraryFiles); 8868 } 8869 if (pkg.usesOptionalLibraries != null) { 8870 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8871 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8872 } 8873 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8874 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8875 } else { 8876 pkg.usesLibraryFiles = null; 8877 } 8878 } 8879 8880 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8881 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8882 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8883 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8884 throws PackageManagerException { 8885 final int libCount = requestedLibraries.size(); 8886 for (int i = 0; i < libCount; i++) { 8887 final String libName = requestedLibraries.get(i); 8888 final int libVersion = requiredVersions != null ? requiredVersions[i] 8889 : SharedLibraryInfo.VERSION_UNDEFINED; 8890 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8891 if (libEntry == null) { 8892 if (required) { 8893 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8894 "Package " + packageName + " requires unavailable shared library " 8895 + libName + "; failing!"); 8896 } else { 8897 Slog.w(TAG, "Package " + packageName 8898 + " desires unavailable shared library " 8899 + libName + "; ignoring!"); 8900 } 8901 } else { 8902 if (requiredVersions != null && requiredCertDigests != null) { 8903 if (libEntry.info.getVersion() != requiredVersions[i]) { 8904 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8905 "Package " + packageName + " requires unavailable static shared" 8906 + " library " + libName + " version " 8907 + libEntry.info.getVersion() + "; failing!"); 8908 } 8909 8910 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8911 if (libPkg == null) { 8912 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8913 "Package " + packageName + " requires unavailable static shared" 8914 + " library; failing!"); 8915 } 8916 8917 String expectedCertDigest = requiredCertDigests[i]; 8918 String libCertDigest = PackageUtils.computeCertSha256Digest( 8919 libPkg.mSignatures[0]); 8920 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8921 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8922 "Package " + packageName + " requires differently signed" + 8923 " static shared library; failing!"); 8924 } 8925 } 8926 8927 if (outUsedLibraries == null) { 8928 outUsedLibraries = new ArraySet<>(); 8929 } 8930 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8931 } 8932 } 8933 return outUsedLibraries; 8934 } 8935 8936 private static boolean hasString(List<String> list, List<String> which) { 8937 if (list == null) { 8938 return false; 8939 } 8940 for (int i=list.size()-1; i>=0; i--) { 8941 for (int j=which.size()-1; j>=0; j--) { 8942 if (which.get(j).equals(list.get(i))) { 8943 return true; 8944 } 8945 } 8946 } 8947 return false; 8948 } 8949 8950 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8951 PackageParser.Package changingPkg) { 8952 ArrayList<PackageParser.Package> res = null; 8953 for (PackageParser.Package pkg : mPackages.values()) { 8954 if (changingPkg != null 8955 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8956 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8957 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8958 changingPkg.staticSharedLibName)) { 8959 return null; 8960 } 8961 if (res == null) { 8962 res = new ArrayList<>(); 8963 } 8964 res.add(pkg); 8965 try { 8966 updateSharedLibrariesLPr(pkg, changingPkg); 8967 } catch (PackageManagerException e) { 8968 // If a system app update or an app and a required lib missing we 8969 // delete the package and for updated system apps keep the data as 8970 // it is better for the user to reinstall than to be in an limbo 8971 // state. Also libs disappearing under an app should never happen 8972 // - just in case. 8973 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8974 final int flags = pkg.isUpdatedSystemApp() 8975 ? PackageManager.DELETE_KEEP_DATA : 0; 8976 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8977 flags , null, true, null); 8978 } 8979 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8980 } 8981 } 8982 return res; 8983 } 8984 8985 /** 8986 * Derive the value of the {@code cpuAbiOverride} based on the provided 8987 * value and an optional stored value from the package settings. 8988 */ 8989 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8990 String cpuAbiOverride = null; 8991 8992 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8993 cpuAbiOverride = null; 8994 } else if (abiOverride != null) { 8995 cpuAbiOverride = abiOverride; 8996 } else if (settings != null) { 8997 cpuAbiOverride = settings.cpuAbiOverrideString; 8998 } 8999 9000 return cpuAbiOverride; 9001 } 9002 9003 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9004 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9005 throws PackageManagerException { 9006 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9007 // If the package has children and this is the first dive in the function 9008 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9009 // whether all packages (parent and children) would be successfully scanned 9010 // before the actual scan since scanning mutates internal state and we want 9011 // to atomically install the package and its children. 9012 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9013 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9014 scanFlags |= SCAN_CHECK_ONLY; 9015 } 9016 } else { 9017 scanFlags &= ~SCAN_CHECK_ONLY; 9018 } 9019 9020 final PackageParser.Package scannedPkg; 9021 try { 9022 // Scan the parent 9023 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9024 // Scan the children 9025 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9026 for (int i = 0; i < childCount; i++) { 9027 PackageParser.Package childPkg = pkg.childPackages.get(i); 9028 scanPackageLI(childPkg, policyFlags, 9029 scanFlags, currentTime, user); 9030 } 9031 } finally { 9032 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9033 } 9034 9035 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9036 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9037 } 9038 9039 return scannedPkg; 9040 } 9041 9042 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9043 int scanFlags, long currentTime, @Nullable UserHandle user) 9044 throws PackageManagerException { 9045 boolean success = false; 9046 try { 9047 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9048 currentTime, user); 9049 success = true; 9050 return res; 9051 } finally { 9052 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9053 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9054 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9055 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9056 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9057 } 9058 } 9059 } 9060 9061 /** 9062 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9063 */ 9064 private static boolean apkHasCode(String fileName) { 9065 StrictJarFile jarFile = null; 9066 try { 9067 jarFile = new StrictJarFile(fileName, 9068 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9069 return jarFile.findEntry("classes.dex") != null; 9070 } catch (IOException ignore) { 9071 } finally { 9072 try { 9073 if (jarFile != null) { 9074 jarFile.close(); 9075 } 9076 } catch (IOException ignore) {} 9077 } 9078 return false; 9079 } 9080 9081 /** 9082 * Enforces code policy for the package. This ensures that if an APK has 9083 * declared hasCode="true" in its manifest that the APK actually contains 9084 * code. 9085 * 9086 * @throws PackageManagerException If bytecode could not be found when it should exist 9087 */ 9088 private static void assertCodePolicy(PackageParser.Package pkg) 9089 throws PackageManagerException { 9090 final boolean shouldHaveCode = 9091 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9092 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9093 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9094 "Package " + pkg.baseCodePath + " code is missing"); 9095 } 9096 9097 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9098 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9099 final boolean splitShouldHaveCode = 9100 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9101 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9102 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9103 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9104 } 9105 } 9106 } 9107 } 9108 9109 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9110 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9111 throws PackageManagerException { 9112 if (DEBUG_PACKAGE_SCANNING) { 9113 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9114 Log.d(TAG, "Scanning package " + pkg.packageName); 9115 } 9116 9117 applyPolicy(pkg, policyFlags); 9118 9119 assertPackageIsValid(pkg, policyFlags, scanFlags); 9120 9121 // Initialize package source and resource directories 9122 final File scanFile = new File(pkg.codePath); 9123 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9124 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9125 9126 SharedUserSetting suid = null; 9127 PackageSetting pkgSetting = null; 9128 9129 // Getting the package setting may have a side-effect, so if we 9130 // are only checking if scan would succeed, stash a copy of the 9131 // old setting to restore at the end. 9132 PackageSetting nonMutatedPs = null; 9133 9134 // We keep references to the derived CPU Abis from settings in oder to reuse 9135 // them in the case where we're not upgrading or booting for the first time. 9136 String primaryCpuAbiFromSettings = null; 9137 String secondaryCpuAbiFromSettings = null; 9138 9139 // writer 9140 synchronized (mPackages) { 9141 if (pkg.mSharedUserId != null) { 9142 // SIDE EFFECTS; may potentially allocate a new shared user 9143 suid = mSettings.getSharedUserLPw( 9144 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9145 if (DEBUG_PACKAGE_SCANNING) { 9146 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9147 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9148 + "): packages=" + suid.packages); 9149 } 9150 } 9151 9152 // Check if we are renaming from an original package name. 9153 PackageSetting origPackage = null; 9154 String realName = null; 9155 if (pkg.mOriginalPackages != null) { 9156 // This package may need to be renamed to a previously 9157 // installed name. Let's check on that... 9158 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9159 if (pkg.mOriginalPackages.contains(renamed)) { 9160 // This package had originally been installed as the 9161 // original name, and we have already taken care of 9162 // transitioning to the new one. Just update the new 9163 // one to continue using the old name. 9164 realName = pkg.mRealPackage; 9165 if (!pkg.packageName.equals(renamed)) { 9166 // Callers into this function may have already taken 9167 // care of renaming the package; only do it here if 9168 // it is not already done. 9169 pkg.setPackageName(renamed); 9170 } 9171 } else { 9172 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9173 if ((origPackage = mSettings.getPackageLPr( 9174 pkg.mOriginalPackages.get(i))) != null) { 9175 // We do have the package already installed under its 9176 // original name... should we use it? 9177 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9178 // New package is not compatible with original. 9179 origPackage = null; 9180 continue; 9181 } else if (origPackage.sharedUser != null) { 9182 // Make sure uid is compatible between packages. 9183 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9184 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9185 + " to " + pkg.packageName + ": old uid " 9186 + origPackage.sharedUser.name 9187 + " differs from " + pkg.mSharedUserId); 9188 origPackage = null; 9189 continue; 9190 } 9191 // TODO: Add case when shared user id is added [b/28144775] 9192 } else { 9193 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9194 + pkg.packageName + " to old name " + origPackage.name); 9195 } 9196 break; 9197 } 9198 } 9199 } 9200 } 9201 9202 if (mTransferedPackages.contains(pkg.packageName)) { 9203 Slog.w(TAG, "Package " + pkg.packageName 9204 + " was transferred to another, but its .apk remains"); 9205 } 9206 9207 // See comments in nonMutatedPs declaration 9208 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9209 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9210 if (foundPs != null) { 9211 nonMutatedPs = new PackageSetting(foundPs); 9212 } 9213 } 9214 9215 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9216 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9217 if (foundPs != null) { 9218 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9219 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9220 } 9221 } 9222 9223 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9224 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9225 PackageManagerService.reportSettingsProblem(Log.WARN, 9226 "Package " + pkg.packageName + " shared user changed from " 9227 + (pkgSetting.sharedUser != null 9228 ? pkgSetting.sharedUser.name : "<nothing>") 9229 + " to " 9230 + (suid != null ? suid.name : "<nothing>") 9231 + "; replacing with new"); 9232 pkgSetting = null; 9233 } 9234 final PackageSetting oldPkgSetting = 9235 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9236 final PackageSetting disabledPkgSetting = 9237 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9238 9239 String[] usesStaticLibraries = null; 9240 if (pkg.usesStaticLibraries != null) { 9241 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9242 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9243 } 9244 9245 if (pkgSetting == null) { 9246 final String parentPackageName = (pkg.parentPackage != null) 9247 ? pkg.parentPackage.packageName : null; 9248 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9249 // REMOVE SharedUserSetting from method; update in a separate call 9250 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9251 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9252 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9253 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9254 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9255 true /*allowInstall*/, instantApp, parentPackageName, 9256 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9257 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9258 // SIDE EFFECTS; updates system state; move elsewhere 9259 if (origPackage != null) { 9260 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9261 } 9262 mSettings.addUserToSettingLPw(pkgSetting); 9263 } else { 9264 // REMOVE SharedUserSetting from method; update in a separate call. 9265 // 9266 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9267 // secondaryCpuAbi are not known at this point so we always update them 9268 // to null here, only to reset them at a later point. 9269 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9270 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9271 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9272 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9273 UserManagerService.getInstance(), usesStaticLibraries, 9274 pkg.usesStaticLibrariesVersions); 9275 } 9276 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9277 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9278 9279 // SIDE EFFECTS; modifies system state; move elsewhere 9280 if (pkgSetting.origPackage != null) { 9281 // If we are first transitioning from an original package, 9282 // fix up the new package's name now. We need to do this after 9283 // looking up the package under its new name, so getPackageLP 9284 // can take care of fiddling things correctly. 9285 pkg.setPackageName(origPackage.name); 9286 9287 // File a report about this. 9288 String msg = "New package " + pkgSetting.realName 9289 + " renamed to replace old package " + pkgSetting.name; 9290 reportSettingsProblem(Log.WARN, msg); 9291 9292 // Make a note of it. 9293 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9294 mTransferedPackages.add(origPackage.name); 9295 } 9296 9297 // No longer need to retain this. 9298 pkgSetting.origPackage = null; 9299 } 9300 9301 // SIDE EFFECTS; modifies system state; move elsewhere 9302 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9303 // Make a note of it. 9304 mTransferedPackages.add(pkg.packageName); 9305 } 9306 9307 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9308 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9309 } 9310 9311 if ((scanFlags & SCAN_BOOTING) == 0 9312 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9313 // Check all shared libraries and map to their actual file path. 9314 // We only do this here for apps not on a system dir, because those 9315 // are the only ones that can fail an install due to this. We 9316 // will take care of the system apps by updating all of their 9317 // library paths after the scan is done. Also during the initial 9318 // scan don't update any libs as we do this wholesale after all 9319 // apps are scanned to avoid dependency based scanning. 9320 updateSharedLibrariesLPr(pkg, null); 9321 } 9322 9323 if (mFoundPolicyFile) { 9324 SELinuxMMAC.assignSeInfoValue(pkg); 9325 } 9326 pkg.applicationInfo.uid = pkgSetting.appId; 9327 pkg.mExtras = pkgSetting; 9328 9329 9330 // Static shared libs have same package with different versions where 9331 // we internally use a synthetic package name to allow multiple versions 9332 // of the same package, therefore we need to compare signatures against 9333 // the package setting for the latest library version. 9334 PackageSetting signatureCheckPs = pkgSetting; 9335 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9336 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9337 if (libraryEntry != null) { 9338 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9339 } 9340 } 9341 9342 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9343 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9344 // We just determined the app is signed correctly, so bring 9345 // over the latest parsed certs. 9346 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9347 } else { 9348 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9349 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9350 "Package " + pkg.packageName + " upgrade keys do not match the " 9351 + "previously installed version"); 9352 } else { 9353 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9354 String msg = "System package " + pkg.packageName 9355 + " signature changed; retaining data."; 9356 reportSettingsProblem(Log.WARN, msg); 9357 } 9358 } 9359 } else { 9360 try { 9361 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9362 verifySignaturesLP(signatureCheckPs, pkg); 9363 // We just determined the app is signed correctly, so bring 9364 // over the latest parsed certs. 9365 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9366 } catch (PackageManagerException e) { 9367 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9368 throw e; 9369 } 9370 // The signature has changed, but this package is in the system 9371 // image... let's recover! 9372 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9373 // However... if this package is part of a shared user, but it 9374 // doesn't match the signature of the shared user, let's fail. 9375 // What this means is that you can't change the signatures 9376 // associated with an overall shared user, which doesn't seem all 9377 // that unreasonable. 9378 if (signatureCheckPs.sharedUser != null) { 9379 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9380 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9381 throw new PackageManagerException( 9382 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9383 "Signature mismatch for shared user: " 9384 + pkgSetting.sharedUser); 9385 } 9386 } 9387 // File a report about this. 9388 String msg = "System package " + pkg.packageName 9389 + " signature changed; retaining data."; 9390 reportSettingsProblem(Log.WARN, msg); 9391 } 9392 } 9393 9394 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9395 // This package wants to adopt ownership of permissions from 9396 // another package. 9397 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9398 final String origName = pkg.mAdoptPermissions.get(i); 9399 final PackageSetting orig = mSettings.getPackageLPr(origName); 9400 if (orig != null) { 9401 if (verifyPackageUpdateLPr(orig, pkg)) { 9402 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9403 + pkg.packageName); 9404 // SIDE EFFECTS; updates permissions system state; move elsewhere 9405 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9406 } 9407 } 9408 } 9409 } 9410 } 9411 9412 pkg.applicationInfo.processName = fixProcessName( 9413 pkg.applicationInfo.packageName, 9414 pkg.applicationInfo.processName); 9415 9416 if (pkg != mPlatformPackage) { 9417 // Get all of our default paths setup 9418 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9419 } 9420 9421 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9422 9423 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9424 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9426 derivePackageAbi( 9427 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9429 9430 // Some system apps still use directory structure for native libraries 9431 // in which case we might end up not detecting abi solely based on apk 9432 // structure. Try to detect abi based on directory structure. 9433 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9434 pkg.applicationInfo.primaryCpuAbi == null) { 9435 setBundledAppAbisAndRoots(pkg, pkgSetting); 9436 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9437 } 9438 } else { 9439 // This is not a first boot or an upgrade, don't bother deriving the 9440 // ABI during the scan. Instead, trust the value that was stored in the 9441 // package setting. 9442 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9443 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9444 9445 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9446 9447 if (DEBUG_ABI_SELECTION) { 9448 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9449 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9450 pkg.applicationInfo.secondaryCpuAbi); 9451 } 9452 } 9453 } else { 9454 if ((scanFlags & SCAN_MOVE) != 0) { 9455 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9456 // but we already have this packages package info in the PackageSetting. We just 9457 // use that and derive the native library path based on the new codepath. 9458 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9459 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9460 } 9461 9462 // Set native library paths again. For moves, the path will be updated based on the 9463 // ABIs we've determined above. For non-moves, the path will be updated based on the 9464 // ABIs we determined during compilation, but the path will depend on the final 9465 // package path (after the rename away from the stage path). 9466 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9467 } 9468 9469 // This is a special case for the "system" package, where the ABI is 9470 // dictated by the zygote configuration (and init.rc). We should keep track 9471 // of this ABI so that we can deal with "normal" applications that run under 9472 // the same UID correctly. 9473 if (mPlatformPackage == pkg) { 9474 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9475 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9476 } 9477 9478 // If there's a mismatch between the abi-override in the package setting 9479 // and the abiOverride specified for the install. Warn about this because we 9480 // would've already compiled the app without taking the package setting into 9481 // account. 9482 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9483 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9484 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9485 " for package " + pkg.packageName); 9486 } 9487 } 9488 9489 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9490 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9491 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9492 9493 // Copy the derived override back to the parsed package, so that we can 9494 // update the package settings accordingly. 9495 pkg.cpuAbiOverride = cpuAbiOverride; 9496 9497 if (DEBUG_ABI_SELECTION) { 9498 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9499 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9500 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9501 } 9502 9503 // Push the derived path down into PackageSettings so we know what to 9504 // clean up at uninstall time. 9505 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9506 9507 if (DEBUG_ABI_SELECTION) { 9508 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9509 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9510 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9511 } 9512 9513 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9514 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9515 // We don't do this here during boot because we can do it all 9516 // at once after scanning all existing packages. 9517 // 9518 // We also do this *before* we perform dexopt on this package, so that 9519 // we can avoid redundant dexopts, and also to make sure we've got the 9520 // code and package path correct. 9521 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9522 } 9523 9524 if (mFactoryTest && pkg.requestedPermissions.contains( 9525 android.Manifest.permission.FACTORY_TEST)) { 9526 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9527 } 9528 9529 if (isSystemApp(pkg)) { 9530 pkgSetting.isOrphaned = true; 9531 } 9532 9533 // Take care of first install / last update times. 9534 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9535 if (currentTime != 0) { 9536 if (pkgSetting.firstInstallTime == 0) { 9537 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9538 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9539 pkgSetting.lastUpdateTime = currentTime; 9540 } 9541 } else if (pkgSetting.firstInstallTime == 0) { 9542 // We need *something*. Take time time stamp of the file. 9543 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9544 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9545 if (scanFileTime != pkgSetting.timeStamp) { 9546 // A package on the system image has changed; consider this 9547 // to be an update. 9548 pkgSetting.lastUpdateTime = scanFileTime; 9549 } 9550 } 9551 pkgSetting.setTimeStamp(scanFileTime); 9552 9553 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9554 if (nonMutatedPs != null) { 9555 synchronized (mPackages) { 9556 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9557 } 9558 } 9559 } else { 9560 final int userId = user == null ? 0 : user.getIdentifier(); 9561 // Modify state for the given package setting 9562 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9563 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9564 if (pkgSetting.getInstantApp(userId)) { 9565 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9566 } 9567 } 9568 return pkg; 9569 } 9570 9571 /** 9572 * Applies policy to the parsed package based upon the given policy flags. 9573 * Ensures the package is in a good state. 9574 * <p> 9575 * Implementation detail: This method must NOT have any side effect. It would 9576 * ideally be static, but, it requires locks to read system state. 9577 */ 9578 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9579 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9580 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9581 if (pkg.applicationInfo.isDirectBootAware()) { 9582 // we're direct boot aware; set for all components 9583 for (PackageParser.Service s : pkg.services) { 9584 s.info.encryptionAware = s.info.directBootAware = true; 9585 } 9586 for (PackageParser.Provider p : pkg.providers) { 9587 p.info.encryptionAware = p.info.directBootAware = true; 9588 } 9589 for (PackageParser.Activity a : pkg.activities) { 9590 a.info.encryptionAware = a.info.directBootAware = true; 9591 } 9592 for (PackageParser.Activity r : pkg.receivers) { 9593 r.info.encryptionAware = r.info.directBootAware = true; 9594 } 9595 } 9596 } else { 9597 // Only allow system apps to be flagged as core apps. 9598 pkg.coreApp = false; 9599 // clear flags not applicable to regular apps 9600 pkg.applicationInfo.privateFlags &= 9601 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9602 pkg.applicationInfo.privateFlags &= 9603 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9604 } 9605 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9606 9607 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9608 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9609 } 9610 9611 if (!isSystemApp(pkg)) { 9612 // Only system apps can use these features. 9613 pkg.mOriginalPackages = null; 9614 pkg.mRealPackage = null; 9615 pkg.mAdoptPermissions = null; 9616 } 9617 } 9618 9619 /** 9620 * Asserts the parsed package is valid according to the given policy. If the 9621 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9622 * <p> 9623 * Implementation detail: This method must NOT have any side effects. It would 9624 * ideally be static, but, it requires locks to read system state. 9625 * 9626 * @throws PackageManagerException If the package fails any of the validation checks 9627 */ 9628 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9629 throws PackageManagerException { 9630 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9631 assertCodePolicy(pkg); 9632 } 9633 9634 if (pkg.applicationInfo.getCodePath() == null || 9635 pkg.applicationInfo.getResourcePath() == null) { 9636 // Bail out. The resource and code paths haven't been set. 9637 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9638 "Code and resource paths haven't been set correctly"); 9639 } 9640 9641 // Make sure we're not adding any bogus keyset info 9642 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9643 ksms.assertScannedPackageValid(pkg); 9644 9645 synchronized (mPackages) { 9646 // The special "android" package can only be defined once 9647 if (pkg.packageName.equals("android")) { 9648 if (mAndroidApplication != null) { 9649 Slog.w(TAG, "*************************************************"); 9650 Slog.w(TAG, "Core android package being redefined. Skipping."); 9651 Slog.w(TAG, " codePath=" + pkg.codePath); 9652 Slog.w(TAG, "*************************************************"); 9653 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9654 "Core android package being redefined. Skipping."); 9655 } 9656 } 9657 9658 // A package name must be unique; don't allow duplicates 9659 if (mPackages.containsKey(pkg.packageName)) { 9660 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9661 "Application package " + pkg.packageName 9662 + " already installed. Skipping duplicate."); 9663 } 9664 9665 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9666 // Static libs have a synthetic package name containing the version 9667 // but we still want the base name to be unique. 9668 if (mPackages.containsKey(pkg.manifestPackageName)) { 9669 throw new PackageManagerException( 9670 "Duplicate static shared lib provider package"); 9671 } 9672 9673 // Static shared libraries should have at least O target SDK 9674 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9675 throw new PackageManagerException( 9676 "Packages declaring static-shared libs must target O SDK or higher"); 9677 } 9678 9679 // Package declaring static a shared lib cannot be instant apps 9680 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9681 throw new PackageManagerException( 9682 "Packages declaring static-shared libs cannot be instant apps"); 9683 } 9684 9685 // Package declaring static a shared lib cannot be renamed since the package 9686 // name is synthetic and apps can't code around package manager internals. 9687 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9688 throw new PackageManagerException( 9689 "Packages declaring static-shared libs cannot be renamed"); 9690 } 9691 9692 // Package declaring static a shared lib cannot declare child packages 9693 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9694 throw new PackageManagerException( 9695 "Packages declaring static-shared libs cannot have child packages"); 9696 } 9697 9698 // Package declaring static a shared lib cannot declare dynamic libs 9699 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9700 throw new PackageManagerException( 9701 "Packages declaring static-shared libs cannot declare dynamic libs"); 9702 } 9703 9704 // Package declaring static a shared lib cannot declare shared users 9705 if (pkg.mSharedUserId != null) { 9706 throw new PackageManagerException( 9707 "Packages declaring static-shared libs cannot declare shared users"); 9708 } 9709 9710 // Static shared libs cannot declare activities 9711 if (!pkg.activities.isEmpty()) { 9712 throw new PackageManagerException( 9713 "Static shared libs cannot declare activities"); 9714 } 9715 9716 // Static shared libs cannot declare services 9717 if (!pkg.services.isEmpty()) { 9718 throw new PackageManagerException( 9719 "Static shared libs cannot declare services"); 9720 } 9721 9722 // Static shared libs cannot declare providers 9723 if (!pkg.providers.isEmpty()) { 9724 throw new PackageManagerException( 9725 "Static shared libs cannot declare content providers"); 9726 } 9727 9728 // Static shared libs cannot declare receivers 9729 if (!pkg.receivers.isEmpty()) { 9730 throw new PackageManagerException( 9731 "Static shared libs cannot declare broadcast receivers"); 9732 } 9733 9734 // Static shared libs cannot declare permission groups 9735 if (!pkg.permissionGroups.isEmpty()) { 9736 throw new PackageManagerException( 9737 "Static shared libs cannot declare permission groups"); 9738 } 9739 9740 // Static shared libs cannot declare permissions 9741 if (!pkg.permissions.isEmpty()) { 9742 throw new PackageManagerException( 9743 "Static shared libs cannot declare permissions"); 9744 } 9745 9746 // Static shared libs cannot declare protected broadcasts 9747 if (pkg.protectedBroadcasts != null) { 9748 throw new PackageManagerException( 9749 "Static shared libs cannot declare protected broadcasts"); 9750 } 9751 9752 // Static shared libs cannot be overlay targets 9753 if (pkg.mOverlayTarget != null) { 9754 throw new PackageManagerException( 9755 "Static shared libs cannot be overlay targets"); 9756 } 9757 9758 // The version codes must be ordered as lib versions 9759 int minVersionCode = Integer.MIN_VALUE; 9760 int maxVersionCode = Integer.MAX_VALUE; 9761 9762 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9763 pkg.staticSharedLibName); 9764 if (versionedLib != null) { 9765 final int versionCount = versionedLib.size(); 9766 for (int i = 0; i < versionCount; i++) { 9767 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9768 // TODO: We will change version code to long, so in the new API it is long 9769 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9770 .getVersionCode(); 9771 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9772 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9773 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9774 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9775 } else { 9776 minVersionCode = maxVersionCode = libVersionCode; 9777 break; 9778 } 9779 } 9780 } 9781 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9782 throw new PackageManagerException("Static shared" 9783 + " lib version codes must be ordered as lib versions"); 9784 } 9785 } 9786 9787 // Only privileged apps and updated privileged apps can add child packages. 9788 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9789 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9790 throw new PackageManagerException("Only privileged apps can add child " 9791 + "packages. Ignoring package " + pkg.packageName); 9792 } 9793 final int childCount = pkg.childPackages.size(); 9794 for (int i = 0; i < childCount; i++) { 9795 PackageParser.Package childPkg = pkg.childPackages.get(i); 9796 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9797 childPkg.packageName)) { 9798 throw new PackageManagerException("Can't override child of " 9799 + "another disabled app. Ignoring package " + pkg.packageName); 9800 } 9801 } 9802 } 9803 9804 // If we're only installing presumed-existing packages, require that the 9805 // scanned APK is both already known and at the path previously established 9806 // for it. Previously unknown packages we pick up normally, but if we have an 9807 // a priori expectation about this package's install presence, enforce it. 9808 // With a singular exception for new system packages. When an OTA contains 9809 // a new system package, we allow the codepath to change from a system location 9810 // to the user-installed location. If we don't allow this change, any newer, 9811 // user-installed version of the application will be ignored. 9812 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9813 if (mExpectingBetter.containsKey(pkg.packageName)) { 9814 logCriticalInfo(Log.WARN, 9815 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9816 } else { 9817 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9818 if (known != null) { 9819 if (DEBUG_PACKAGE_SCANNING) { 9820 Log.d(TAG, "Examining " + pkg.codePath 9821 + " and requiring known paths " + known.codePathString 9822 + " & " + known.resourcePathString); 9823 } 9824 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9825 || !pkg.applicationInfo.getResourcePath().equals( 9826 known.resourcePathString)) { 9827 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9828 "Application package " + pkg.packageName 9829 + " found at " + pkg.applicationInfo.getCodePath() 9830 + " but expected at " + known.codePathString 9831 + "; ignoring."); 9832 } 9833 } 9834 } 9835 } 9836 9837 // Verify that this new package doesn't have any content providers 9838 // that conflict with existing packages. Only do this if the 9839 // package isn't already installed, since we don't want to break 9840 // things that are installed. 9841 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9842 final int N = pkg.providers.size(); 9843 int i; 9844 for (i=0; i<N; i++) { 9845 PackageParser.Provider p = pkg.providers.get(i); 9846 if (p.info.authority != null) { 9847 String names[] = p.info.authority.split(";"); 9848 for (int j = 0; j < names.length; j++) { 9849 if (mProvidersByAuthority.containsKey(names[j])) { 9850 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9851 final String otherPackageName = 9852 ((other != null && other.getComponentName() != null) ? 9853 other.getComponentName().getPackageName() : "?"); 9854 throw new PackageManagerException( 9855 INSTALL_FAILED_CONFLICTING_PROVIDER, 9856 "Can't install because provider name " + names[j] 9857 + " (in package " + pkg.applicationInfo.packageName 9858 + ") is already used by " + otherPackageName); 9859 } 9860 } 9861 } 9862 } 9863 } 9864 } 9865 } 9866 9867 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9868 int type, String declaringPackageName, int declaringVersionCode) { 9869 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9870 if (versionedLib == null) { 9871 versionedLib = new SparseArray<>(); 9872 mSharedLibraries.put(name, versionedLib); 9873 if (type == SharedLibraryInfo.TYPE_STATIC) { 9874 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9875 } 9876 } else if (versionedLib.indexOfKey(version) >= 0) { 9877 return false; 9878 } 9879 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9880 version, type, declaringPackageName, declaringVersionCode); 9881 versionedLib.put(version, libEntry); 9882 return true; 9883 } 9884 9885 private boolean removeSharedLibraryLPw(String name, int version) { 9886 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9887 if (versionedLib == null) { 9888 return false; 9889 } 9890 final int libIdx = versionedLib.indexOfKey(version); 9891 if (libIdx < 0) { 9892 return false; 9893 } 9894 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9895 versionedLib.remove(version); 9896 if (versionedLib.size() <= 0) { 9897 mSharedLibraries.remove(name); 9898 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9899 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9900 .getPackageName()); 9901 } 9902 } 9903 return true; 9904 } 9905 9906 /** 9907 * Adds a scanned package to the system. When this method is finished, the package will 9908 * be available for query, resolution, etc... 9909 */ 9910 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9911 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9912 final String pkgName = pkg.packageName; 9913 if (mCustomResolverComponentName != null && 9914 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9915 setUpCustomResolverActivity(pkg); 9916 } 9917 9918 if (pkg.packageName.equals("android")) { 9919 synchronized (mPackages) { 9920 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9921 // Set up information for our fall-back user intent resolution activity. 9922 mPlatformPackage = pkg; 9923 pkg.mVersionCode = mSdkVersion; 9924 mAndroidApplication = pkg.applicationInfo; 9925 if (!mResolverReplaced) { 9926 mResolveActivity.applicationInfo = mAndroidApplication; 9927 mResolveActivity.name = ResolverActivity.class.getName(); 9928 mResolveActivity.packageName = mAndroidApplication.packageName; 9929 mResolveActivity.processName = "system:ui"; 9930 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9931 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9932 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9933 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9934 mResolveActivity.exported = true; 9935 mResolveActivity.enabled = true; 9936 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9937 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9938 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9939 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9940 | ActivityInfo.CONFIG_ORIENTATION 9941 | ActivityInfo.CONFIG_KEYBOARD 9942 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9943 mResolveInfo.activityInfo = mResolveActivity; 9944 mResolveInfo.priority = 0; 9945 mResolveInfo.preferredOrder = 0; 9946 mResolveInfo.match = 0; 9947 mResolveComponentName = new ComponentName( 9948 mAndroidApplication.packageName, mResolveActivity.name); 9949 } 9950 } 9951 } 9952 } 9953 9954 ArrayList<PackageParser.Package> clientLibPkgs = null; 9955 // writer 9956 synchronized (mPackages) { 9957 boolean hasStaticSharedLibs = false; 9958 9959 // Any app can add new static shared libraries 9960 if (pkg.staticSharedLibName != null) { 9961 // Static shared libs don't allow renaming as they have synthetic package 9962 // names to allow install of multiple versions, so use name from manifest. 9963 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9964 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9965 pkg.manifestPackageName, pkg.mVersionCode)) { 9966 hasStaticSharedLibs = true; 9967 } else { 9968 Slog.w(TAG, "Package " + pkg.packageName + " library " 9969 + pkg.staticSharedLibName + " already exists; skipping"); 9970 } 9971 // Static shared libs cannot be updated once installed since they 9972 // use synthetic package name which includes the version code, so 9973 // not need to update other packages's shared lib dependencies. 9974 } 9975 9976 if (!hasStaticSharedLibs 9977 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9978 // Only system apps can add new dynamic shared libraries. 9979 if (pkg.libraryNames != null) { 9980 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9981 String name = pkg.libraryNames.get(i); 9982 boolean allowed = false; 9983 if (pkg.isUpdatedSystemApp()) { 9984 // New library entries can only be added through the 9985 // system image. This is important to get rid of a lot 9986 // of nasty edge cases: for example if we allowed a non- 9987 // system update of the app to add a library, then uninstalling 9988 // the update would make the library go away, and assumptions 9989 // we made such as through app install filtering would now 9990 // have allowed apps on the device which aren't compatible 9991 // with it. Better to just have the restriction here, be 9992 // conservative, and create many fewer cases that can negatively 9993 // impact the user experience. 9994 final PackageSetting sysPs = mSettings 9995 .getDisabledSystemPkgLPr(pkg.packageName); 9996 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9997 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9998 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9999 allowed = true; 10000 break; 10001 } 10002 } 10003 } 10004 } else { 10005 allowed = true; 10006 } 10007 if (allowed) { 10008 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10009 SharedLibraryInfo.VERSION_UNDEFINED, 10010 SharedLibraryInfo.TYPE_DYNAMIC, 10011 pkg.packageName, pkg.mVersionCode)) { 10012 Slog.w(TAG, "Package " + pkg.packageName + " library " 10013 + name + " already exists; skipping"); 10014 } 10015 } else { 10016 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10017 + name + " that is not declared on system image; skipping"); 10018 } 10019 } 10020 10021 if ((scanFlags & SCAN_BOOTING) == 0) { 10022 // If we are not booting, we need to update any applications 10023 // that are clients of our shared library. If we are booting, 10024 // this will all be done once the scan is complete. 10025 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10026 } 10027 } 10028 } 10029 } 10030 10031 if ((scanFlags & SCAN_BOOTING) != 0) { 10032 // No apps can run during boot scan, so they don't need to be frozen 10033 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10034 // Caller asked to not kill app, so it's probably not frozen 10035 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10036 // Caller asked us to ignore frozen check for some reason; they 10037 // probably didn't know the package name 10038 } else { 10039 // We're doing major surgery on this package, so it better be frozen 10040 // right now to keep it from launching 10041 checkPackageFrozen(pkgName); 10042 } 10043 10044 // Also need to kill any apps that are dependent on the library. 10045 if (clientLibPkgs != null) { 10046 for (int i=0; i<clientLibPkgs.size(); i++) { 10047 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10048 killApplication(clientPkg.applicationInfo.packageName, 10049 clientPkg.applicationInfo.uid, "update lib"); 10050 } 10051 } 10052 10053 // writer 10054 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10055 10056 synchronized (mPackages) { 10057 // We don't expect installation to fail beyond this point 10058 10059 if (pkgSetting.pkg != null) { 10060 // Note that |user| might be null during the initial boot scan. If a codePath 10061 // for an app has changed during a boot scan, it's due to an app update that's 10062 // part of the system partition and marker changes must be applied to all users. 10063 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 10064 final int[] userIds = resolveUserIds(userId); 10065 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 10066 } 10067 10068 // Add the new setting to mSettings 10069 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10070 // Add the new setting to mPackages 10071 mPackages.put(pkg.applicationInfo.packageName, pkg); 10072 // Make sure we don't accidentally delete its data. 10073 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10074 while (iter.hasNext()) { 10075 PackageCleanItem item = iter.next(); 10076 if (pkgName.equals(item.packageName)) { 10077 iter.remove(); 10078 } 10079 } 10080 10081 // Add the package's KeySets to the global KeySetManagerService 10082 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10083 ksms.addScannedPackageLPw(pkg); 10084 10085 int N = pkg.providers.size(); 10086 StringBuilder r = null; 10087 int i; 10088 for (i=0; i<N; i++) { 10089 PackageParser.Provider p = pkg.providers.get(i); 10090 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10091 p.info.processName); 10092 mProviders.addProvider(p); 10093 p.syncable = p.info.isSyncable; 10094 if (p.info.authority != null) { 10095 String names[] = p.info.authority.split(";"); 10096 p.info.authority = null; 10097 for (int j = 0; j < names.length; j++) { 10098 if (j == 1 && p.syncable) { 10099 // We only want the first authority for a provider to possibly be 10100 // syncable, so if we already added this provider using a different 10101 // authority clear the syncable flag. We copy the provider before 10102 // changing it because the mProviders object contains a reference 10103 // to a provider that we don't want to change. 10104 // Only do this for the second authority since the resulting provider 10105 // object can be the same for all future authorities for this provider. 10106 p = new PackageParser.Provider(p); 10107 p.syncable = false; 10108 } 10109 if (!mProvidersByAuthority.containsKey(names[j])) { 10110 mProvidersByAuthority.put(names[j], p); 10111 if (p.info.authority == null) { 10112 p.info.authority = names[j]; 10113 } else { 10114 p.info.authority = p.info.authority + ";" + names[j]; 10115 } 10116 if (DEBUG_PACKAGE_SCANNING) { 10117 if (chatty) 10118 Log.d(TAG, "Registered content provider: " + names[j] 10119 + ", className = " + p.info.name + ", isSyncable = " 10120 + p.info.isSyncable); 10121 } 10122 } else { 10123 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10124 Slog.w(TAG, "Skipping provider name " + names[j] + 10125 " (in package " + pkg.applicationInfo.packageName + 10126 "): name already used by " 10127 + ((other != null && other.getComponentName() != null) 10128 ? other.getComponentName().getPackageName() : "?")); 10129 } 10130 } 10131 } 10132 if (chatty) { 10133 if (r == null) { 10134 r = new StringBuilder(256); 10135 } else { 10136 r.append(' '); 10137 } 10138 r.append(p.info.name); 10139 } 10140 } 10141 if (r != null) { 10142 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10143 } 10144 10145 N = pkg.services.size(); 10146 r = null; 10147 for (i=0; i<N; i++) { 10148 PackageParser.Service s = pkg.services.get(i); 10149 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10150 s.info.processName); 10151 mServices.addService(s); 10152 if (chatty) { 10153 if (r == null) { 10154 r = new StringBuilder(256); 10155 } else { 10156 r.append(' '); 10157 } 10158 r.append(s.info.name); 10159 } 10160 } 10161 if (r != null) { 10162 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10163 } 10164 10165 N = pkg.receivers.size(); 10166 r = null; 10167 for (i=0; i<N; i++) { 10168 PackageParser.Activity a = pkg.receivers.get(i); 10169 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10170 a.info.processName); 10171 mReceivers.addActivity(a, "receiver"); 10172 if (chatty) { 10173 if (r == null) { 10174 r = new StringBuilder(256); 10175 } else { 10176 r.append(' '); 10177 } 10178 r.append(a.info.name); 10179 } 10180 } 10181 if (r != null) { 10182 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10183 } 10184 10185 N = pkg.activities.size(); 10186 r = null; 10187 for (i=0; i<N; i++) { 10188 PackageParser.Activity a = pkg.activities.get(i); 10189 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10190 a.info.processName); 10191 mActivities.addActivity(a, "activity"); 10192 if (chatty) { 10193 if (r == null) { 10194 r = new StringBuilder(256); 10195 } else { 10196 r.append(' '); 10197 } 10198 r.append(a.info.name); 10199 } 10200 } 10201 if (r != null) { 10202 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10203 } 10204 10205 N = pkg.permissionGroups.size(); 10206 r = null; 10207 for (i=0; i<N; i++) { 10208 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10209 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10210 final String curPackageName = cur == null ? null : cur.info.packageName; 10211 // Dont allow ephemeral apps to define new permission groups. 10212 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10213 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10214 + pg.info.packageName 10215 + " ignored: instant apps cannot define new permission groups."); 10216 continue; 10217 } 10218 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10219 if (cur == null || isPackageUpdate) { 10220 mPermissionGroups.put(pg.info.name, pg); 10221 if (chatty) { 10222 if (r == null) { 10223 r = new StringBuilder(256); 10224 } else { 10225 r.append(' '); 10226 } 10227 if (isPackageUpdate) { 10228 r.append("UPD:"); 10229 } 10230 r.append(pg.info.name); 10231 } 10232 } else { 10233 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10234 + pg.info.packageName + " ignored: original from " 10235 + cur.info.packageName); 10236 if (chatty) { 10237 if (r == null) { 10238 r = new StringBuilder(256); 10239 } else { 10240 r.append(' '); 10241 } 10242 r.append("DUP:"); 10243 r.append(pg.info.name); 10244 } 10245 } 10246 } 10247 if (r != null) { 10248 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10249 } 10250 10251 N = pkg.permissions.size(); 10252 r = null; 10253 for (i=0; i<N; i++) { 10254 PackageParser.Permission p = pkg.permissions.get(i); 10255 10256 // Dont allow ephemeral apps to define new permissions. 10257 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10258 Slog.w(TAG, "Permission " + p.info.name + " from package " 10259 + p.info.packageName 10260 + " ignored: instant apps cannot define new permissions."); 10261 continue; 10262 } 10263 10264 // Assume by default that we did not install this permission into the system. 10265 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10266 10267 // Now that permission groups have a special meaning, we ignore permission 10268 // groups for legacy apps to prevent unexpected behavior. In particular, 10269 // permissions for one app being granted to someone just becase they happen 10270 // to be in a group defined by another app (before this had no implications). 10271 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10272 p.group = mPermissionGroups.get(p.info.group); 10273 // Warn for a permission in an unknown group. 10274 if (p.info.group != null && p.group == null) { 10275 Slog.w(TAG, "Permission " + p.info.name + " from package " 10276 + p.info.packageName + " in an unknown group " + p.info.group); 10277 } 10278 } 10279 10280 ArrayMap<String, BasePermission> permissionMap = 10281 p.tree ? mSettings.mPermissionTrees 10282 : mSettings.mPermissions; 10283 BasePermission bp = permissionMap.get(p.info.name); 10284 10285 // Allow system apps to redefine non-system permissions 10286 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10287 final boolean currentOwnerIsSystem = (bp.perm != null 10288 && isSystemApp(bp.perm.owner)); 10289 if (isSystemApp(p.owner)) { 10290 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10291 // It's a built-in permission and no owner, take ownership now 10292 bp.packageSetting = pkgSetting; 10293 bp.perm = p; 10294 bp.uid = pkg.applicationInfo.uid; 10295 bp.sourcePackage = p.info.packageName; 10296 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10297 } else if (!currentOwnerIsSystem) { 10298 String msg = "New decl " + p.owner + " of permission " 10299 + p.info.name + " is system; overriding " + bp.sourcePackage; 10300 reportSettingsProblem(Log.WARN, msg); 10301 bp = null; 10302 } 10303 } 10304 } 10305 10306 if (bp == null) { 10307 bp = new BasePermission(p.info.name, p.info.packageName, 10308 BasePermission.TYPE_NORMAL); 10309 permissionMap.put(p.info.name, bp); 10310 } 10311 10312 if (bp.perm == null) { 10313 if (bp.sourcePackage == null 10314 || bp.sourcePackage.equals(p.info.packageName)) { 10315 BasePermission tree = findPermissionTreeLP(p.info.name); 10316 if (tree == null 10317 || tree.sourcePackage.equals(p.info.packageName)) { 10318 bp.packageSetting = pkgSetting; 10319 bp.perm = p; 10320 bp.uid = pkg.applicationInfo.uid; 10321 bp.sourcePackage = p.info.packageName; 10322 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10323 if (chatty) { 10324 if (r == null) { 10325 r = new StringBuilder(256); 10326 } else { 10327 r.append(' '); 10328 } 10329 r.append(p.info.name); 10330 } 10331 } else { 10332 Slog.w(TAG, "Permission " + p.info.name + " from package " 10333 + p.info.packageName + " ignored: base tree " 10334 + tree.name + " is from package " 10335 + tree.sourcePackage); 10336 } 10337 } else { 10338 Slog.w(TAG, "Permission " + p.info.name + " from package " 10339 + p.info.packageName + " ignored: original from " 10340 + bp.sourcePackage); 10341 } 10342 } else if (chatty) { 10343 if (r == null) { 10344 r = new StringBuilder(256); 10345 } else { 10346 r.append(' '); 10347 } 10348 r.append("DUP:"); 10349 r.append(p.info.name); 10350 } 10351 if (bp.perm == p) { 10352 bp.protectionLevel = p.info.protectionLevel; 10353 } 10354 } 10355 10356 if (r != null) { 10357 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10358 } 10359 10360 N = pkg.instrumentation.size(); 10361 r = null; 10362 for (i=0; i<N; i++) { 10363 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10364 a.info.packageName = pkg.applicationInfo.packageName; 10365 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10366 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10367 a.info.splitNames = pkg.splitNames; 10368 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10369 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10370 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10371 a.info.dataDir = pkg.applicationInfo.dataDir; 10372 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10373 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10374 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10375 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10376 mInstrumentation.put(a.getComponentName(), a); 10377 if (chatty) { 10378 if (r == null) { 10379 r = new StringBuilder(256); 10380 } else { 10381 r.append(' '); 10382 } 10383 r.append(a.info.name); 10384 } 10385 } 10386 if (r != null) { 10387 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10388 } 10389 10390 if (pkg.protectedBroadcasts != null) { 10391 N = pkg.protectedBroadcasts.size(); 10392 for (i=0; i<N; i++) { 10393 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10394 } 10395 } 10396 } 10397 10398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10399 } 10400 10401 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 10402 PackageParser.Package update, int[] userIds) { 10403 if (existing.applicationInfo == null || update.applicationInfo == null) { 10404 // This isn't due to an app installation. 10405 return; 10406 } 10407 10408 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 10409 final File newCodePath = new File(update.applicationInfo.getCodePath()); 10410 10411 // The codePath hasn't changed, so there's nothing for us to do. 10412 if (Objects.equals(oldCodePath, newCodePath)) { 10413 return; 10414 } 10415 10416 File canonicalNewCodePath; 10417 try { 10418 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 10419 } catch (IOException e) { 10420 Slog.w(TAG, "Failed to get canonical path.", e); 10421 return; 10422 } 10423 10424 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 10425 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 10426 // that the last component of the path (i.e, the name) doesn't need canonicalization 10427 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 10428 // but may change in the future. Hopefully this function won't exist at that point. 10429 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 10430 oldCodePath.getName()); 10431 10432 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 10433 // with "@". 10434 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 10435 if (!oldMarkerPrefix.endsWith("@")) { 10436 oldMarkerPrefix += "@"; 10437 } 10438 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 10439 if (!newMarkerPrefix.endsWith("@")) { 10440 newMarkerPrefix += "@"; 10441 } 10442 10443 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 10444 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 10445 for (String updatedPath : updatedPaths) { 10446 String updatedPathName = new File(updatedPath).getName(); 10447 markerSuffixes.add(updatedPathName.replace('/', '@')); 10448 } 10449 10450 for (int userId : userIds) { 10451 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 10452 10453 for (String markerSuffix : markerSuffixes) { 10454 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 10455 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 10456 if (oldForeignUseMark.exists()) { 10457 try { 10458 Os.rename(oldForeignUseMark.getAbsolutePath(), 10459 newForeignUseMark.getAbsolutePath()); 10460 } catch (ErrnoException e) { 10461 Slog.w(TAG, "Failed to rename foreign use marker", e); 10462 oldForeignUseMark.delete(); 10463 } 10464 } 10465 } 10466 } 10467 } 10468 10469 /** 10470 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10471 * is derived purely on the basis of the contents of {@code scanFile} and 10472 * {@code cpuAbiOverride}. 10473 * 10474 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10475 */ 10476 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10477 String cpuAbiOverride, boolean extractLibs, 10478 File appLib32InstallDir) 10479 throws PackageManagerException { 10480 // Give ourselves some initial paths; we'll come back for another 10481 // pass once we've determined ABI below. 10482 setNativeLibraryPaths(pkg, appLib32InstallDir); 10483 10484 // We would never need to extract libs for forward-locked and external packages, 10485 // since the container service will do it for us. We shouldn't attempt to 10486 // extract libs from system app when it was not updated. 10487 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10488 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10489 extractLibs = false; 10490 } 10491 10492 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10493 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10494 10495 NativeLibraryHelper.Handle handle = null; 10496 try { 10497 handle = NativeLibraryHelper.Handle.create(pkg); 10498 // TODO(multiArch): This can be null for apps that didn't go through the 10499 // usual installation process. We can calculate it again, like we 10500 // do during install time. 10501 // 10502 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10503 // unnecessary. 10504 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10505 10506 // Null out the abis so that they can be recalculated. 10507 pkg.applicationInfo.primaryCpuAbi = null; 10508 pkg.applicationInfo.secondaryCpuAbi = null; 10509 if (isMultiArch(pkg.applicationInfo)) { 10510 // Warn if we've set an abiOverride for multi-lib packages.. 10511 // By definition, we need to copy both 32 and 64 bit libraries for 10512 // such packages. 10513 if (pkg.cpuAbiOverride != null 10514 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10515 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10516 } 10517 10518 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10519 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10520 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10521 if (extractLibs) { 10522 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10523 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10524 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10525 useIsaSpecificSubdirs); 10526 } else { 10527 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10528 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10529 } 10530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10531 } 10532 10533 maybeThrowExceptionForMultiArchCopy( 10534 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10535 10536 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10537 if (extractLibs) { 10538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10539 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10540 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10541 useIsaSpecificSubdirs); 10542 } else { 10543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10544 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10545 } 10546 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10547 } 10548 10549 maybeThrowExceptionForMultiArchCopy( 10550 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10551 10552 if (abi64 >= 0) { 10553 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10554 } 10555 10556 if (abi32 >= 0) { 10557 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10558 if (abi64 >= 0) { 10559 if (pkg.use32bitAbi) { 10560 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10561 pkg.applicationInfo.primaryCpuAbi = abi; 10562 } else { 10563 pkg.applicationInfo.secondaryCpuAbi = abi; 10564 } 10565 } else { 10566 pkg.applicationInfo.primaryCpuAbi = abi; 10567 } 10568 } 10569 10570 } else { 10571 String[] abiList = (cpuAbiOverride != null) ? 10572 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10573 10574 // Enable gross and lame hacks for apps that are built with old 10575 // SDK tools. We must scan their APKs for renderscript bitcode and 10576 // not launch them if it's present. Don't bother checking on devices 10577 // that don't have 64 bit support. 10578 boolean needsRenderScriptOverride = false; 10579 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10580 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10581 abiList = Build.SUPPORTED_32_BIT_ABIS; 10582 needsRenderScriptOverride = true; 10583 } 10584 10585 final int copyRet; 10586 if (extractLibs) { 10587 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10588 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10589 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10590 } else { 10591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10592 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10593 } 10594 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10595 10596 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10597 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10598 "Error unpackaging native libs for app, errorCode=" + copyRet); 10599 } 10600 10601 if (copyRet >= 0) { 10602 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10603 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10604 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10605 } else if (needsRenderScriptOverride) { 10606 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10607 } 10608 } 10609 } catch (IOException ioe) { 10610 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10611 } finally { 10612 IoUtils.closeQuietly(handle); 10613 } 10614 10615 // Now that we've calculated the ABIs and determined if it's an internal app, 10616 // we will go ahead and populate the nativeLibraryPath. 10617 setNativeLibraryPaths(pkg, appLib32InstallDir); 10618 } 10619 10620 /** 10621 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10622 * i.e, so that all packages can be run inside a single process if required. 10623 * 10624 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10625 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10626 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10627 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10628 * updating a package that belongs to a shared user. 10629 * 10630 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10631 * adds unnecessary complexity. 10632 */ 10633 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10634 PackageParser.Package scannedPackage) { 10635 String requiredInstructionSet = null; 10636 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10637 requiredInstructionSet = VMRuntime.getInstructionSet( 10638 scannedPackage.applicationInfo.primaryCpuAbi); 10639 } 10640 10641 PackageSetting requirer = null; 10642 for (PackageSetting ps : packagesForUser) { 10643 // If packagesForUser contains scannedPackage, we skip it. This will happen 10644 // when scannedPackage is an update of an existing package. Without this check, 10645 // we will never be able to change the ABI of any package belonging to a shared 10646 // user, even if it's compatible with other packages. 10647 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10648 if (ps.primaryCpuAbiString == null) { 10649 continue; 10650 } 10651 10652 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10653 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10654 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10655 // this but there's not much we can do. 10656 String errorMessage = "Instruction set mismatch, " 10657 + ((requirer == null) ? "[caller]" : requirer) 10658 + " requires " + requiredInstructionSet + " whereas " + ps 10659 + " requires " + instructionSet; 10660 Slog.w(TAG, errorMessage); 10661 } 10662 10663 if (requiredInstructionSet == null) { 10664 requiredInstructionSet = instructionSet; 10665 requirer = ps; 10666 } 10667 } 10668 } 10669 10670 if (requiredInstructionSet != null) { 10671 String adjustedAbi; 10672 if (requirer != null) { 10673 // requirer != null implies that either scannedPackage was null or that scannedPackage 10674 // did not require an ABI, in which case we have to adjust scannedPackage to match 10675 // the ABI of the set (which is the same as requirer's ABI) 10676 adjustedAbi = requirer.primaryCpuAbiString; 10677 if (scannedPackage != null) { 10678 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10679 } 10680 } else { 10681 // requirer == null implies that we're updating all ABIs in the set to 10682 // match scannedPackage. 10683 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10684 } 10685 10686 for (PackageSetting ps : packagesForUser) { 10687 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10688 if (ps.primaryCpuAbiString != null) { 10689 continue; 10690 } 10691 10692 ps.primaryCpuAbiString = adjustedAbi; 10693 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10694 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10695 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10696 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10697 + " (requirer=" 10698 + (requirer == null ? "null" : requirer.pkg.packageName) 10699 + ", scannedPackage=" 10700 + (scannedPackage != null ? scannedPackage.packageName : "null") 10701 + ")"); 10702 try { 10703 mInstaller.rmdex(ps.codePathString, 10704 getDexCodeInstructionSet(getPreferredInstructionSet())); 10705 } catch (InstallerException ignored) { 10706 } 10707 } 10708 } 10709 } 10710 } 10711 } 10712 10713 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10714 synchronized (mPackages) { 10715 mResolverReplaced = true; 10716 // Set up information for custom user intent resolution activity. 10717 mResolveActivity.applicationInfo = pkg.applicationInfo; 10718 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10719 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10720 mResolveActivity.processName = pkg.applicationInfo.packageName; 10721 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10722 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10723 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10724 mResolveActivity.theme = 0; 10725 mResolveActivity.exported = true; 10726 mResolveActivity.enabled = true; 10727 mResolveInfo.activityInfo = mResolveActivity; 10728 mResolveInfo.priority = 0; 10729 mResolveInfo.preferredOrder = 0; 10730 mResolveInfo.match = 0; 10731 mResolveComponentName = mCustomResolverComponentName; 10732 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10733 mResolveComponentName); 10734 } 10735 } 10736 10737 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10738 if (installerComponent == null) { 10739 if (DEBUG_EPHEMERAL) { 10740 Slog.d(TAG, "Clear ephemeral installer activity"); 10741 } 10742 mInstantAppInstallerActivity.applicationInfo = null; 10743 return; 10744 } 10745 10746 if (DEBUG_EPHEMERAL) { 10747 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10748 } 10749 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10750 // Set up information for ephemeral installer activity 10751 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10752 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10753 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10754 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10755 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10756 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10757 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10758 mInstantAppInstallerActivity.theme = 0; 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 11419 if (DEBUG_INSTALL) { 11420 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11421 } 11422 11423 if (bp == null || bp.packageSetting == null) { 11424 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11425 Slog.w(TAG, "Unknown permission " + name 11426 + " in package " + pkg.packageName); 11427 } 11428 continue; 11429 } 11430 11431 11432 // Limit ephemeral apps to ephemeral allowed permissions. 11433 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11434 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11435 + pkg.packageName); 11436 continue; 11437 } 11438 11439 final String perm = bp.name; 11440 boolean allowedSig = false; 11441 int grant = GRANT_DENIED; 11442 11443 // Keep track of app op permissions. 11444 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11445 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11446 if (pkgs == null) { 11447 pkgs = new ArraySet<>(); 11448 mAppOpPermissionPackages.put(bp.name, pkgs); 11449 } 11450 pkgs.add(pkg.packageName); 11451 } 11452 11453 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11454 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11455 >= Build.VERSION_CODES.M; 11456 switch (level) { 11457 case PermissionInfo.PROTECTION_NORMAL: { 11458 // For all apps normal permissions are install time ones. 11459 grant = GRANT_INSTALL; 11460 } break; 11461 11462 case PermissionInfo.PROTECTION_DANGEROUS: { 11463 // If a permission review is required for legacy apps we represent 11464 // their permissions as always granted runtime ones since we need 11465 // to keep the review required permission flag per user while an 11466 // install permission's state is shared across all users. 11467 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11468 // For legacy apps dangerous permissions are install time ones. 11469 grant = GRANT_INSTALL; 11470 } else if (origPermissions.hasInstallPermission(bp.name)) { 11471 // For legacy apps that became modern, install becomes runtime. 11472 grant = GRANT_UPGRADE; 11473 } else if (mPromoteSystemApps 11474 && isSystemApp(ps) 11475 && mExistingSystemPackages.contains(ps.name)) { 11476 // For legacy system apps, install becomes runtime. 11477 // We cannot check hasInstallPermission() for system apps since those 11478 // permissions were granted implicitly and not persisted pre-M. 11479 grant = GRANT_UPGRADE; 11480 } else { 11481 // For modern apps keep runtime permissions unchanged. 11482 grant = GRANT_RUNTIME; 11483 } 11484 } break; 11485 11486 case PermissionInfo.PROTECTION_SIGNATURE: { 11487 // For all apps signature permissions are install time ones. 11488 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11489 if (allowedSig) { 11490 grant = GRANT_INSTALL; 11491 } 11492 } break; 11493 } 11494 11495 if (DEBUG_INSTALL) { 11496 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11497 } 11498 11499 if (grant != GRANT_DENIED) { 11500 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11501 // If this is an existing, non-system package, then 11502 // we can't add any new permissions to it. 11503 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11504 // Except... if this is a permission that was added 11505 // to the platform (note: need to only do this when 11506 // updating the platform). 11507 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11508 grant = GRANT_DENIED; 11509 } 11510 } 11511 } 11512 11513 switch (grant) { 11514 case GRANT_INSTALL: { 11515 // Revoke this as runtime permission to handle the case of 11516 // a runtime permission being downgraded to an install one. 11517 // Also in permission review mode we keep dangerous permissions 11518 // for legacy apps 11519 for (int userId : UserManagerService.getInstance().getUserIds()) { 11520 if (origPermissions.getRuntimePermissionState( 11521 bp.name, userId) != null) { 11522 // Revoke the runtime permission and clear the flags. 11523 origPermissions.revokeRuntimePermission(bp, userId); 11524 origPermissions.updatePermissionFlags(bp, userId, 11525 PackageManager.MASK_PERMISSION_FLAGS, 0); 11526 // If we revoked a permission permission, we have to write. 11527 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11528 changedRuntimePermissionUserIds, userId); 11529 } 11530 } 11531 // Grant an install permission. 11532 if (permissionsState.grantInstallPermission(bp) != 11533 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11534 changedInstallPermission = true; 11535 } 11536 } break; 11537 11538 case GRANT_RUNTIME: { 11539 // Grant previously granted runtime permissions. 11540 for (int userId : UserManagerService.getInstance().getUserIds()) { 11541 PermissionState permissionState = origPermissions 11542 .getRuntimePermissionState(bp.name, userId); 11543 int flags = permissionState != null 11544 ? permissionState.getFlags() : 0; 11545 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11546 // Don't propagate the permission in a permission review mode if 11547 // the former was revoked, i.e. marked to not propagate on upgrade. 11548 // Note that in a permission review mode install permissions are 11549 // represented as constantly granted runtime ones since we need to 11550 // keep a per user state associated with the permission. Also the 11551 // revoke on upgrade flag is no longer applicable and is reset. 11552 final boolean revokeOnUpgrade = (flags & PackageManager 11553 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11554 if (revokeOnUpgrade) { 11555 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11556 // Since we changed the flags, we have to write. 11557 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11558 changedRuntimePermissionUserIds, userId); 11559 } 11560 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11561 if (permissionsState.grantRuntimePermission(bp, userId) == 11562 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11563 // If we cannot put the permission as it was, 11564 // we have to write. 11565 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11566 changedRuntimePermissionUserIds, userId); 11567 } 11568 } 11569 11570 // If the app supports runtime permissions no need for a review. 11571 if (mPermissionReviewRequired 11572 && appSupportsRuntimePermissions 11573 && (flags & PackageManager 11574 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11575 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11576 // Since we changed the flags, we have to write. 11577 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11578 changedRuntimePermissionUserIds, userId); 11579 } 11580 } else if (mPermissionReviewRequired 11581 && !appSupportsRuntimePermissions) { 11582 // For legacy apps that need a permission review, every new 11583 // runtime permission is granted but it is pending a review. 11584 // We also need to review only platform defined runtime 11585 // permissions as these are the only ones the platform knows 11586 // how to disable the API to simulate revocation as legacy 11587 // apps don't expect to run with revoked permissions. 11588 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11589 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11590 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11591 // We changed the flags, hence have to write. 11592 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11593 changedRuntimePermissionUserIds, userId); 11594 } 11595 } 11596 if (permissionsState.grantRuntimePermission(bp, userId) 11597 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11598 // We changed the permission, hence have to write. 11599 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11600 changedRuntimePermissionUserIds, userId); 11601 } 11602 } 11603 // Propagate the permission flags. 11604 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11605 } 11606 } break; 11607 11608 case GRANT_UPGRADE: { 11609 // Grant runtime permissions for a previously held install permission. 11610 PermissionState permissionState = origPermissions 11611 .getInstallPermissionState(bp.name); 11612 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11613 11614 if (origPermissions.revokeInstallPermission(bp) 11615 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11616 // We will be transferring the permission flags, so clear them. 11617 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11618 PackageManager.MASK_PERMISSION_FLAGS, 0); 11619 changedInstallPermission = true; 11620 } 11621 11622 // If the permission is not to be promoted to runtime we ignore it and 11623 // also its other flags as they are not applicable to install permissions. 11624 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11625 for (int userId : currentUserIds) { 11626 if (permissionsState.grantRuntimePermission(bp, userId) != 11627 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11628 // Transfer the permission flags. 11629 permissionsState.updatePermissionFlags(bp, userId, 11630 flags, flags); 11631 // If we granted the permission, we have to write. 11632 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11633 changedRuntimePermissionUserIds, userId); 11634 } 11635 } 11636 } 11637 } break; 11638 11639 default: { 11640 if (packageOfInterest == null 11641 || packageOfInterest.equals(pkg.packageName)) { 11642 Slog.w(TAG, "Not granting permission " + perm 11643 + " to package " + pkg.packageName 11644 + " because it was previously installed without"); 11645 } 11646 } break; 11647 } 11648 } else { 11649 if (permissionsState.revokeInstallPermission(bp) != 11650 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11651 // Also drop the permission flags. 11652 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11653 PackageManager.MASK_PERMISSION_FLAGS, 0); 11654 changedInstallPermission = true; 11655 Slog.i(TAG, "Un-granting permission " + perm 11656 + " from package " + pkg.packageName 11657 + " (protectionLevel=" + bp.protectionLevel 11658 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11659 + ")"); 11660 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11661 // Don't print warning for app op permissions, since it is fine for them 11662 // not to be granted, there is a UI for the user to decide. 11663 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11664 Slog.w(TAG, "Not granting permission " + perm 11665 + " to package " + pkg.packageName 11666 + " (protectionLevel=" + bp.protectionLevel 11667 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11668 + ")"); 11669 } 11670 } 11671 } 11672 } 11673 11674 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11675 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11676 // This is the first that we have heard about this package, so the 11677 // permissions we have now selected are fixed until explicitly 11678 // changed. 11679 ps.installPermissionsFixed = true; 11680 } 11681 11682 // Persist the runtime permissions state for users with changes. If permissions 11683 // were revoked because no app in the shared user declares them we have to 11684 // write synchronously to avoid losing runtime permissions state. 11685 for (int userId : changedRuntimePermissionUserIds) { 11686 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11687 } 11688 } 11689 11690 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11691 boolean allowed = false; 11692 final int NP = PackageParser.NEW_PERMISSIONS.length; 11693 for (int ip=0; ip<NP; ip++) { 11694 final PackageParser.NewPermissionInfo npi 11695 = PackageParser.NEW_PERMISSIONS[ip]; 11696 if (npi.name.equals(perm) 11697 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11698 allowed = true; 11699 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11700 + pkg.packageName); 11701 break; 11702 } 11703 } 11704 return allowed; 11705 } 11706 11707 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11708 BasePermission bp, PermissionsState origPermissions) { 11709 boolean privilegedPermission = (bp.protectionLevel 11710 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11711 boolean privappPermissionsDisable = 11712 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11713 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11714 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11715 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11716 && !platformPackage && platformPermission) { 11717 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11718 .getPrivAppPermissions(pkg.packageName); 11719 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11720 if (!whitelisted) { 11721 Slog.w(TAG, "Privileged permission " + perm + " for package " 11722 + pkg.packageName + " - not in privapp-permissions whitelist"); 11723 // Only report violations for apps on system image 11724 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11725 if (mPrivappPermissionsViolations == null) { 11726 mPrivappPermissionsViolations = new ArraySet<>(); 11727 } 11728 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11729 } 11730 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11731 return false; 11732 } 11733 } 11734 } 11735 boolean allowed = (compareSignatures( 11736 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11737 == PackageManager.SIGNATURE_MATCH) 11738 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11739 == PackageManager.SIGNATURE_MATCH); 11740 if (!allowed && privilegedPermission) { 11741 if (isSystemApp(pkg)) { 11742 // For updated system applications, a system permission 11743 // is granted only if it had been defined by the original application. 11744 if (pkg.isUpdatedSystemApp()) { 11745 final PackageSetting sysPs = mSettings 11746 .getDisabledSystemPkgLPr(pkg.packageName); 11747 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11748 // If the original was granted this permission, we take 11749 // that grant decision as read and propagate it to the 11750 // update. 11751 if (sysPs.isPrivileged()) { 11752 allowed = true; 11753 } 11754 } else { 11755 // The system apk may have been updated with an older 11756 // version of the one on the data partition, but which 11757 // granted a new system permission that it didn't have 11758 // before. In this case we do want to allow the app to 11759 // now get the new permission if the ancestral apk is 11760 // privileged to get it. 11761 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11762 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11763 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11764 allowed = true; 11765 break; 11766 } 11767 } 11768 } 11769 // Also if a privileged parent package on the system image or any of 11770 // its children requested a privileged permission, the updated child 11771 // packages can also get the permission. 11772 if (pkg.parentPackage != null) { 11773 final PackageSetting disabledSysParentPs = mSettings 11774 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11775 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11776 && disabledSysParentPs.isPrivileged()) { 11777 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11778 allowed = true; 11779 } else if (disabledSysParentPs.pkg.childPackages != null) { 11780 final int count = disabledSysParentPs.pkg.childPackages.size(); 11781 for (int i = 0; i < count; i++) { 11782 PackageParser.Package disabledSysChildPkg = 11783 disabledSysParentPs.pkg.childPackages.get(i); 11784 if (isPackageRequestingPermission(disabledSysChildPkg, 11785 perm)) { 11786 allowed = true; 11787 break; 11788 } 11789 } 11790 } 11791 } 11792 } 11793 } 11794 } else { 11795 allowed = isPrivilegedApp(pkg); 11796 } 11797 } 11798 } 11799 if (!allowed) { 11800 if (!allowed && (bp.protectionLevel 11801 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11802 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11803 // If this was a previously normal/dangerous permission that got moved 11804 // to a system permission as part of the runtime permission redesign, then 11805 // we still want to blindly grant it to old apps. 11806 allowed = true; 11807 } 11808 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11809 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11810 // If this permission is to be granted to the system installer and 11811 // this app is an installer, then it gets the permission. 11812 allowed = true; 11813 } 11814 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11815 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11816 // If this permission is to be granted to the system verifier and 11817 // this app is a verifier, then it gets the permission. 11818 allowed = true; 11819 } 11820 if (!allowed && (bp.protectionLevel 11821 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11822 && isSystemApp(pkg)) { 11823 // Any pre-installed system app is allowed to get this permission. 11824 allowed = true; 11825 } 11826 if (!allowed && (bp.protectionLevel 11827 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11828 // For development permissions, a development permission 11829 // is granted only if it was already granted. 11830 allowed = origPermissions.hasInstallPermission(perm); 11831 } 11832 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11833 && pkg.packageName.equals(mSetupWizardPackage)) { 11834 // If this permission is to be granted to the system setup wizard and 11835 // this app is a setup wizard, then it gets the permission. 11836 allowed = true; 11837 } 11838 } 11839 return allowed; 11840 } 11841 11842 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11843 final int permCount = pkg.requestedPermissions.size(); 11844 for (int j = 0; j < permCount; j++) { 11845 String requestedPermission = pkg.requestedPermissions.get(j); 11846 if (permission.equals(requestedPermission)) { 11847 return true; 11848 } 11849 } 11850 return false; 11851 } 11852 11853 final class ActivityIntentResolver 11854 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11855 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11856 boolean defaultOnly, int userId) { 11857 if (!sUserManager.exists(userId)) return null; 11858 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11859 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11860 } 11861 11862 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11863 int userId) { 11864 if (!sUserManager.exists(userId)) return null; 11865 mFlags = flags; 11866 return super.queryIntent(intent, resolvedType, 11867 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11868 userId); 11869 } 11870 11871 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11872 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11873 if (!sUserManager.exists(userId)) return null; 11874 if (packageActivities == null) { 11875 return null; 11876 } 11877 mFlags = flags; 11878 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11879 final int N = packageActivities.size(); 11880 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11881 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11882 11883 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11884 for (int i = 0; i < N; ++i) { 11885 intentFilters = packageActivities.get(i).intents; 11886 if (intentFilters != null && intentFilters.size() > 0) { 11887 PackageParser.ActivityIntentInfo[] array = 11888 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11889 intentFilters.toArray(array); 11890 listCut.add(array); 11891 } 11892 } 11893 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11894 } 11895 11896 /** 11897 * Finds a privileged activity that matches the specified activity names. 11898 */ 11899 private PackageParser.Activity findMatchingActivity( 11900 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11901 for (PackageParser.Activity sysActivity : activityList) { 11902 if (sysActivity.info.name.equals(activityInfo.name)) { 11903 return sysActivity; 11904 } 11905 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11906 return sysActivity; 11907 } 11908 if (sysActivity.info.targetActivity != null) { 11909 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11910 return sysActivity; 11911 } 11912 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11913 return sysActivity; 11914 } 11915 } 11916 } 11917 return null; 11918 } 11919 11920 public class IterGenerator<E> { 11921 public Iterator<E> generate(ActivityIntentInfo info) { 11922 return null; 11923 } 11924 } 11925 11926 public class ActionIterGenerator extends IterGenerator<String> { 11927 @Override 11928 public Iterator<String> generate(ActivityIntentInfo info) { 11929 return info.actionsIterator(); 11930 } 11931 } 11932 11933 public class CategoriesIterGenerator extends IterGenerator<String> { 11934 @Override 11935 public Iterator<String> generate(ActivityIntentInfo info) { 11936 return info.categoriesIterator(); 11937 } 11938 } 11939 11940 public class SchemesIterGenerator extends IterGenerator<String> { 11941 @Override 11942 public Iterator<String> generate(ActivityIntentInfo info) { 11943 return info.schemesIterator(); 11944 } 11945 } 11946 11947 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11948 @Override 11949 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11950 return info.authoritiesIterator(); 11951 } 11952 } 11953 11954 /** 11955 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11956 * MODIFIED. Do not pass in a list that should not be changed. 11957 */ 11958 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11959 IterGenerator<T> generator, Iterator<T> searchIterator) { 11960 // loop through the set of actions; every one must be found in the intent filter 11961 while (searchIterator.hasNext()) { 11962 // we must have at least one filter in the list to consider a match 11963 if (intentList.size() == 0) { 11964 break; 11965 } 11966 11967 final T searchAction = searchIterator.next(); 11968 11969 // loop through the set of intent filters 11970 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11971 while (intentIter.hasNext()) { 11972 final ActivityIntentInfo intentInfo = intentIter.next(); 11973 boolean selectionFound = false; 11974 11975 // loop through the intent filter's selection criteria; at least one 11976 // of them must match the searched criteria 11977 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11978 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11979 final T intentSelection = intentSelectionIter.next(); 11980 if (intentSelection != null && intentSelection.equals(searchAction)) { 11981 selectionFound = true; 11982 break; 11983 } 11984 } 11985 11986 // the selection criteria wasn't found in this filter's set; this filter 11987 // is not a potential match 11988 if (!selectionFound) { 11989 intentIter.remove(); 11990 } 11991 } 11992 } 11993 } 11994 11995 private boolean isProtectedAction(ActivityIntentInfo filter) { 11996 final Iterator<String> actionsIter = filter.actionsIterator(); 11997 while (actionsIter != null && actionsIter.hasNext()) { 11998 final String filterAction = actionsIter.next(); 11999 if (PROTECTED_ACTIONS.contains(filterAction)) { 12000 return true; 12001 } 12002 } 12003 return false; 12004 } 12005 12006 /** 12007 * Adjusts the priority of the given intent filter according to policy. 12008 * <p> 12009 * <ul> 12010 * <li>The priority for non privileged applications is capped to '0'</li> 12011 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12012 * <li>The priority for unbundled updates to privileged applications is capped to the 12013 * priority defined on the system partition</li> 12014 * </ul> 12015 * <p> 12016 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12017 * allowed to obtain any priority on any action. 12018 */ 12019 private void adjustPriority( 12020 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12021 // nothing to do; priority is fine as-is 12022 if (intent.getPriority() <= 0) { 12023 return; 12024 } 12025 12026 final ActivityInfo activityInfo = intent.activity.info; 12027 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12028 12029 final boolean privilegedApp = 12030 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12031 if (!privilegedApp) { 12032 // non-privileged applications can never define a priority >0 12033 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12034 + " package: " + applicationInfo.packageName 12035 + " activity: " + intent.activity.className 12036 + " origPrio: " + intent.getPriority()); 12037 intent.setPriority(0); 12038 return; 12039 } 12040 12041 if (systemActivities == null) { 12042 // the system package is not disabled; we're parsing the system partition 12043 if (isProtectedAction(intent)) { 12044 if (mDeferProtectedFilters) { 12045 // We can't deal with these just yet. No component should ever obtain a 12046 // >0 priority for a protected actions, with ONE exception -- the setup 12047 // wizard. The setup wizard, however, cannot be known until we're able to 12048 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12049 // until all intent filters have been processed. Chicken, meet egg. 12050 // Let the filter temporarily have a high priority and rectify the 12051 // priorities after all system packages have been scanned. 12052 mProtectedFilters.add(intent); 12053 if (DEBUG_FILTERS) { 12054 Slog.i(TAG, "Protected action; save for later;" 12055 + " package: " + applicationInfo.packageName 12056 + " activity: " + intent.activity.className 12057 + " origPrio: " + intent.getPriority()); 12058 } 12059 return; 12060 } else { 12061 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12062 Slog.i(TAG, "No setup wizard;" 12063 + " All protected intents capped to priority 0"); 12064 } 12065 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12066 if (DEBUG_FILTERS) { 12067 Slog.i(TAG, "Found setup wizard;" 12068 + " allow priority " + intent.getPriority() + ";" 12069 + " package: " + intent.activity.info.packageName 12070 + " activity: " + intent.activity.className 12071 + " priority: " + intent.getPriority()); 12072 } 12073 // setup wizard gets whatever it wants 12074 return; 12075 } 12076 Slog.w(TAG, "Protected action; cap priority to 0;" 12077 + " package: " + intent.activity.info.packageName 12078 + " activity: " + intent.activity.className 12079 + " origPrio: " + intent.getPriority()); 12080 intent.setPriority(0); 12081 return; 12082 } 12083 } 12084 // privileged apps on the system image get whatever priority they request 12085 return; 12086 } 12087 12088 // privileged app unbundled update ... try to find the same activity 12089 final PackageParser.Activity foundActivity = 12090 findMatchingActivity(systemActivities, activityInfo); 12091 if (foundActivity == null) { 12092 // this is a new activity; it cannot obtain >0 priority 12093 if (DEBUG_FILTERS) { 12094 Slog.i(TAG, "New activity; cap priority to 0;" 12095 + " package: " + applicationInfo.packageName 12096 + " activity: " + intent.activity.className 12097 + " origPrio: " + intent.getPriority()); 12098 } 12099 intent.setPriority(0); 12100 return; 12101 } 12102 12103 // found activity, now check for filter equivalence 12104 12105 // a shallow copy is enough; we modify the list, not its contents 12106 final List<ActivityIntentInfo> intentListCopy = 12107 new ArrayList<>(foundActivity.intents); 12108 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12109 12110 // find matching action subsets 12111 final Iterator<String> actionsIterator = intent.actionsIterator(); 12112 if (actionsIterator != null) { 12113 getIntentListSubset( 12114 intentListCopy, new ActionIterGenerator(), actionsIterator); 12115 if (intentListCopy.size() == 0) { 12116 // no more intents to match; we're not equivalent 12117 if (DEBUG_FILTERS) { 12118 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12119 + " package: " + applicationInfo.packageName 12120 + " activity: " + intent.activity.className 12121 + " origPrio: " + intent.getPriority()); 12122 } 12123 intent.setPriority(0); 12124 return; 12125 } 12126 } 12127 12128 // find matching category subsets 12129 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12130 if (categoriesIterator != null) { 12131 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12132 categoriesIterator); 12133 if (intentListCopy.size() == 0) { 12134 // no more intents to match; we're not equivalent 12135 if (DEBUG_FILTERS) { 12136 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12137 + " package: " + applicationInfo.packageName 12138 + " activity: " + intent.activity.className 12139 + " origPrio: " + intent.getPriority()); 12140 } 12141 intent.setPriority(0); 12142 return; 12143 } 12144 } 12145 12146 // find matching schemes subsets 12147 final Iterator<String> schemesIterator = intent.schemesIterator(); 12148 if (schemesIterator != null) { 12149 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12150 schemesIterator); 12151 if (intentListCopy.size() == 0) { 12152 // no more intents to match; we're not equivalent 12153 if (DEBUG_FILTERS) { 12154 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12155 + " package: " + applicationInfo.packageName 12156 + " activity: " + intent.activity.className 12157 + " origPrio: " + intent.getPriority()); 12158 } 12159 intent.setPriority(0); 12160 return; 12161 } 12162 } 12163 12164 // find matching authorities subsets 12165 final Iterator<IntentFilter.AuthorityEntry> 12166 authoritiesIterator = intent.authoritiesIterator(); 12167 if (authoritiesIterator != null) { 12168 getIntentListSubset(intentListCopy, 12169 new AuthoritiesIterGenerator(), 12170 authoritiesIterator); 12171 if (intentListCopy.size() == 0) { 12172 // no more intents to match; we're not equivalent 12173 if (DEBUG_FILTERS) { 12174 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12175 + " package: " + applicationInfo.packageName 12176 + " activity: " + intent.activity.className 12177 + " origPrio: " + intent.getPriority()); 12178 } 12179 intent.setPriority(0); 12180 return; 12181 } 12182 } 12183 12184 // we found matching filter(s); app gets the max priority of all intents 12185 int cappedPriority = 0; 12186 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12187 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12188 } 12189 if (intent.getPriority() > cappedPriority) { 12190 if (DEBUG_FILTERS) { 12191 Slog.i(TAG, "Found matching filter(s);" 12192 + " cap priority to " + cappedPriority + ";" 12193 + " package: " + applicationInfo.packageName 12194 + " activity: " + intent.activity.className 12195 + " origPrio: " + intent.getPriority()); 12196 } 12197 intent.setPriority(cappedPriority); 12198 return; 12199 } 12200 // all this for nothing; the requested priority was <= what was on the system 12201 } 12202 12203 public final void addActivity(PackageParser.Activity a, String type) { 12204 mActivities.put(a.getComponentName(), a); 12205 if (DEBUG_SHOW_INFO) 12206 Log.v( 12207 TAG, " " + type + " " + 12208 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12209 if (DEBUG_SHOW_INFO) 12210 Log.v(TAG, " Class=" + a.info.name); 12211 final int NI = a.intents.size(); 12212 for (int j=0; j<NI; j++) { 12213 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12214 if ("activity".equals(type)) { 12215 final PackageSetting ps = 12216 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12217 final List<PackageParser.Activity> systemActivities = 12218 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12219 adjustPriority(systemActivities, intent); 12220 } 12221 if (DEBUG_SHOW_INFO) { 12222 Log.v(TAG, " IntentFilter:"); 12223 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12224 } 12225 if (!intent.debugCheck()) { 12226 Log.w(TAG, "==> For Activity " + a.info.name); 12227 } 12228 addFilter(intent); 12229 } 12230 } 12231 12232 public final void removeActivity(PackageParser.Activity a, String type) { 12233 mActivities.remove(a.getComponentName()); 12234 if (DEBUG_SHOW_INFO) { 12235 Log.v(TAG, " " + type + " " 12236 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12237 : a.info.name) + ":"); 12238 Log.v(TAG, " Class=" + a.info.name); 12239 } 12240 final int NI = a.intents.size(); 12241 for (int j=0; j<NI; j++) { 12242 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12243 if (DEBUG_SHOW_INFO) { 12244 Log.v(TAG, " IntentFilter:"); 12245 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12246 } 12247 removeFilter(intent); 12248 } 12249 } 12250 12251 @Override 12252 protected boolean allowFilterResult( 12253 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12254 ActivityInfo filterAi = filter.activity.info; 12255 for (int i=dest.size()-1; i>=0; i--) { 12256 ActivityInfo destAi = dest.get(i).activityInfo; 12257 if (destAi.name == filterAi.name 12258 && destAi.packageName == filterAi.packageName) { 12259 return false; 12260 } 12261 } 12262 return true; 12263 } 12264 12265 @Override 12266 protected ActivityIntentInfo[] newArray(int size) { 12267 return new ActivityIntentInfo[size]; 12268 } 12269 12270 @Override 12271 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12272 if (!sUserManager.exists(userId)) return true; 12273 PackageParser.Package p = filter.activity.owner; 12274 if (p != null) { 12275 PackageSetting ps = (PackageSetting)p.mExtras; 12276 if (ps != null) { 12277 // System apps are never considered stopped for purposes of 12278 // filtering, because there may be no way for the user to 12279 // actually re-launch them. 12280 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12281 && ps.getStopped(userId); 12282 } 12283 } 12284 return false; 12285 } 12286 12287 @Override 12288 protected boolean isPackageForFilter(String packageName, 12289 PackageParser.ActivityIntentInfo info) { 12290 return packageName.equals(info.activity.owner.packageName); 12291 } 12292 12293 @Override 12294 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12295 int match, int userId) { 12296 if (!sUserManager.exists(userId)) return null; 12297 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12298 return null; 12299 } 12300 final PackageParser.Activity activity = info.activity; 12301 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12302 if (ps == null) { 12303 return null; 12304 } 12305 final PackageUserState userState = ps.readUserState(userId); 12306 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12307 userState, userId); 12308 if (ai == null) { 12309 return null; 12310 } 12311 final boolean matchVisibleToInstantApp = 12312 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12313 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12314 // throw out filters that aren't visible to ephemeral apps 12315 if (matchVisibleToInstantApp 12316 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12317 return null; 12318 } 12319 // throw out ephemeral filters if we're not explicitly requesting them 12320 if (!isInstantApp && userState.instantApp) { 12321 return null; 12322 } 12323 final ResolveInfo res = new ResolveInfo(); 12324 res.activityInfo = ai; 12325 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12326 res.filter = info; 12327 } 12328 if (info != null) { 12329 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12330 } 12331 res.priority = info.getPriority(); 12332 res.preferredOrder = activity.owner.mPreferredOrder; 12333 //System.out.println("Result: " + res.activityInfo.className + 12334 // " = " + res.priority); 12335 res.match = match; 12336 res.isDefault = info.hasDefault; 12337 res.labelRes = info.labelRes; 12338 res.nonLocalizedLabel = info.nonLocalizedLabel; 12339 if (userNeedsBadging(userId)) { 12340 res.noResourceId = true; 12341 } else { 12342 res.icon = info.icon; 12343 } 12344 res.iconResourceId = info.icon; 12345 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12346 res.instantAppAvailable = userState.instantApp; 12347 return res; 12348 } 12349 12350 @Override 12351 protected void sortResults(List<ResolveInfo> results) { 12352 Collections.sort(results, mResolvePrioritySorter); 12353 } 12354 12355 @Override 12356 protected void dumpFilter(PrintWriter out, String prefix, 12357 PackageParser.ActivityIntentInfo filter) { 12358 out.print(prefix); out.print( 12359 Integer.toHexString(System.identityHashCode(filter.activity))); 12360 out.print(' '); 12361 filter.activity.printComponentShortName(out); 12362 out.print(" filter "); 12363 out.println(Integer.toHexString(System.identityHashCode(filter))); 12364 } 12365 12366 @Override 12367 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12368 return filter.activity; 12369 } 12370 12371 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12372 PackageParser.Activity activity = (PackageParser.Activity)label; 12373 out.print(prefix); out.print( 12374 Integer.toHexString(System.identityHashCode(activity))); 12375 out.print(' '); 12376 activity.printComponentShortName(out); 12377 if (count > 1) { 12378 out.print(" ("); out.print(count); out.print(" filters)"); 12379 } 12380 out.println(); 12381 } 12382 12383 // Keys are String (activity class name), values are Activity. 12384 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12385 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12386 private int mFlags; 12387 } 12388 12389 private final class ServiceIntentResolver 12390 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12391 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12392 boolean defaultOnly, int userId) { 12393 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12394 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12395 } 12396 12397 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12398 int userId) { 12399 if (!sUserManager.exists(userId)) return null; 12400 mFlags = flags; 12401 return super.queryIntent(intent, resolvedType, 12402 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12403 userId); 12404 } 12405 12406 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12407 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12408 if (!sUserManager.exists(userId)) return null; 12409 if (packageServices == null) { 12410 return null; 12411 } 12412 mFlags = flags; 12413 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12414 final int N = packageServices.size(); 12415 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12416 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12417 12418 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12419 for (int i = 0; i < N; ++i) { 12420 intentFilters = packageServices.get(i).intents; 12421 if (intentFilters != null && intentFilters.size() > 0) { 12422 PackageParser.ServiceIntentInfo[] array = 12423 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12424 intentFilters.toArray(array); 12425 listCut.add(array); 12426 } 12427 } 12428 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12429 } 12430 12431 public final void addService(PackageParser.Service s) { 12432 mServices.put(s.getComponentName(), s); 12433 if (DEBUG_SHOW_INFO) { 12434 Log.v(TAG, " " 12435 + (s.info.nonLocalizedLabel != null 12436 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12437 Log.v(TAG, " Class=" + s.info.name); 12438 } 12439 final int NI = s.intents.size(); 12440 int j; 12441 for (j=0; j<NI; j++) { 12442 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12443 if (DEBUG_SHOW_INFO) { 12444 Log.v(TAG, " IntentFilter:"); 12445 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12446 } 12447 if (!intent.debugCheck()) { 12448 Log.w(TAG, "==> For Service " + s.info.name); 12449 } 12450 addFilter(intent); 12451 } 12452 } 12453 12454 public final void removeService(PackageParser.Service s) { 12455 mServices.remove(s.getComponentName()); 12456 if (DEBUG_SHOW_INFO) { 12457 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12458 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12459 Log.v(TAG, " Class=" + s.info.name); 12460 } 12461 final int NI = s.intents.size(); 12462 int j; 12463 for (j=0; j<NI; j++) { 12464 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12465 if (DEBUG_SHOW_INFO) { 12466 Log.v(TAG, " IntentFilter:"); 12467 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12468 } 12469 removeFilter(intent); 12470 } 12471 } 12472 12473 @Override 12474 protected boolean allowFilterResult( 12475 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12476 ServiceInfo filterSi = filter.service.info; 12477 for (int i=dest.size()-1; i>=0; i--) { 12478 ServiceInfo destAi = dest.get(i).serviceInfo; 12479 if (destAi.name == filterSi.name 12480 && destAi.packageName == filterSi.packageName) { 12481 return false; 12482 } 12483 } 12484 return true; 12485 } 12486 12487 @Override 12488 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12489 return new PackageParser.ServiceIntentInfo[size]; 12490 } 12491 12492 @Override 12493 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12494 if (!sUserManager.exists(userId)) return true; 12495 PackageParser.Package p = filter.service.owner; 12496 if (p != null) { 12497 PackageSetting ps = (PackageSetting)p.mExtras; 12498 if (ps != null) { 12499 // System apps are never considered stopped for purposes of 12500 // filtering, because there may be no way for the user to 12501 // actually re-launch them. 12502 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12503 && ps.getStopped(userId); 12504 } 12505 } 12506 return false; 12507 } 12508 12509 @Override 12510 protected boolean isPackageForFilter(String packageName, 12511 PackageParser.ServiceIntentInfo info) { 12512 return packageName.equals(info.service.owner.packageName); 12513 } 12514 12515 @Override 12516 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12517 int match, int userId) { 12518 if (!sUserManager.exists(userId)) return null; 12519 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12520 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12521 return null; 12522 } 12523 final PackageParser.Service service = info.service; 12524 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12525 if (ps == null) { 12526 return null; 12527 } 12528 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12529 ps.readUserState(userId), userId); 12530 if (si == null) { 12531 return null; 12532 } 12533 final ResolveInfo res = new ResolveInfo(); 12534 res.serviceInfo = si; 12535 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12536 res.filter = filter; 12537 } 12538 res.priority = info.getPriority(); 12539 res.preferredOrder = service.owner.mPreferredOrder; 12540 res.match = match; 12541 res.isDefault = info.hasDefault; 12542 res.labelRes = info.labelRes; 12543 res.nonLocalizedLabel = info.nonLocalizedLabel; 12544 res.icon = info.icon; 12545 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12546 return res; 12547 } 12548 12549 @Override 12550 protected void sortResults(List<ResolveInfo> results) { 12551 Collections.sort(results, mResolvePrioritySorter); 12552 } 12553 12554 @Override 12555 protected void dumpFilter(PrintWriter out, String prefix, 12556 PackageParser.ServiceIntentInfo filter) { 12557 out.print(prefix); out.print( 12558 Integer.toHexString(System.identityHashCode(filter.service))); 12559 out.print(' '); 12560 filter.service.printComponentShortName(out); 12561 out.print(" filter "); 12562 out.println(Integer.toHexString(System.identityHashCode(filter))); 12563 } 12564 12565 @Override 12566 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12567 return filter.service; 12568 } 12569 12570 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12571 PackageParser.Service service = (PackageParser.Service)label; 12572 out.print(prefix); out.print( 12573 Integer.toHexString(System.identityHashCode(service))); 12574 out.print(' '); 12575 service.printComponentShortName(out); 12576 if (count > 1) { 12577 out.print(" ("); out.print(count); out.print(" filters)"); 12578 } 12579 out.println(); 12580 } 12581 12582// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12583// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12584// final List<ResolveInfo> retList = Lists.newArrayList(); 12585// while (i.hasNext()) { 12586// final ResolveInfo resolveInfo = (ResolveInfo) i; 12587// if (isEnabledLP(resolveInfo.serviceInfo)) { 12588// retList.add(resolveInfo); 12589// } 12590// } 12591// return retList; 12592// } 12593 12594 // Keys are String (activity class name), values are Activity. 12595 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12596 = new ArrayMap<ComponentName, PackageParser.Service>(); 12597 private int mFlags; 12598 } 12599 12600 private final class ProviderIntentResolver 12601 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12602 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12603 boolean defaultOnly, int userId) { 12604 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12605 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12606 } 12607 12608 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12609 int userId) { 12610 if (!sUserManager.exists(userId)) 12611 return null; 12612 mFlags = flags; 12613 return super.queryIntent(intent, resolvedType, 12614 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12615 userId); 12616 } 12617 12618 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12619 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12620 if (!sUserManager.exists(userId)) 12621 return null; 12622 if (packageProviders == null) { 12623 return null; 12624 } 12625 mFlags = flags; 12626 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12627 final int N = packageProviders.size(); 12628 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12629 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12630 12631 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12632 for (int i = 0; i < N; ++i) { 12633 intentFilters = packageProviders.get(i).intents; 12634 if (intentFilters != null && intentFilters.size() > 0) { 12635 PackageParser.ProviderIntentInfo[] array = 12636 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12637 intentFilters.toArray(array); 12638 listCut.add(array); 12639 } 12640 } 12641 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12642 } 12643 12644 public final void addProvider(PackageParser.Provider p) { 12645 if (mProviders.containsKey(p.getComponentName())) { 12646 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12647 return; 12648 } 12649 12650 mProviders.put(p.getComponentName(), p); 12651 if (DEBUG_SHOW_INFO) { 12652 Log.v(TAG, " " 12653 + (p.info.nonLocalizedLabel != null 12654 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12655 Log.v(TAG, " Class=" + p.info.name); 12656 } 12657 final int NI = p.intents.size(); 12658 int j; 12659 for (j = 0; j < NI; j++) { 12660 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12661 if (DEBUG_SHOW_INFO) { 12662 Log.v(TAG, " IntentFilter:"); 12663 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12664 } 12665 if (!intent.debugCheck()) { 12666 Log.w(TAG, "==> For Provider " + p.info.name); 12667 } 12668 addFilter(intent); 12669 } 12670 } 12671 12672 public final void removeProvider(PackageParser.Provider p) { 12673 mProviders.remove(p.getComponentName()); 12674 if (DEBUG_SHOW_INFO) { 12675 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12676 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12677 Log.v(TAG, " Class=" + p.info.name); 12678 } 12679 final int NI = p.intents.size(); 12680 int j; 12681 for (j = 0; j < NI; j++) { 12682 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12683 if (DEBUG_SHOW_INFO) { 12684 Log.v(TAG, " IntentFilter:"); 12685 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12686 } 12687 removeFilter(intent); 12688 } 12689 } 12690 12691 @Override 12692 protected boolean allowFilterResult( 12693 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12694 ProviderInfo filterPi = filter.provider.info; 12695 for (int i = dest.size() - 1; i >= 0; i--) { 12696 ProviderInfo destPi = dest.get(i).providerInfo; 12697 if (destPi.name == filterPi.name 12698 && destPi.packageName == filterPi.packageName) { 12699 return false; 12700 } 12701 } 12702 return true; 12703 } 12704 12705 @Override 12706 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12707 return new PackageParser.ProviderIntentInfo[size]; 12708 } 12709 12710 @Override 12711 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12712 if (!sUserManager.exists(userId)) 12713 return true; 12714 PackageParser.Package p = filter.provider.owner; 12715 if (p != null) { 12716 PackageSetting ps = (PackageSetting) p.mExtras; 12717 if (ps != null) { 12718 // System apps are never considered stopped for purposes of 12719 // filtering, because there may be no way for the user to 12720 // actually re-launch them. 12721 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12722 && ps.getStopped(userId); 12723 } 12724 } 12725 return false; 12726 } 12727 12728 @Override 12729 protected boolean isPackageForFilter(String packageName, 12730 PackageParser.ProviderIntentInfo info) { 12731 return packageName.equals(info.provider.owner.packageName); 12732 } 12733 12734 @Override 12735 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12736 int match, int userId) { 12737 if (!sUserManager.exists(userId)) 12738 return null; 12739 final PackageParser.ProviderIntentInfo info = filter; 12740 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12741 return null; 12742 } 12743 final PackageParser.Provider provider = info.provider; 12744 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12745 if (ps == null) { 12746 return null; 12747 } 12748 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12749 ps.readUserState(userId), userId); 12750 if (pi == null) { 12751 return null; 12752 } 12753 final ResolveInfo res = new ResolveInfo(); 12754 res.providerInfo = pi; 12755 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12756 res.filter = filter; 12757 } 12758 res.priority = info.getPriority(); 12759 res.preferredOrder = provider.owner.mPreferredOrder; 12760 res.match = match; 12761 res.isDefault = info.hasDefault; 12762 res.labelRes = info.labelRes; 12763 res.nonLocalizedLabel = info.nonLocalizedLabel; 12764 res.icon = info.icon; 12765 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12766 return res; 12767 } 12768 12769 @Override 12770 protected void sortResults(List<ResolveInfo> results) { 12771 Collections.sort(results, mResolvePrioritySorter); 12772 } 12773 12774 @Override 12775 protected void dumpFilter(PrintWriter out, String prefix, 12776 PackageParser.ProviderIntentInfo filter) { 12777 out.print(prefix); 12778 out.print( 12779 Integer.toHexString(System.identityHashCode(filter.provider))); 12780 out.print(' '); 12781 filter.provider.printComponentShortName(out); 12782 out.print(" filter "); 12783 out.println(Integer.toHexString(System.identityHashCode(filter))); 12784 } 12785 12786 @Override 12787 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12788 return filter.provider; 12789 } 12790 12791 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12792 PackageParser.Provider provider = (PackageParser.Provider)label; 12793 out.print(prefix); out.print( 12794 Integer.toHexString(System.identityHashCode(provider))); 12795 out.print(' '); 12796 provider.printComponentShortName(out); 12797 if (count > 1) { 12798 out.print(" ("); out.print(count); out.print(" filters)"); 12799 } 12800 out.println(); 12801 } 12802 12803 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12804 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12805 private int mFlags; 12806 } 12807 12808 static final class EphemeralIntentResolver 12809 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12810 /** 12811 * The result that has the highest defined order. Ordering applies on a 12812 * per-package basis. Mapping is from package name to Pair of order and 12813 * EphemeralResolveInfo. 12814 * <p> 12815 * NOTE: This is implemented as a field variable for convenience and efficiency. 12816 * By having a field variable, we're able to track filter ordering as soon as 12817 * a non-zero order is defined. Otherwise, multiple loops across the result set 12818 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12819 * this needs to be contained entirely within {@link #filterResults}. 12820 */ 12821 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 12822 12823 @Override 12824 protected AuxiliaryResolveInfo[] newArray(int size) { 12825 return new AuxiliaryResolveInfo[size]; 12826 } 12827 12828 @Override 12829 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12830 return true; 12831 } 12832 12833 @Override 12834 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12835 int userId) { 12836 if (!sUserManager.exists(userId)) { 12837 return null; 12838 } 12839 final String packageName = responseObj.resolveInfo.getPackageName(); 12840 final Integer order = responseObj.getOrder(); 12841 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 12842 mOrderResult.get(packageName); 12843 // ordering is enabled and this item's order isn't high enough 12844 if (lastOrderResult != null && lastOrderResult.first >= order) { 12845 return null; 12846 } 12847 final EphemeralResolveInfo res = responseObj.resolveInfo; 12848 if (order > 0) { 12849 // non-zero order, enable ordering 12850 mOrderResult.put(packageName, new Pair<>(order, res)); 12851 } 12852 return responseObj; 12853 } 12854 12855 @Override 12856 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12857 // only do work if ordering is enabled [most of the time it won't be] 12858 if (mOrderResult.size() == 0) { 12859 return; 12860 } 12861 int resultSize = results.size(); 12862 for (int i = 0; i < resultSize; i++) { 12863 final EphemeralResolveInfo info = results.get(i).resolveInfo; 12864 final String packageName = info.getPackageName(); 12865 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 12866 if (savedInfo == null) { 12867 // package doesn't having ordering 12868 continue; 12869 } 12870 if (savedInfo.second == info) { 12871 // circled back to the highest ordered item; remove from order list 12872 mOrderResult.remove(savedInfo); 12873 if (mOrderResult.size() == 0) { 12874 // no more ordered items 12875 break; 12876 } 12877 continue; 12878 } 12879 // item has a worse order, remove it from the result list 12880 results.remove(i); 12881 resultSize--; 12882 i--; 12883 } 12884 } 12885 } 12886 12887 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12888 new Comparator<ResolveInfo>() { 12889 public int compare(ResolveInfo r1, ResolveInfo r2) { 12890 int v1 = r1.priority; 12891 int v2 = r2.priority; 12892 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12893 if (v1 != v2) { 12894 return (v1 > v2) ? -1 : 1; 12895 } 12896 v1 = r1.preferredOrder; 12897 v2 = r2.preferredOrder; 12898 if (v1 != v2) { 12899 return (v1 > v2) ? -1 : 1; 12900 } 12901 if (r1.isDefault != r2.isDefault) { 12902 return r1.isDefault ? -1 : 1; 12903 } 12904 v1 = r1.match; 12905 v2 = r2.match; 12906 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12907 if (v1 != v2) { 12908 return (v1 > v2) ? -1 : 1; 12909 } 12910 if (r1.system != r2.system) { 12911 return r1.system ? -1 : 1; 12912 } 12913 if (r1.activityInfo != null) { 12914 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12915 } 12916 if (r1.serviceInfo != null) { 12917 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12918 } 12919 if (r1.providerInfo != null) { 12920 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12921 } 12922 return 0; 12923 } 12924 }; 12925 12926 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12927 new Comparator<ProviderInfo>() { 12928 public int compare(ProviderInfo p1, ProviderInfo p2) { 12929 final int v1 = p1.initOrder; 12930 final int v2 = p2.initOrder; 12931 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12932 } 12933 }; 12934 12935 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12936 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12937 final int[] userIds) { 12938 mHandler.post(new Runnable() { 12939 @Override 12940 public void run() { 12941 try { 12942 final IActivityManager am = ActivityManager.getService(); 12943 if (am == null) return; 12944 final int[] resolvedUserIds; 12945 if (userIds == null) { 12946 resolvedUserIds = am.getRunningUserIds(); 12947 } else { 12948 resolvedUserIds = userIds; 12949 } 12950 for (int id : resolvedUserIds) { 12951 final Intent intent = new Intent(action, 12952 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12953 if (extras != null) { 12954 intent.putExtras(extras); 12955 } 12956 if (targetPkg != null) { 12957 intent.setPackage(targetPkg); 12958 } 12959 // Modify the UID when posting to other users 12960 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12961 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12962 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12963 intent.putExtra(Intent.EXTRA_UID, uid); 12964 } 12965 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12966 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12967 if (DEBUG_BROADCASTS) { 12968 RuntimeException here = new RuntimeException("here"); 12969 here.fillInStackTrace(); 12970 Slog.d(TAG, "Sending to user " + id + ": " 12971 + intent.toShortString(false, true, false, false) 12972 + " " + intent.getExtras(), here); 12973 } 12974 am.broadcastIntent(null, intent, null, finishedReceiver, 12975 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12976 null, finishedReceiver != null, false, id); 12977 } 12978 } catch (RemoteException ex) { 12979 } 12980 } 12981 }); 12982 } 12983 12984 /** 12985 * Check if the external storage media is available. This is true if there 12986 * is a mounted external storage medium or if the external storage is 12987 * emulated. 12988 */ 12989 private boolean isExternalMediaAvailable() { 12990 return mMediaMounted || Environment.isExternalStorageEmulated(); 12991 } 12992 12993 @Override 12994 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12995 // writer 12996 synchronized (mPackages) { 12997 if (!isExternalMediaAvailable()) { 12998 // If the external storage is no longer mounted at this point, 12999 // the caller may not have been able to delete all of this 13000 // packages files and can not delete any more. Bail. 13001 return null; 13002 } 13003 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13004 if (lastPackage != null) { 13005 pkgs.remove(lastPackage); 13006 } 13007 if (pkgs.size() > 0) { 13008 return pkgs.get(0); 13009 } 13010 } 13011 return null; 13012 } 13013 13014 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13015 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13016 userId, andCode ? 1 : 0, packageName); 13017 if (mSystemReady) { 13018 msg.sendToTarget(); 13019 } else { 13020 if (mPostSystemReadyMessages == null) { 13021 mPostSystemReadyMessages = new ArrayList<>(); 13022 } 13023 mPostSystemReadyMessages.add(msg); 13024 } 13025 } 13026 13027 void startCleaningPackages() { 13028 // reader 13029 if (!isExternalMediaAvailable()) { 13030 return; 13031 } 13032 synchronized (mPackages) { 13033 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13034 return; 13035 } 13036 } 13037 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13038 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13039 IActivityManager am = ActivityManager.getService(); 13040 if (am != null) { 13041 try { 13042 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 13043 UserHandle.USER_SYSTEM); 13044 } catch (RemoteException e) { 13045 } 13046 } 13047 } 13048 13049 @Override 13050 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13051 int installFlags, String installerPackageName, int userId) { 13052 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13053 13054 final int callingUid = Binder.getCallingUid(); 13055 enforceCrossUserPermission(callingUid, userId, 13056 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13057 13058 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13059 try { 13060 if (observer != null) { 13061 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13062 } 13063 } catch (RemoteException re) { 13064 } 13065 return; 13066 } 13067 13068 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13069 installFlags |= PackageManager.INSTALL_FROM_ADB; 13070 13071 } else { 13072 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13073 // about installerPackageName. 13074 13075 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13076 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13077 } 13078 13079 UserHandle user; 13080 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13081 user = UserHandle.ALL; 13082 } else { 13083 user = new UserHandle(userId); 13084 } 13085 13086 // Only system components can circumvent runtime permissions when installing. 13087 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13088 && mContext.checkCallingOrSelfPermission(Manifest.permission 13089 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13090 throw new SecurityException("You need the " 13091 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13092 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13093 } 13094 13095 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13096 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13097 throw new IllegalArgumentException( 13098 "New installs into ASEC containers no longer supported"); 13099 } 13100 13101 final File originFile = new File(originPath); 13102 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13103 13104 final Message msg = mHandler.obtainMessage(INIT_COPY); 13105 final VerificationInfo verificationInfo = new VerificationInfo( 13106 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13107 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13108 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13109 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13110 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13111 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13112 msg.obj = params; 13113 13114 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13115 System.identityHashCode(msg.obj)); 13116 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13117 System.identityHashCode(msg.obj)); 13118 13119 mHandler.sendMessage(msg); 13120 } 13121 13122 13123 /** 13124 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13125 * it is acting on behalf on an enterprise or the user). 13126 * 13127 * Note that the ordering of the conditionals in this method is important. The checks we perform 13128 * are as follows, in this order: 13129 * 13130 * 1) If the install is being performed by a system app, we can trust the app to have set the 13131 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13132 * what it is. 13133 * 2) If the install is being performed by a device or profile owner app, the install reason 13134 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13135 * set the install reason correctly. If the app targets an older SDK version where install 13136 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13137 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13138 * 3) In all other cases, the install is being performed by a regular app that is neither part 13139 * of the system nor a device or profile owner. We have no reason to believe that this app is 13140 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13141 * set to enterprise policy and if so, change it to unknown instead. 13142 */ 13143 private int fixUpInstallReason(String installerPackageName, int installerUid, 13144 int installReason) { 13145 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13146 == PERMISSION_GRANTED) { 13147 // If the install is being performed by a system app, we trust that app to have set the 13148 // install reason correctly. 13149 return installReason; 13150 } 13151 13152 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13153 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13154 if (dpm != null) { 13155 ComponentName owner = null; 13156 try { 13157 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13158 if (owner == null) { 13159 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13160 } 13161 } catch (RemoteException e) { 13162 } 13163 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13164 // If the install is being performed by a device or profile owner, the install 13165 // reason should be enterprise policy. 13166 return PackageManager.INSTALL_REASON_POLICY; 13167 } 13168 } 13169 13170 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13171 // If the install is being performed by a regular app (i.e. neither system app nor 13172 // device or profile owner), we have no reason to believe that the app is acting on 13173 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13174 // change it to unknown instead. 13175 return PackageManager.INSTALL_REASON_UNKNOWN; 13176 } 13177 13178 // If the install is being performed by a regular app and the install reason was set to any 13179 // value but enterprise policy, leave the install reason unchanged. 13180 return installReason; 13181 } 13182 13183 void installStage(String packageName, File stagedDir, String stagedCid, 13184 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13185 String installerPackageName, int installerUid, UserHandle user, 13186 Certificate[][] certificates) { 13187 if (DEBUG_EPHEMERAL) { 13188 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13189 Slog.d(TAG, "Ephemeral install of " + packageName); 13190 } 13191 } 13192 final VerificationInfo verificationInfo = new VerificationInfo( 13193 sessionParams.originatingUri, sessionParams.referrerUri, 13194 sessionParams.originatingUid, installerUid); 13195 13196 final OriginInfo origin; 13197 if (stagedDir != null) { 13198 origin = OriginInfo.fromStagedFile(stagedDir); 13199 } else { 13200 origin = OriginInfo.fromStagedContainer(stagedCid); 13201 } 13202 13203 final Message msg = mHandler.obtainMessage(INIT_COPY); 13204 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13205 sessionParams.installReason); 13206 final InstallParams params = new InstallParams(origin, null, observer, 13207 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13208 verificationInfo, user, sessionParams.abiOverride, 13209 sessionParams.grantedRuntimePermissions, certificates, installReason); 13210 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13211 msg.obj = params; 13212 13213 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13214 System.identityHashCode(msg.obj)); 13215 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13216 System.identityHashCode(msg.obj)); 13217 13218 mHandler.sendMessage(msg); 13219 } 13220 13221 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13222 int userId) { 13223 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13224 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13225 } 13226 13227 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13228 int appId, int... userIds) { 13229 if (ArrayUtils.isEmpty(userIds)) { 13230 return; 13231 } 13232 Bundle extras = new Bundle(1); 13233 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13234 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13235 13236 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13237 packageName, extras, 0, null, null, userIds); 13238 if (isSystem) { 13239 mHandler.post(() -> { 13240 for (int userId : userIds) { 13241 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13242 } 13243 } 13244 ); 13245 } 13246 } 13247 13248 /** 13249 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13250 * automatically without needing an explicit launch. 13251 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13252 */ 13253 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13254 // If user is not running, the app didn't miss any broadcast 13255 if (!mUserManagerInternal.isUserRunning(userId)) { 13256 return; 13257 } 13258 final IActivityManager am = ActivityManager.getService(); 13259 try { 13260 // Deliver LOCKED_BOOT_COMPLETED first 13261 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13262 .setPackage(packageName); 13263 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13264 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13265 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13266 13267 // Deliver BOOT_COMPLETED only if user is unlocked 13268 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13269 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13270 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13271 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13272 } 13273 } catch (RemoteException e) { 13274 throw e.rethrowFromSystemServer(); 13275 } 13276 } 13277 13278 @Override 13279 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13280 int userId) { 13281 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13282 PackageSetting pkgSetting; 13283 final int uid = Binder.getCallingUid(); 13284 enforceCrossUserPermission(uid, userId, 13285 true /* requireFullPermission */, true /* checkShell */, 13286 "setApplicationHiddenSetting for user " + userId); 13287 13288 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13289 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13290 return false; 13291 } 13292 13293 long callingId = Binder.clearCallingIdentity(); 13294 try { 13295 boolean sendAdded = false; 13296 boolean sendRemoved = false; 13297 // writer 13298 synchronized (mPackages) { 13299 pkgSetting = mSettings.mPackages.get(packageName); 13300 if (pkgSetting == null) { 13301 return false; 13302 } 13303 // Do not allow "android" is being disabled 13304 if ("android".equals(packageName)) { 13305 Slog.w(TAG, "Cannot hide package: android"); 13306 return false; 13307 } 13308 // Cannot hide static shared libs as they are considered 13309 // a part of the using app (emulating static linking). Also 13310 // static libs are installed always on internal storage. 13311 PackageParser.Package pkg = mPackages.get(packageName); 13312 if (pkg != null && pkg.staticSharedLibName != null) { 13313 Slog.w(TAG, "Cannot hide package: " + packageName 13314 + " providing static shared library: " 13315 + pkg.staticSharedLibName); 13316 return false; 13317 } 13318 // Only allow protected packages to hide themselves. 13319 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13320 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13321 Slog.w(TAG, "Not hiding protected package: " + packageName); 13322 return false; 13323 } 13324 13325 if (pkgSetting.getHidden(userId) != hidden) { 13326 pkgSetting.setHidden(hidden, userId); 13327 mSettings.writePackageRestrictionsLPr(userId); 13328 if (hidden) { 13329 sendRemoved = true; 13330 } else { 13331 sendAdded = true; 13332 } 13333 } 13334 } 13335 if (sendAdded) { 13336 sendPackageAddedForUser(packageName, pkgSetting, userId); 13337 return true; 13338 } 13339 if (sendRemoved) { 13340 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13341 "hiding pkg"); 13342 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13343 return true; 13344 } 13345 } finally { 13346 Binder.restoreCallingIdentity(callingId); 13347 } 13348 return false; 13349 } 13350 13351 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13352 int userId) { 13353 final PackageRemovedInfo info = new PackageRemovedInfo(); 13354 info.removedPackage = packageName; 13355 info.removedUsers = new int[] {userId}; 13356 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13357 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13358 } 13359 13360 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13361 if (pkgList.length > 0) { 13362 Bundle extras = new Bundle(1); 13363 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13364 13365 sendPackageBroadcast( 13366 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13367 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13368 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13369 new int[] {userId}); 13370 } 13371 } 13372 13373 /** 13374 * Returns true if application is not found or there was an error. Otherwise it returns 13375 * the hidden state of the package for the given user. 13376 */ 13377 @Override 13378 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13379 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13381 true /* requireFullPermission */, false /* checkShell */, 13382 "getApplicationHidden for user " + userId); 13383 PackageSetting pkgSetting; 13384 long callingId = Binder.clearCallingIdentity(); 13385 try { 13386 // writer 13387 synchronized (mPackages) { 13388 pkgSetting = mSettings.mPackages.get(packageName); 13389 if (pkgSetting == null) { 13390 return true; 13391 } 13392 return pkgSetting.getHidden(userId); 13393 } 13394 } finally { 13395 Binder.restoreCallingIdentity(callingId); 13396 } 13397 } 13398 13399 /** 13400 * @hide 13401 */ 13402 @Override 13403 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13404 int installReason) { 13405 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13406 null); 13407 PackageSetting pkgSetting; 13408 final int uid = Binder.getCallingUid(); 13409 enforceCrossUserPermission(uid, userId, 13410 true /* requireFullPermission */, true /* checkShell */, 13411 "installExistingPackage for user " + userId); 13412 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13413 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13414 } 13415 13416 long callingId = Binder.clearCallingIdentity(); 13417 try { 13418 boolean installed = false; 13419 final boolean instantApp = 13420 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13421 final boolean fullApp = 13422 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13423 13424 // writer 13425 synchronized (mPackages) { 13426 pkgSetting = mSettings.mPackages.get(packageName); 13427 if (pkgSetting == null) { 13428 return PackageManager.INSTALL_FAILED_INVALID_URI; 13429 } 13430 if (!pkgSetting.getInstalled(userId)) { 13431 pkgSetting.setInstalled(true, userId); 13432 pkgSetting.setHidden(false, userId); 13433 pkgSetting.setInstallReason(installReason, userId); 13434 mSettings.writePackageRestrictionsLPr(userId); 13435 mSettings.writeKernelMappingLPr(pkgSetting); 13436 installed = true; 13437 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13438 // upgrade app from instant to full; we don't allow app downgrade 13439 installed = true; 13440 } 13441 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13442 } 13443 13444 if (installed) { 13445 if (pkgSetting.pkg != null) { 13446 synchronized (mInstallLock) { 13447 // We don't need to freeze for a brand new install 13448 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13449 } 13450 } 13451 sendPackageAddedForUser(packageName, pkgSetting, userId); 13452 synchronized (mPackages) { 13453 updateSequenceNumberLP(packageName, new int[]{ userId }); 13454 } 13455 } 13456 } finally { 13457 Binder.restoreCallingIdentity(callingId); 13458 } 13459 13460 return PackageManager.INSTALL_SUCCEEDED; 13461 } 13462 13463 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13464 boolean instantApp, boolean fullApp) { 13465 // no state specified; do nothing 13466 if (!instantApp && !fullApp) { 13467 return; 13468 } 13469 if (userId != UserHandle.USER_ALL) { 13470 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13471 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13472 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13473 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13474 } 13475 } else { 13476 for (int currentUserId : sUserManager.getUserIds()) { 13477 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13478 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13479 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13480 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13481 } 13482 } 13483 } 13484 } 13485 13486 boolean isUserRestricted(int userId, String restrictionKey) { 13487 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13488 if (restrictions.getBoolean(restrictionKey, false)) { 13489 Log.w(TAG, "User is restricted: " + restrictionKey); 13490 return true; 13491 } 13492 return false; 13493 } 13494 13495 @Override 13496 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13497 int userId) { 13498 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13499 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13500 true /* requireFullPermission */, true /* checkShell */, 13501 "setPackagesSuspended for user " + userId); 13502 13503 if (ArrayUtils.isEmpty(packageNames)) { 13504 return packageNames; 13505 } 13506 13507 // List of package names for whom the suspended state has changed. 13508 List<String> changedPackages = new ArrayList<>(packageNames.length); 13509 // List of package names for whom the suspended state is not set as requested in this 13510 // method. 13511 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13512 long callingId = Binder.clearCallingIdentity(); 13513 try { 13514 for (int i = 0; i < packageNames.length; i++) { 13515 String packageName = packageNames[i]; 13516 boolean changed = false; 13517 final int appId; 13518 synchronized (mPackages) { 13519 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13520 if (pkgSetting == null) { 13521 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13522 + "\". Skipping suspending/un-suspending."); 13523 unactionedPackages.add(packageName); 13524 continue; 13525 } 13526 appId = pkgSetting.appId; 13527 if (pkgSetting.getSuspended(userId) != suspended) { 13528 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13529 unactionedPackages.add(packageName); 13530 continue; 13531 } 13532 pkgSetting.setSuspended(suspended, userId); 13533 mSettings.writePackageRestrictionsLPr(userId); 13534 changed = true; 13535 changedPackages.add(packageName); 13536 } 13537 } 13538 13539 if (changed && suspended) { 13540 killApplication(packageName, UserHandle.getUid(userId, appId), 13541 "suspending package"); 13542 } 13543 } 13544 } finally { 13545 Binder.restoreCallingIdentity(callingId); 13546 } 13547 13548 if (!changedPackages.isEmpty()) { 13549 sendPackagesSuspendedForUser(changedPackages.toArray( 13550 new String[changedPackages.size()]), userId, suspended); 13551 } 13552 13553 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13554 } 13555 13556 @Override 13557 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13558 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13559 true /* requireFullPermission */, false /* checkShell */, 13560 "isPackageSuspendedForUser for user " + userId); 13561 synchronized (mPackages) { 13562 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13563 if (pkgSetting == null) { 13564 throw new IllegalArgumentException("Unknown target package: " + packageName); 13565 } 13566 return pkgSetting.getSuspended(userId); 13567 } 13568 } 13569 13570 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13571 if (isPackageDeviceAdmin(packageName, userId)) { 13572 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13573 + "\": has an active device admin"); 13574 return false; 13575 } 13576 13577 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13578 if (packageName.equals(activeLauncherPackageName)) { 13579 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13580 + "\": contains the active launcher"); 13581 return false; 13582 } 13583 13584 if (packageName.equals(mRequiredInstallerPackage)) { 13585 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13586 + "\": required for package installation"); 13587 return false; 13588 } 13589 13590 if (packageName.equals(mRequiredUninstallerPackage)) { 13591 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13592 + "\": required for package uninstallation"); 13593 return false; 13594 } 13595 13596 if (packageName.equals(mRequiredVerifierPackage)) { 13597 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13598 + "\": required for package verification"); 13599 return false; 13600 } 13601 13602 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13603 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13604 + "\": is the default dialer"); 13605 return false; 13606 } 13607 13608 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13609 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13610 + "\": protected package"); 13611 return false; 13612 } 13613 13614 // Cannot suspend static shared libs as they are considered 13615 // a part of the using app (emulating static linking). Also 13616 // static libs are installed always on internal storage. 13617 PackageParser.Package pkg = mPackages.get(packageName); 13618 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13619 Slog.w(TAG, "Cannot suspend package: " + packageName 13620 + " providing static shared library: " 13621 + pkg.staticSharedLibName); 13622 return false; 13623 } 13624 13625 return true; 13626 } 13627 13628 private String getActiveLauncherPackageName(int userId) { 13629 Intent intent = new Intent(Intent.ACTION_MAIN); 13630 intent.addCategory(Intent.CATEGORY_HOME); 13631 ResolveInfo resolveInfo = resolveIntent( 13632 intent, 13633 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13634 PackageManager.MATCH_DEFAULT_ONLY, 13635 userId); 13636 13637 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13638 } 13639 13640 private String getDefaultDialerPackageName(int userId) { 13641 synchronized (mPackages) { 13642 return mSettings.getDefaultDialerPackageNameLPw(userId); 13643 } 13644 } 13645 13646 @Override 13647 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13648 mContext.enforceCallingOrSelfPermission( 13649 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13650 "Only package verification agents can verify applications"); 13651 13652 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13653 final PackageVerificationResponse response = new PackageVerificationResponse( 13654 verificationCode, Binder.getCallingUid()); 13655 msg.arg1 = id; 13656 msg.obj = response; 13657 mHandler.sendMessage(msg); 13658 } 13659 13660 @Override 13661 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13662 long millisecondsToDelay) { 13663 mContext.enforceCallingOrSelfPermission( 13664 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13665 "Only package verification agents can extend verification timeouts"); 13666 13667 final PackageVerificationState state = mPendingVerification.get(id); 13668 final PackageVerificationResponse response = new PackageVerificationResponse( 13669 verificationCodeAtTimeout, Binder.getCallingUid()); 13670 13671 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13672 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13673 } 13674 if (millisecondsToDelay < 0) { 13675 millisecondsToDelay = 0; 13676 } 13677 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13678 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13679 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13680 } 13681 13682 if ((state != null) && !state.timeoutExtended()) { 13683 state.extendTimeout(); 13684 13685 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13686 msg.arg1 = id; 13687 msg.obj = response; 13688 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13689 } 13690 } 13691 13692 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13693 int verificationCode, UserHandle user) { 13694 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13695 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13696 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13697 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13698 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13699 13700 mContext.sendBroadcastAsUser(intent, user, 13701 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13702 } 13703 13704 private ComponentName matchComponentForVerifier(String packageName, 13705 List<ResolveInfo> receivers) { 13706 ActivityInfo targetReceiver = null; 13707 13708 final int NR = receivers.size(); 13709 for (int i = 0; i < NR; i++) { 13710 final ResolveInfo info = receivers.get(i); 13711 if (info.activityInfo == null) { 13712 continue; 13713 } 13714 13715 if (packageName.equals(info.activityInfo.packageName)) { 13716 targetReceiver = info.activityInfo; 13717 break; 13718 } 13719 } 13720 13721 if (targetReceiver == null) { 13722 return null; 13723 } 13724 13725 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13726 } 13727 13728 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13729 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13730 if (pkgInfo.verifiers.length == 0) { 13731 return null; 13732 } 13733 13734 final int N = pkgInfo.verifiers.length; 13735 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13736 for (int i = 0; i < N; i++) { 13737 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13738 13739 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13740 receivers); 13741 if (comp == null) { 13742 continue; 13743 } 13744 13745 final int verifierUid = getUidForVerifier(verifierInfo); 13746 if (verifierUid == -1) { 13747 continue; 13748 } 13749 13750 if (DEBUG_VERIFY) { 13751 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13752 + " with the correct signature"); 13753 } 13754 sufficientVerifiers.add(comp); 13755 verificationState.addSufficientVerifier(verifierUid); 13756 } 13757 13758 return sufficientVerifiers; 13759 } 13760 13761 private int getUidForVerifier(VerifierInfo verifierInfo) { 13762 synchronized (mPackages) { 13763 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13764 if (pkg == null) { 13765 return -1; 13766 } else if (pkg.mSignatures.length != 1) { 13767 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13768 + " has more than one signature; ignoring"); 13769 return -1; 13770 } 13771 13772 /* 13773 * If the public key of the package's signature does not match 13774 * our expected public key, then this is a different package and 13775 * we should skip. 13776 */ 13777 13778 final byte[] expectedPublicKey; 13779 try { 13780 final Signature verifierSig = pkg.mSignatures[0]; 13781 final PublicKey publicKey = verifierSig.getPublicKey(); 13782 expectedPublicKey = publicKey.getEncoded(); 13783 } catch (CertificateException e) { 13784 return -1; 13785 } 13786 13787 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13788 13789 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13790 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13791 + " does not have the expected public key; ignoring"); 13792 return -1; 13793 } 13794 13795 return pkg.applicationInfo.uid; 13796 } 13797 } 13798 13799 @Override 13800 public void finishPackageInstall(int token, boolean didLaunch) { 13801 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13802 13803 if (DEBUG_INSTALL) { 13804 Slog.v(TAG, "BM finishing package install for " + token); 13805 } 13806 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13807 13808 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13809 mHandler.sendMessage(msg); 13810 } 13811 13812 /** 13813 * Get the verification agent timeout. 13814 * 13815 * @return verification timeout in milliseconds 13816 */ 13817 private long getVerificationTimeout() { 13818 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13819 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13820 DEFAULT_VERIFICATION_TIMEOUT); 13821 } 13822 13823 /** 13824 * Get the default verification agent response code. 13825 * 13826 * @return default verification response code 13827 */ 13828 private int getDefaultVerificationResponse() { 13829 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13830 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13831 DEFAULT_VERIFICATION_RESPONSE); 13832 } 13833 13834 /** 13835 * Check whether or not package verification has been enabled. 13836 * 13837 * @return true if verification should be performed 13838 */ 13839 private boolean isVerificationEnabled(int userId, int installFlags) { 13840 if (!DEFAULT_VERIFY_ENABLE) { 13841 return false; 13842 } 13843 13844 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13845 13846 // Check if installing from ADB 13847 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13848 // Do not run verification in a test harness environment 13849 if (ActivityManager.isRunningInTestHarness()) { 13850 return false; 13851 } 13852 if (ensureVerifyAppsEnabled) { 13853 return true; 13854 } 13855 // Check if the developer does not want package verification for ADB installs 13856 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13857 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13858 return false; 13859 } 13860 } 13861 13862 if (ensureVerifyAppsEnabled) { 13863 return true; 13864 } 13865 13866 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13867 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13868 } 13869 13870 @Override 13871 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13872 throws RemoteException { 13873 mContext.enforceCallingOrSelfPermission( 13874 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13875 "Only intentfilter verification agents can verify applications"); 13876 13877 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13878 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13879 Binder.getCallingUid(), verificationCode, failedDomains); 13880 msg.arg1 = id; 13881 msg.obj = response; 13882 mHandler.sendMessage(msg); 13883 } 13884 13885 @Override 13886 public int getIntentVerificationStatus(String packageName, int userId) { 13887 synchronized (mPackages) { 13888 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13889 } 13890 } 13891 13892 @Override 13893 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13894 mContext.enforceCallingOrSelfPermission( 13895 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13896 13897 boolean result = false; 13898 synchronized (mPackages) { 13899 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13900 } 13901 if (result) { 13902 scheduleWritePackageRestrictionsLocked(userId); 13903 } 13904 return result; 13905 } 13906 13907 @Override 13908 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13909 String packageName) { 13910 synchronized (mPackages) { 13911 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13912 } 13913 } 13914 13915 @Override 13916 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13917 if (TextUtils.isEmpty(packageName)) { 13918 return ParceledListSlice.emptyList(); 13919 } 13920 synchronized (mPackages) { 13921 PackageParser.Package pkg = mPackages.get(packageName); 13922 if (pkg == null || pkg.activities == null) { 13923 return ParceledListSlice.emptyList(); 13924 } 13925 final int count = pkg.activities.size(); 13926 ArrayList<IntentFilter> result = new ArrayList<>(); 13927 for (int n=0; n<count; n++) { 13928 PackageParser.Activity activity = pkg.activities.get(n); 13929 if (activity.intents != null && activity.intents.size() > 0) { 13930 result.addAll(activity.intents); 13931 } 13932 } 13933 return new ParceledListSlice<>(result); 13934 } 13935 } 13936 13937 @Override 13938 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13939 mContext.enforceCallingOrSelfPermission( 13940 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13941 13942 synchronized (mPackages) { 13943 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13944 if (packageName != null) { 13945 result |= updateIntentVerificationStatus(packageName, 13946 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13947 userId); 13948 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13949 packageName, userId); 13950 } 13951 return result; 13952 } 13953 } 13954 13955 @Override 13956 public String getDefaultBrowserPackageName(int userId) { 13957 synchronized (mPackages) { 13958 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13959 } 13960 } 13961 13962 /** 13963 * Get the "allow unknown sources" setting. 13964 * 13965 * @return the current "allow unknown sources" setting 13966 */ 13967 private int getUnknownSourcesSettings() { 13968 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13969 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13970 -1); 13971 } 13972 13973 @Override 13974 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13975 final int uid = Binder.getCallingUid(); 13976 // writer 13977 synchronized (mPackages) { 13978 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13979 if (targetPackageSetting == null) { 13980 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13981 } 13982 13983 PackageSetting installerPackageSetting; 13984 if (installerPackageName != null) { 13985 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13986 if (installerPackageSetting == null) { 13987 throw new IllegalArgumentException("Unknown installer package: " 13988 + installerPackageName); 13989 } 13990 } else { 13991 installerPackageSetting = null; 13992 } 13993 13994 Signature[] callerSignature; 13995 Object obj = mSettings.getUserIdLPr(uid); 13996 if (obj != null) { 13997 if (obj instanceof SharedUserSetting) { 13998 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13999 } else if (obj instanceof PackageSetting) { 14000 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14001 } else { 14002 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14003 } 14004 } else { 14005 throw new SecurityException("Unknown calling UID: " + uid); 14006 } 14007 14008 // Verify: can't set installerPackageName to a package that is 14009 // not signed with the same cert as the caller. 14010 if (installerPackageSetting != null) { 14011 if (compareSignatures(callerSignature, 14012 installerPackageSetting.signatures.mSignatures) 14013 != PackageManager.SIGNATURE_MATCH) { 14014 throw new SecurityException( 14015 "Caller does not have same cert as new installer package " 14016 + installerPackageName); 14017 } 14018 } 14019 14020 // Verify: if target already has an installer package, it must 14021 // be signed with the same cert as the caller. 14022 if (targetPackageSetting.installerPackageName != null) { 14023 PackageSetting setting = mSettings.mPackages.get( 14024 targetPackageSetting.installerPackageName); 14025 // If the currently set package isn't valid, then it's always 14026 // okay to change it. 14027 if (setting != null) { 14028 if (compareSignatures(callerSignature, 14029 setting.signatures.mSignatures) 14030 != PackageManager.SIGNATURE_MATCH) { 14031 throw new SecurityException( 14032 "Caller does not have same cert as old installer package " 14033 + targetPackageSetting.installerPackageName); 14034 } 14035 } 14036 } 14037 14038 // Okay! 14039 targetPackageSetting.installerPackageName = installerPackageName; 14040 if (installerPackageName != null) { 14041 mSettings.mInstallerPackages.add(installerPackageName); 14042 } 14043 scheduleWriteSettingsLocked(); 14044 } 14045 } 14046 14047 @Override 14048 public void setApplicationCategoryHint(String packageName, int categoryHint, 14049 String callerPackageName) { 14050 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14051 callerPackageName); 14052 synchronized (mPackages) { 14053 PackageSetting ps = mSettings.mPackages.get(packageName); 14054 if (ps == null) { 14055 throw new IllegalArgumentException("Unknown target package " + packageName); 14056 } 14057 14058 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14059 throw new IllegalArgumentException("Calling package " + callerPackageName 14060 + " is not installer for " + packageName); 14061 } 14062 14063 if (ps.categoryHint != categoryHint) { 14064 ps.categoryHint = categoryHint; 14065 scheduleWriteSettingsLocked(); 14066 } 14067 } 14068 } 14069 14070 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14071 // Queue up an async operation since the package installation may take a little while. 14072 mHandler.post(new Runnable() { 14073 public void run() { 14074 mHandler.removeCallbacks(this); 14075 // Result object to be returned 14076 PackageInstalledInfo res = new PackageInstalledInfo(); 14077 res.setReturnCode(currentStatus); 14078 res.uid = -1; 14079 res.pkg = null; 14080 res.removedInfo = null; 14081 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14082 args.doPreInstall(res.returnCode); 14083 synchronized (mInstallLock) { 14084 installPackageTracedLI(args, res); 14085 } 14086 args.doPostInstall(res.returnCode, res.uid); 14087 } 14088 14089 // A restore should be performed at this point if (a) the install 14090 // succeeded, (b) the operation is not an update, and (c) the new 14091 // package has not opted out of backup participation. 14092 final boolean update = res.removedInfo != null 14093 && res.removedInfo.removedPackage != null; 14094 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14095 boolean doRestore = !update 14096 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14097 14098 // Set up the post-install work request bookkeeping. This will be used 14099 // and cleaned up by the post-install event handling regardless of whether 14100 // there's a restore pass performed. Token values are >= 1. 14101 int token; 14102 if (mNextInstallToken < 0) mNextInstallToken = 1; 14103 token = mNextInstallToken++; 14104 14105 PostInstallData data = new PostInstallData(args, res); 14106 mRunningInstalls.put(token, data); 14107 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14108 14109 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14110 // Pass responsibility to the Backup Manager. It will perform a 14111 // restore if appropriate, then pass responsibility back to the 14112 // Package Manager to run the post-install observer callbacks 14113 // and broadcasts. 14114 IBackupManager bm = IBackupManager.Stub.asInterface( 14115 ServiceManager.getService(Context.BACKUP_SERVICE)); 14116 if (bm != null) { 14117 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14118 + " to BM for possible restore"); 14119 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14120 try { 14121 // TODO: http://b/22388012 14122 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14123 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14124 } else { 14125 doRestore = false; 14126 } 14127 } catch (RemoteException e) { 14128 // can't happen; the backup manager is local 14129 } catch (Exception e) { 14130 Slog.e(TAG, "Exception trying to enqueue restore", e); 14131 doRestore = false; 14132 } 14133 } else { 14134 Slog.e(TAG, "Backup Manager not found!"); 14135 doRestore = false; 14136 } 14137 } 14138 14139 if (!doRestore) { 14140 // No restore possible, or the Backup Manager was mysteriously not 14141 // available -- just fire the post-install work request directly. 14142 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14143 14144 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14145 14146 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14147 mHandler.sendMessage(msg); 14148 } 14149 } 14150 }); 14151 } 14152 14153 /** 14154 * Callback from PackageSettings whenever an app is first transitioned out of the 14155 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14156 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14157 * here whether the app is the target of an ongoing install, and only send the 14158 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14159 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14160 * handling. 14161 */ 14162 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14163 // Serialize this with the rest of the install-process message chain. In the 14164 // restore-at-install case, this Runnable will necessarily run before the 14165 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14166 // are coherent. In the non-restore case, the app has already completed install 14167 // and been launched through some other means, so it is not in a problematic 14168 // state for observers to see the FIRST_LAUNCH signal. 14169 mHandler.post(new Runnable() { 14170 @Override 14171 public void run() { 14172 for (int i = 0; i < mRunningInstalls.size(); i++) { 14173 final PostInstallData data = mRunningInstalls.valueAt(i); 14174 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14175 continue; 14176 } 14177 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14178 // right package; but is it for the right user? 14179 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14180 if (userId == data.res.newUsers[uIndex]) { 14181 if (DEBUG_BACKUP) { 14182 Slog.i(TAG, "Package " + pkgName 14183 + " being restored so deferring FIRST_LAUNCH"); 14184 } 14185 return; 14186 } 14187 } 14188 } 14189 } 14190 // didn't find it, so not being restored 14191 if (DEBUG_BACKUP) { 14192 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14193 } 14194 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14195 } 14196 }); 14197 } 14198 14199 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14200 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14201 installerPkg, null, userIds); 14202 } 14203 14204 private abstract class HandlerParams { 14205 private static final int MAX_RETRIES = 4; 14206 14207 /** 14208 * Number of times startCopy() has been attempted and had a non-fatal 14209 * error. 14210 */ 14211 private int mRetries = 0; 14212 14213 /** User handle for the user requesting the information or installation. */ 14214 private final UserHandle mUser; 14215 String traceMethod; 14216 int traceCookie; 14217 14218 HandlerParams(UserHandle user) { 14219 mUser = user; 14220 } 14221 14222 UserHandle getUser() { 14223 return mUser; 14224 } 14225 14226 HandlerParams setTraceMethod(String traceMethod) { 14227 this.traceMethod = traceMethod; 14228 return this; 14229 } 14230 14231 HandlerParams setTraceCookie(int traceCookie) { 14232 this.traceCookie = traceCookie; 14233 return this; 14234 } 14235 14236 final boolean startCopy() { 14237 boolean res; 14238 try { 14239 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14240 14241 if (++mRetries > MAX_RETRIES) { 14242 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14243 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14244 handleServiceError(); 14245 return false; 14246 } else { 14247 handleStartCopy(); 14248 res = true; 14249 } 14250 } catch (RemoteException e) { 14251 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14252 mHandler.sendEmptyMessage(MCS_RECONNECT); 14253 res = false; 14254 } 14255 handleReturnCode(); 14256 return res; 14257 } 14258 14259 final void serviceError() { 14260 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14261 handleServiceError(); 14262 handleReturnCode(); 14263 } 14264 14265 abstract void handleStartCopy() throws RemoteException; 14266 abstract void handleServiceError(); 14267 abstract void handleReturnCode(); 14268 } 14269 14270 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14271 for (File path : paths) { 14272 try { 14273 mcs.clearDirectory(path.getAbsolutePath()); 14274 } catch (RemoteException e) { 14275 } 14276 } 14277 } 14278 14279 static class OriginInfo { 14280 /** 14281 * Location where install is coming from, before it has been 14282 * copied/renamed into place. This could be a single monolithic APK 14283 * file, or a cluster directory. This location may be untrusted. 14284 */ 14285 final File file; 14286 final String cid; 14287 14288 /** 14289 * Flag indicating that {@link #file} or {@link #cid} has already been 14290 * staged, meaning downstream users don't need to defensively copy the 14291 * contents. 14292 */ 14293 final boolean staged; 14294 14295 /** 14296 * Flag indicating that {@link #file} or {@link #cid} is an already 14297 * installed app that is being moved. 14298 */ 14299 final boolean existing; 14300 14301 final String resolvedPath; 14302 final File resolvedFile; 14303 14304 static OriginInfo fromNothing() { 14305 return new OriginInfo(null, null, false, false); 14306 } 14307 14308 static OriginInfo fromUntrustedFile(File file) { 14309 return new OriginInfo(file, null, false, false); 14310 } 14311 14312 static OriginInfo fromExistingFile(File file) { 14313 return new OriginInfo(file, null, false, true); 14314 } 14315 14316 static OriginInfo fromStagedFile(File file) { 14317 return new OriginInfo(file, null, true, false); 14318 } 14319 14320 static OriginInfo fromStagedContainer(String cid) { 14321 return new OriginInfo(null, cid, true, false); 14322 } 14323 14324 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14325 this.file = file; 14326 this.cid = cid; 14327 this.staged = staged; 14328 this.existing = existing; 14329 14330 if (cid != null) { 14331 resolvedPath = PackageHelper.getSdDir(cid); 14332 resolvedFile = new File(resolvedPath); 14333 } else if (file != null) { 14334 resolvedPath = file.getAbsolutePath(); 14335 resolvedFile = file; 14336 } else { 14337 resolvedPath = null; 14338 resolvedFile = null; 14339 } 14340 } 14341 } 14342 14343 static class MoveInfo { 14344 final int moveId; 14345 final String fromUuid; 14346 final String toUuid; 14347 final String packageName; 14348 final String dataAppName; 14349 final int appId; 14350 final String seinfo; 14351 final int targetSdkVersion; 14352 14353 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14354 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14355 this.moveId = moveId; 14356 this.fromUuid = fromUuid; 14357 this.toUuid = toUuid; 14358 this.packageName = packageName; 14359 this.dataAppName = dataAppName; 14360 this.appId = appId; 14361 this.seinfo = seinfo; 14362 this.targetSdkVersion = targetSdkVersion; 14363 } 14364 } 14365 14366 static class VerificationInfo { 14367 /** A constant used to indicate that a uid value is not present. */ 14368 public static final int NO_UID = -1; 14369 14370 /** URI referencing where the package was downloaded from. */ 14371 final Uri originatingUri; 14372 14373 /** HTTP referrer URI associated with the originatingURI. */ 14374 final Uri referrer; 14375 14376 /** UID of the application that the install request originated from. */ 14377 final int originatingUid; 14378 14379 /** UID of application requesting the install */ 14380 final int installerUid; 14381 14382 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14383 this.originatingUri = originatingUri; 14384 this.referrer = referrer; 14385 this.originatingUid = originatingUid; 14386 this.installerUid = installerUid; 14387 } 14388 } 14389 14390 class InstallParams extends HandlerParams { 14391 final OriginInfo origin; 14392 final MoveInfo move; 14393 final IPackageInstallObserver2 observer; 14394 int installFlags; 14395 final String installerPackageName; 14396 final String volumeUuid; 14397 private InstallArgs mArgs; 14398 private int mRet; 14399 final String packageAbiOverride; 14400 final String[] grantedRuntimePermissions; 14401 final VerificationInfo verificationInfo; 14402 final Certificate[][] certificates; 14403 final int installReason; 14404 14405 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14406 int installFlags, String installerPackageName, String volumeUuid, 14407 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14408 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14409 super(user); 14410 this.origin = origin; 14411 this.move = move; 14412 this.observer = observer; 14413 this.installFlags = installFlags; 14414 this.installerPackageName = installerPackageName; 14415 this.volumeUuid = volumeUuid; 14416 this.verificationInfo = verificationInfo; 14417 this.packageAbiOverride = packageAbiOverride; 14418 this.grantedRuntimePermissions = grantedPermissions; 14419 this.certificates = certificates; 14420 this.installReason = installReason; 14421 } 14422 14423 @Override 14424 public String toString() { 14425 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14426 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14427 } 14428 14429 private int installLocationPolicy(PackageInfoLite pkgLite) { 14430 String packageName = pkgLite.packageName; 14431 int installLocation = pkgLite.installLocation; 14432 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14433 // reader 14434 synchronized (mPackages) { 14435 // Currently installed package which the new package is attempting to replace or 14436 // null if no such package is installed. 14437 PackageParser.Package installedPkg = mPackages.get(packageName); 14438 // Package which currently owns the data which the new package will own if installed. 14439 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14440 // will be null whereas dataOwnerPkg will contain information about the package 14441 // which was uninstalled while keeping its data. 14442 PackageParser.Package dataOwnerPkg = installedPkg; 14443 if (dataOwnerPkg == null) { 14444 PackageSetting ps = mSettings.mPackages.get(packageName); 14445 if (ps != null) { 14446 dataOwnerPkg = ps.pkg; 14447 } 14448 } 14449 14450 if (dataOwnerPkg != null) { 14451 // If installed, the package will get access to data left on the device by its 14452 // predecessor. As a security measure, this is permited only if this is not a 14453 // version downgrade or if the predecessor package is marked as debuggable and 14454 // a downgrade is explicitly requested. 14455 // 14456 // On debuggable platform builds, downgrades are permitted even for 14457 // non-debuggable packages to make testing easier. Debuggable platform builds do 14458 // not offer security guarantees and thus it's OK to disable some security 14459 // mechanisms to make debugging/testing easier on those builds. However, even on 14460 // debuggable builds downgrades of packages are permitted only if requested via 14461 // installFlags. This is because we aim to keep the behavior of debuggable 14462 // platform builds as close as possible to the behavior of non-debuggable 14463 // platform builds. 14464 final boolean downgradeRequested = 14465 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14466 final boolean packageDebuggable = 14467 (dataOwnerPkg.applicationInfo.flags 14468 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14469 final boolean downgradePermitted = 14470 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14471 if (!downgradePermitted) { 14472 try { 14473 checkDowngrade(dataOwnerPkg, pkgLite); 14474 } catch (PackageManagerException e) { 14475 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14476 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14477 } 14478 } 14479 } 14480 14481 if (installedPkg != null) { 14482 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14483 // Check for updated system application. 14484 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14485 if (onSd) { 14486 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14487 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14488 } 14489 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14490 } else { 14491 if (onSd) { 14492 // Install flag overrides everything. 14493 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14494 } 14495 // If current upgrade specifies particular preference 14496 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14497 // Application explicitly specified internal. 14498 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14499 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14500 // App explictly prefers external. Let policy decide 14501 } else { 14502 // Prefer previous location 14503 if (isExternal(installedPkg)) { 14504 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14505 } 14506 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14507 } 14508 } 14509 } else { 14510 // Invalid install. Return error code 14511 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14512 } 14513 } 14514 } 14515 // All the special cases have been taken care of. 14516 // Return result based on recommended install location. 14517 if (onSd) { 14518 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14519 } 14520 return pkgLite.recommendedInstallLocation; 14521 } 14522 14523 /* 14524 * Invoke remote method to get package information and install 14525 * location values. Override install location based on default 14526 * policy if needed and then create install arguments based 14527 * on the install location. 14528 */ 14529 public void handleStartCopy() throws RemoteException { 14530 int ret = PackageManager.INSTALL_SUCCEEDED; 14531 14532 // If we're already staged, we've firmly committed to an install location 14533 if (origin.staged) { 14534 if (origin.file != null) { 14535 installFlags |= PackageManager.INSTALL_INTERNAL; 14536 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14537 } else if (origin.cid != null) { 14538 installFlags |= PackageManager.INSTALL_EXTERNAL; 14539 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14540 } else { 14541 throw new IllegalStateException("Invalid stage location"); 14542 } 14543 } 14544 14545 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14546 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14547 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14548 PackageInfoLite pkgLite = null; 14549 14550 if (onInt && onSd) { 14551 // Check if both bits are set. 14552 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14553 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14554 } else if (onSd && ephemeral) { 14555 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14556 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14557 } else { 14558 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14559 packageAbiOverride); 14560 14561 if (DEBUG_EPHEMERAL && ephemeral) { 14562 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14563 } 14564 14565 /* 14566 * If we have too little free space, try to free cache 14567 * before giving up. 14568 */ 14569 if (!origin.staged && pkgLite.recommendedInstallLocation 14570 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14571 // TODO: focus freeing disk space on the target device 14572 final StorageManager storage = StorageManager.from(mContext); 14573 final long lowThreshold = storage.getStorageLowBytes( 14574 Environment.getDataDirectory()); 14575 14576 final long sizeBytes = mContainerService.calculateInstalledSize( 14577 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14578 14579 try { 14580 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14581 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14582 installFlags, packageAbiOverride); 14583 } catch (InstallerException e) { 14584 Slog.w(TAG, "Failed to free cache", e); 14585 } 14586 14587 /* 14588 * The cache free must have deleted the file we 14589 * downloaded to install. 14590 * 14591 * TODO: fix the "freeCache" call to not delete 14592 * the file we care about. 14593 */ 14594 if (pkgLite.recommendedInstallLocation 14595 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14596 pkgLite.recommendedInstallLocation 14597 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14598 } 14599 } 14600 } 14601 14602 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14603 int loc = pkgLite.recommendedInstallLocation; 14604 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14605 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14606 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14607 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14608 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14609 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14610 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14611 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14612 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14613 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14614 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14615 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14616 } else { 14617 // Override with defaults if needed. 14618 loc = installLocationPolicy(pkgLite); 14619 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14620 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14621 } else if (!onSd && !onInt) { 14622 // Override install location with flags 14623 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14624 // Set the flag to install on external media. 14625 installFlags |= PackageManager.INSTALL_EXTERNAL; 14626 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14627 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14628 if (DEBUG_EPHEMERAL) { 14629 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14630 } 14631 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14632 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14633 |PackageManager.INSTALL_INTERNAL); 14634 } else { 14635 // Make sure the flag for installing on external 14636 // media is unset 14637 installFlags |= PackageManager.INSTALL_INTERNAL; 14638 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14639 } 14640 } 14641 } 14642 } 14643 14644 final InstallArgs args = createInstallArgs(this); 14645 mArgs = args; 14646 14647 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14648 // TODO: http://b/22976637 14649 // Apps installed for "all" users use the device owner to verify the app 14650 UserHandle verifierUser = getUser(); 14651 if (verifierUser == UserHandle.ALL) { 14652 verifierUser = UserHandle.SYSTEM; 14653 } 14654 14655 /* 14656 * Determine if we have any installed package verifiers. If we 14657 * do, then we'll defer to them to verify the packages. 14658 */ 14659 final int requiredUid = mRequiredVerifierPackage == null ? -1 14660 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14661 verifierUser.getIdentifier()); 14662 if (!origin.existing && requiredUid != -1 14663 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14664 final Intent verification = new Intent( 14665 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14666 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14667 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14668 PACKAGE_MIME_TYPE); 14669 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14670 14671 // Query all live verifiers based on current user state 14672 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14673 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14674 14675 if (DEBUG_VERIFY) { 14676 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14677 + verification.toString() + " with " + pkgLite.verifiers.length 14678 + " optional verifiers"); 14679 } 14680 14681 final int verificationId = mPendingVerificationToken++; 14682 14683 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14684 14685 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14686 installerPackageName); 14687 14688 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14689 installFlags); 14690 14691 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14692 pkgLite.packageName); 14693 14694 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14695 pkgLite.versionCode); 14696 14697 if (verificationInfo != null) { 14698 if (verificationInfo.originatingUri != null) { 14699 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14700 verificationInfo.originatingUri); 14701 } 14702 if (verificationInfo.referrer != null) { 14703 verification.putExtra(Intent.EXTRA_REFERRER, 14704 verificationInfo.referrer); 14705 } 14706 if (verificationInfo.originatingUid >= 0) { 14707 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14708 verificationInfo.originatingUid); 14709 } 14710 if (verificationInfo.installerUid >= 0) { 14711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14712 verificationInfo.installerUid); 14713 } 14714 } 14715 14716 final PackageVerificationState verificationState = new PackageVerificationState( 14717 requiredUid, args); 14718 14719 mPendingVerification.append(verificationId, verificationState); 14720 14721 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14722 receivers, verificationState); 14723 14724 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14725 final long idleDuration = getVerificationTimeout(); 14726 14727 /* 14728 * If any sufficient verifiers were listed in the package 14729 * manifest, attempt to ask them. 14730 */ 14731 if (sufficientVerifiers != null) { 14732 final int N = sufficientVerifiers.size(); 14733 if (N == 0) { 14734 Slog.i(TAG, "Additional verifiers required, but none installed."); 14735 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14736 } else { 14737 for (int i = 0; i < N; i++) { 14738 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14739 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14740 verifierComponent.getPackageName(), idleDuration, 14741 verifierUser.getIdentifier(), false, "package verifier"); 14742 14743 final Intent sufficientIntent = new Intent(verification); 14744 sufficientIntent.setComponent(verifierComponent); 14745 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14746 } 14747 } 14748 } 14749 14750 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14751 mRequiredVerifierPackage, receivers); 14752 if (ret == PackageManager.INSTALL_SUCCEEDED 14753 && mRequiredVerifierPackage != null) { 14754 Trace.asyncTraceBegin( 14755 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14756 /* 14757 * Send the intent to the required verification agent, 14758 * but only start the verification timeout after the 14759 * target BroadcastReceivers have run. 14760 */ 14761 verification.setComponent(requiredVerifierComponent); 14762 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14763 mRequiredVerifierPackage, idleDuration, 14764 verifierUser.getIdentifier(), false, "package verifier"); 14765 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14766 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14767 new BroadcastReceiver() { 14768 @Override 14769 public void onReceive(Context context, Intent intent) { 14770 final Message msg = mHandler 14771 .obtainMessage(CHECK_PENDING_VERIFICATION); 14772 msg.arg1 = verificationId; 14773 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14774 } 14775 }, null, 0, null, null); 14776 14777 /* 14778 * We don't want the copy to proceed until verification 14779 * succeeds, so null out this field. 14780 */ 14781 mArgs = null; 14782 } 14783 } else { 14784 /* 14785 * No package verification is enabled, so immediately start 14786 * the remote call to initiate copy using temporary file. 14787 */ 14788 ret = args.copyApk(mContainerService, true); 14789 } 14790 } 14791 14792 mRet = ret; 14793 } 14794 14795 @Override 14796 void handleReturnCode() { 14797 // If mArgs is null, then MCS couldn't be reached. When it 14798 // reconnects, it will try again to install. At that point, this 14799 // will succeed. 14800 if (mArgs != null) { 14801 processPendingInstall(mArgs, mRet); 14802 } 14803 } 14804 14805 @Override 14806 void handleServiceError() { 14807 mArgs = createInstallArgs(this); 14808 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14809 } 14810 14811 public boolean isForwardLocked() { 14812 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14813 } 14814 } 14815 14816 /** 14817 * Used during creation of InstallArgs 14818 * 14819 * @param installFlags package installation flags 14820 * @return true if should be installed on external storage 14821 */ 14822 private static boolean installOnExternalAsec(int installFlags) { 14823 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14824 return false; 14825 } 14826 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14827 return true; 14828 } 14829 return false; 14830 } 14831 14832 /** 14833 * Used during creation of InstallArgs 14834 * 14835 * @param installFlags package installation flags 14836 * @return true if should be installed as forward locked 14837 */ 14838 private static boolean installForwardLocked(int installFlags) { 14839 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14840 } 14841 14842 private InstallArgs createInstallArgs(InstallParams params) { 14843 if (params.move != null) { 14844 return new MoveInstallArgs(params); 14845 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14846 return new AsecInstallArgs(params); 14847 } else { 14848 return new FileInstallArgs(params); 14849 } 14850 } 14851 14852 /** 14853 * Create args that describe an existing installed package. Typically used 14854 * when cleaning up old installs, or used as a move source. 14855 */ 14856 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14857 String resourcePath, String[] instructionSets) { 14858 final boolean isInAsec; 14859 if (installOnExternalAsec(installFlags)) { 14860 /* Apps on SD card are always in ASEC containers. */ 14861 isInAsec = true; 14862 } else if (installForwardLocked(installFlags) 14863 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14864 /* 14865 * Forward-locked apps are only in ASEC containers if they're the 14866 * new style 14867 */ 14868 isInAsec = true; 14869 } else { 14870 isInAsec = false; 14871 } 14872 14873 if (isInAsec) { 14874 return new AsecInstallArgs(codePath, instructionSets, 14875 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14876 } else { 14877 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14878 } 14879 } 14880 14881 static abstract class InstallArgs { 14882 /** @see InstallParams#origin */ 14883 final OriginInfo origin; 14884 /** @see InstallParams#move */ 14885 final MoveInfo move; 14886 14887 final IPackageInstallObserver2 observer; 14888 // Always refers to PackageManager flags only 14889 final int installFlags; 14890 final String installerPackageName; 14891 final String volumeUuid; 14892 final UserHandle user; 14893 final String abiOverride; 14894 final String[] installGrantPermissions; 14895 /** If non-null, drop an async trace when the install completes */ 14896 final String traceMethod; 14897 final int traceCookie; 14898 final Certificate[][] certificates; 14899 final int installReason; 14900 14901 // The list of instruction sets supported by this app. This is currently 14902 // only used during the rmdex() phase to clean up resources. We can get rid of this 14903 // if we move dex files under the common app path. 14904 /* nullable */ String[] instructionSets; 14905 14906 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14907 int installFlags, String installerPackageName, String volumeUuid, 14908 UserHandle user, String[] instructionSets, 14909 String abiOverride, String[] installGrantPermissions, 14910 String traceMethod, int traceCookie, Certificate[][] certificates, 14911 int installReason) { 14912 this.origin = origin; 14913 this.move = move; 14914 this.installFlags = installFlags; 14915 this.observer = observer; 14916 this.installerPackageName = installerPackageName; 14917 this.volumeUuid = volumeUuid; 14918 this.user = user; 14919 this.instructionSets = instructionSets; 14920 this.abiOverride = abiOverride; 14921 this.installGrantPermissions = installGrantPermissions; 14922 this.traceMethod = traceMethod; 14923 this.traceCookie = traceCookie; 14924 this.certificates = certificates; 14925 this.installReason = installReason; 14926 } 14927 14928 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14929 abstract int doPreInstall(int status); 14930 14931 /** 14932 * Rename package into final resting place. All paths on the given 14933 * scanned package should be updated to reflect the rename. 14934 */ 14935 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14936 abstract int doPostInstall(int status, int uid); 14937 14938 /** @see PackageSettingBase#codePathString */ 14939 abstract String getCodePath(); 14940 /** @see PackageSettingBase#resourcePathString */ 14941 abstract String getResourcePath(); 14942 14943 // Need installer lock especially for dex file removal. 14944 abstract void cleanUpResourcesLI(); 14945 abstract boolean doPostDeleteLI(boolean delete); 14946 14947 /** 14948 * Called before the source arguments are copied. This is used mostly 14949 * for MoveParams when it needs to read the source file to put it in the 14950 * destination. 14951 */ 14952 int doPreCopy() { 14953 return PackageManager.INSTALL_SUCCEEDED; 14954 } 14955 14956 /** 14957 * Called after the source arguments are copied. This is used mostly for 14958 * MoveParams when it needs to read the source file to put it in the 14959 * destination. 14960 */ 14961 int doPostCopy(int uid) { 14962 return PackageManager.INSTALL_SUCCEEDED; 14963 } 14964 14965 protected boolean isFwdLocked() { 14966 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14967 } 14968 14969 protected boolean isExternalAsec() { 14970 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14971 } 14972 14973 protected boolean isEphemeral() { 14974 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14975 } 14976 14977 UserHandle getUser() { 14978 return user; 14979 } 14980 } 14981 14982 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14983 if (!allCodePaths.isEmpty()) { 14984 if (instructionSets == null) { 14985 throw new IllegalStateException("instructionSet == null"); 14986 } 14987 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14988 for (String codePath : allCodePaths) { 14989 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14990 try { 14991 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14992 } catch (InstallerException ignored) { 14993 } 14994 } 14995 } 14996 } 14997 } 14998 14999 /** 15000 * Logic to handle installation of non-ASEC applications, including copying 15001 * and renaming logic. 15002 */ 15003 class FileInstallArgs extends InstallArgs { 15004 private File codeFile; 15005 private File resourceFile; 15006 15007 // Example topology: 15008 // /data/app/com.example/base.apk 15009 // /data/app/com.example/split_foo.apk 15010 // /data/app/com.example/lib/arm/libfoo.so 15011 // /data/app/com.example/lib/arm64/libfoo.so 15012 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15013 15014 /** New install */ 15015 FileInstallArgs(InstallParams params) { 15016 super(params.origin, params.move, params.observer, params.installFlags, 15017 params.installerPackageName, params.volumeUuid, 15018 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15019 params.grantedRuntimePermissions, 15020 params.traceMethod, params.traceCookie, params.certificates, 15021 params.installReason); 15022 if (isFwdLocked()) { 15023 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15024 } 15025 } 15026 15027 /** Existing install */ 15028 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15029 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15030 null, null, null, 0, null /*certificates*/, 15031 PackageManager.INSTALL_REASON_UNKNOWN); 15032 this.codeFile = (codePath != null) ? new File(codePath) : null; 15033 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15034 } 15035 15036 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15037 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15038 try { 15039 return doCopyApk(imcs, temp); 15040 } finally { 15041 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15042 } 15043 } 15044 15045 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15046 if (origin.staged) { 15047 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15048 codeFile = origin.file; 15049 resourceFile = origin.file; 15050 return PackageManager.INSTALL_SUCCEEDED; 15051 } 15052 15053 try { 15054 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15055 final File tempDir = 15056 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15057 codeFile = tempDir; 15058 resourceFile = tempDir; 15059 } catch (IOException e) { 15060 Slog.w(TAG, "Failed to create copy file: " + e); 15061 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15062 } 15063 15064 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15065 @Override 15066 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15067 if (!FileUtils.isValidExtFilename(name)) { 15068 throw new IllegalArgumentException("Invalid filename: " + name); 15069 } 15070 try { 15071 final File file = new File(codeFile, name); 15072 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15073 O_RDWR | O_CREAT, 0644); 15074 Os.chmod(file.getAbsolutePath(), 0644); 15075 return new ParcelFileDescriptor(fd); 15076 } catch (ErrnoException e) { 15077 throw new RemoteException("Failed to open: " + e.getMessage()); 15078 } 15079 } 15080 }; 15081 15082 int ret = PackageManager.INSTALL_SUCCEEDED; 15083 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15084 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15085 Slog.e(TAG, "Failed to copy package"); 15086 return ret; 15087 } 15088 15089 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15090 NativeLibraryHelper.Handle handle = null; 15091 try { 15092 handle = NativeLibraryHelper.Handle.create(codeFile); 15093 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15094 abiOverride); 15095 } catch (IOException e) { 15096 Slog.e(TAG, "Copying native libraries failed", e); 15097 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15098 } finally { 15099 IoUtils.closeQuietly(handle); 15100 } 15101 15102 return ret; 15103 } 15104 15105 int doPreInstall(int status) { 15106 if (status != PackageManager.INSTALL_SUCCEEDED) { 15107 cleanUp(); 15108 } 15109 return status; 15110 } 15111 15112 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15113 if (status != PackageManager.INSTALL_SUCCEEDED) { 15114 cleanUp(); 15115 return false; 15116 } 15117 15118 final File targetDir = codeFile.getParentFile(); 15119 final File beforeCodeFile = codeFile; 15120 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15121 15122 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15123 try { 15124 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15125 } catch (ErrnoException e) { 15126 Slog.w(TAG, "Failed to rename", e); 15127 return false; 15128 } 15129 15130 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15131 Slog.w(TAG, "Failed to restorecon"); 15132 return false; 15133 } 15134 15135 // Reflect the rename internally 15136 codeFile = afterCodeFile; 15137 resourceFile = afterCodeFile; 15138 15139 // Reflect the rename in scanned details 15140 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15141 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15142 afterCodeFile, pkg.baseCodePath)); 15143 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15144 afterCodeFile, pkg.splitCodePaths)); 15145 15146 // Reflect the rename in app info 15147 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15148 pkg.setApplicationInfoCodePath(pkg.codePath); 15149 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15150 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15151 pkg.setApplicationInfoResourcePath(pkg.codePath); 15152 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15153 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15154 15155 return true; 15156 } 15157 15158 int doPostInstall(int status, int uid) { 15159 if (status != PackageManager.INSTALL_SUCCEEDED) { 15160 cleanUp(); 15161 } 15162 return status; 15163 } 15164 15165 @Override 15166 String getCodePath() { 15167 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15168 } 15169 15170 @Override 15171 String getResourcePath() { 15172 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15173 } 15174 15175 private boolean cleanUp() { 15176 if (codeFile == null || !codeFile.exists()) { 15177 return false; 15178 } 15179 15180 removeCodePathLI(codeFile); 15181 15182 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15183 resourceFile.delete(); 15184 } 15185 15186 return true; 15187 } 15188 15189 void cleanUpResourcesLI() { 15190 // Try enumerating all code paths before deleting 15191 List<String> allCodePaths = Collections.EMPTY_LIST; 15192 if (codeFile != null && codeFile.exists()) { 15193 try { 15194 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15195 allCodePaths = pkg.getAllCodePaths(); 15196 } catch (PackageParserException e) { 15197 // Ignored; we tried our best 15198 } 15199 } 15200 15201 cleanUp(); 15202 removeDexFiles(allCodePaths, instructionSets); 15203 } 15204 15205 boolean doPostDeleteLI(boolean delete) { 15206 // XXX err, shouldn't we respect the delete flag? 15207 cleanUpResourcesLI(); 15208 return true; 15209 } 15210 } 15211 15212 private boolean isAsecExternal(String cid) { 15213 final String asecPath = PackageHelper.getSdFilesystem(cid); 15214 return !asecPath.startsWith(mAsecInternalPath); 15215 } 15216 15217 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15218 PackageManagerException { 15219 if (copyRet < 0) { 15220 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15221 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15222 throw new PackageManagerException(copyRet, message); 15223 } 15224 } 15225 } 15226 15227 /** 15228 * Extract the StorageManagerService "container ID" from the full code path of an 15229 * .apk. 15230 */ 15231 static String cidFromCodePath(String fullCodePath) { 15232 int eidx = fullCodePath.lastIndexOf("/"); 15233 String subStr1 = fullCodePath.substring(0, eidx); 15234 int sidx = subStr1.lastIndexOf("/"); 15235 return subStr1.substring(sidx+1, eidx); 15236 } 15237 15238 /** 15239 * Logic to handle installation of ASEC applications, including copying and 15240 * renaming logic. 15241 */ 15242 class AsecInstallArgs extends InstallArgs { 15243 static final String RES_FILE_NAME = "pkg.apk"; 15244 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15245 15246 String cid; 15247 String packagePath; 15248 String resourcePath; 15249 15250 /** New install */ 15251 AsecInstallArgs(InstallParams params) { 15252 super(params.origin, params.move, params.observer, params.installFlags, 15253 params.installerPackageName, params.volumeUuid, 15254 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15255 params.grantedRuntimePermissions, 15256 params.traceMethod, params.traceCookie, params.certificates, 15257 params.installReason); 15258 } 15259 15260 /** Existing install */ 15261 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15262 boolean isExternal, boolean isForwardLocked) { 15263 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15264 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15265 instructionSets, null, null, null, 0, null /*certificates*/, 15266 PackageManager.INSTALL_REASON_UNKNOWN); 15267 // Hackily pretend we're still looking at a full code path 15268 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15269 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15270 } 15271 15272 // Extract cid from fullCodePath 15273 int eidx = fullCodePath.lastIndexOf("/"); 15274 String subStr1 = fullCodePath.substring(0, eidx); 15275 int sidx = subStr1.lastIndexOf("/"); 15276 cid = subStr1.substring(sidx+1, eidx); 15277 setMountPath(subStr1); 15278 } 15279 15280 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15281 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15282 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15283 instructionSets, null, null, null, 0, null /*certificates*/, 15284 PackageManager.INSTALL_REASON_UNKNOWN); 15285 this.cid = cid; 15286 setMountPath(PackageHelper.getSdDir(cid)); 15287 } 15288 15289 void createCopyFile() { 15290 cid = mInstallerService.allocateExternalStageCidLegacy(); 15291 } 15292 15293 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15294 if (origin.staged && origin.cid != null) { 15295 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15296 cid = origin.cid; 15297 setMountPath(PackageHelper.getSdDir(cid)); 15298 return PackageManager.INSTALL_SUCCEEDED; 15299 } 15300 15301 if (temp) { 15302 createCopyFile(); 15303 } else { 15304 /* 15305 * Pre-emptively destroy the container since it's destroyed if 15306 * copying fails due to it existing anyway. 15307 */ 15308 PackageHelper.destroySdDir(cid); 15309 } 15310 15311 final String newMountPath = imcs.copyPackageToContainer( 15312 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15313 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15314 15315 if (newMountPath != null) { 15316 setMountPath(newMountPath); 15317 return PackageManager.INSTALL_SUCCEEDED; 15318 } else { 15319 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15320 } 15321 } 15322 15323 @Override 15324 String getCodePath() { 15325 return packagePath; 15326 } 15327 15328 @Override 15329 String getResourcePath() { 15330 return resourcePath; 15331 } 15332 15333 int doPreInstall(int status) { 15334 if (status != PackageManager.INSTALL_SUCCEEDED) { 15335 // Destroy container 15336 PackageHelper.destroySdDir(cid); 15337 } else { 15338 boolean mounted = PackageHelper.isContainerMounted(cid); 15339 if (!mounted) { 15340 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15341 Process.SYSTEM_UID); 15342 if (newMountPath != null) { 15343 setMountPath(newMountPath); 15344 } else { 15345 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15346 } 15347 } 15348 } 15349 return status; 15350 } 15351 15352 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15353 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15354 String newMountPath = null; 15355 if (PackageHelper.isContainerMounted(cid)) { 15356 // Unmount the container 15357 if (!PackageHelper.unMountSdDir(cid)) { 15358 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15359 return false; 15360 } 15361 } 15362 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15363 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15364 " which might be stale. Will try to clean up."); 15365 // Clean up the stale container and proceed to recreate. 15366 if (!PackageHelper.destroySdDir(newCacheId)) { 15367 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15368 return false; 15369 } 15370 // Successfully cleaned up stale container. Try to rename again. 15371 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15372 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15373 + " inspite of cleaning it up."); 15374 return false; 15375 } 15376 } 15377 if (!PackageHelper.isContainerMounted(newCacheId)) { 15378 Slog.w(TAG, "Mounting container " + newCacheId); 15379 newMountPath = PackageHelper.mountSdDir(newCacheId, 15380 getEncryptKey(), Process.SYSTEM_UID); 15381 } else { 15382 newMountPath = PackageHelper.getSdDir(newCacheId); 15383 } 15384 if (newMountPath == null) { 15385 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15386 return false; 15387 } 15388 Log.i(TAG, "Succesfully renamed " + cid + 15389 " to " + newCacheId + 15390 " at new path: " + newMountPath); 15391 cid = newCacheId; 15392 15393 final File beforeCodeFile = new File(packagePath); 15394 setMountPath(newMountPath); 15395 final File afterCodeFile = new File(packagePath); 15396 15397 // Reflect the rename in scanned details 15398 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15399 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15400 afterCodeFile, pkg.baseCodePath)); 15401 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15402 afterCodeFile, pkg.splitCodePaths)); 15403 15404 // Reflect the rename in app info 15405 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15406 pkg.setApplicationInfoCodePath(pkg.codePath); 15407 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15408 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15409 pkg.setApplicationInfoResourcePath(pkg.codePath); 15410 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15411 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15412 15413 return true; 15414 } 15415 15416 private void setMountPath(String mountPath) { 15417 final File mountFile = new File(mountPath); 15418 15419 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15420 if (monolithicFile.exists()) { 15421 packagePath = monolithicFile.getAbsolutePath(); 15422 if (isFwdLocked()) { 15423 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15424 } else { 15425 resourcePath = packagePath; 15426 } 15427 } else { 15428 packagePath = mountFile.getAbsolutePath(); 15429 resourcePath = packagePath; 15430 } 15431 } 15432 15433 int doPostInstall(int status, int uid) { 15434 if (status != PackageManager.INSTALL_SUCCEEDED) { 15435 cleanUp(); 15436 } else { 15437 final int groupOwner; 15438 final String protectedFile; 15439 if (isFwdLocked()) { 15440 groupOwner = UserHandle.getSharedAppGid(uid); 15441 protectedFile = RES_FILE_NAME; 15442 } else { 15443 groupOwner = -1; 15444 protectedFile = null; 15445 } 15446 15447 if (uid < Process.FIRST_APPLICATION_UID 15448 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15449 Slog.e(TAG, "Failed to finalize " + cid); 15450 PackageHelper.destroySdDir(cid); 15451 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15452 } 15453 15454 boolean mounted = PackageHelper.isContainerMounted(cid); 15455 if (!mounted) { 15456 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15457 } 15458 } 15459 return status; 15460 } 15461 15462 private void cleanUp() { 15463 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15464 15465 // Destroy secure container 15466 PackageHelper.destroySdDir(cid); 15467 } 15468 15469 private List<String> getAllCodePaths() { 15470 final File codeFile = new File(getCodePath()); 15471 if (codeFile != null && codeFile.exists()) { 15472 try { 15473 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15474 return pkg.getAllCodePaths(); 15475 } catch (PackageParserException e) { 15476 // Ignored; we tried our best 15477 } 15478 } 15479 return Collections.EMPTY_LIST; 15480 } 15481 15482 void cleanUpResourcesLI() { 15483 // Enumerate all code paths before deleting 15484 cleanUpResourcesLI(getAllCodePaths()); 15485 } 15486 15487 private void cleanUpResourcesLI(List<String> allCodePaths) { 15488 cleanUp(); 15489 removeDexFiles(allCodePaths, instructionSets); 15490 } 15491 15492 String getPackageName() { 15493 return getAsecPackageName(cid); 15494 } 15495 15496 boolean doPostDeleteLI(boolean delete) { 15497 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15498 final List<String> allCodePaths = getAllCodePaths(); 15499 boolean mounted = PackageHelper.isContainerMounted(cid); 15500 if (mounted) { 15501 // Unmount first 15502 if (PackageHelper.unMountSdDir(cid)) { 15503 mounted = false; 15504 } 15505 } 15506 if (!mounted && delete) { 15507 cleanUpResourcesLI(allCodePaths); 15508 } 15509 return !mounted; 15510 } 15511 15512 @Override 15513 int doPreCopy() { 15514 if (isFwdLocked()) { 15515 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15516 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15517 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15518 } 15519 } 15520 15521 return PackageManager.INSTALL_SUCCEEDED; 15522 } 15523 15524 @Override 15525 int doPostCopy(int uid) { 15526 if (isFwdLocked()) { 15527 if (uid < Process.FIRST_APPLICATION_UID 15528 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15529 RES_FILE_NAME)) { 15530 Slog.e(TAG, "Failed to finalize " + cid); 15531 PackageHelper.destroySdDir(cid); 15532 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15533 } 15534 } 15535 15536 return PackageManager.INSTALL_SUCCEEDED; 15537 } 15538 } 15539 15540 /** 15541 * Logic to handle movement of existing installed applications. 15542 */ 15543 class MoveInstallArgs extends InstallArgs { 15544 private File codeFile; 15545 private File resourceFile; 15546 15547 /** New install */ 15548 MoveInstallArgs(InstallParams params) { 15549 super(params.origin, params.move, params.observer, params.installFlags, 15550 params.installerPackageName, params.volumeUuid, 15551 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15552 params.grantedRuntimePermissions, 15553 params.traceMethod, params.traceCookie, params.certificates, 15554 params.installReason); 15555 } 15556 15557 int copyApk(IMediaContainerService imcs, boolean temp) { 15558 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15559 + move.fromUuid + " to " + move.toUuid); 15560 synchronized (mInstaller) { 15561 try { 15562 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15563 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15564 } catch (InstallerException e) { 15565 Slog.w(TAG, "Failed to move app", e); 15566 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15567 } 15568 } 15569 15570 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15571 resourceFile = codeFile; 15572 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15573 15574 return PackageManager.INSTALL_SUCCEEDED; 15575 } 15576 15577 int doPreInstall(int status) { 15578 if (status != PackageManager.INSTALL_SUCCEEDED) { 15579 cleanUp(move.toUuid); 15580 } 15581 return status; 15582 } 15583 15584 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15585 if (status != PackageManager.INSTALL_SUCCEEDED) { 15586 cleanUp(move.toUuid); 15587 return false; 15588 } 15589 15590 // Reflect the move in app info 15591 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15592 pkg.setApplicationInfoCodePath(pkg.codePath); 15593 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15594 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15595 pkg.setApplicationInfoResourcePath(pkg.codePath); 15596 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15597 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15598 15599 return true; 15600 } 15601 15602 int doPostInstall(int status, int uid) { 15603 if (status == PackageManager.INSTALL_SUCCEEDED) { 15604 cleanUp(move.fromUuid); 15605 } else { 15606 cleanUp(move.toUuid); 15607 } 15608 return status; 15609 } 15610 15611 @Override 15612 String getCodePath() { 15613 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15614 } 15615 15616 @Override 15617 String getResourcePath() { 15618 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15619 } 15620 15621 private boolean cleanUp(String volumeUuid) { 15622 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15623 move.dataAppName); 15624 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15625 final int[] userIds = sUserManager.getUserIds(); 15626 synchronized (mInstallLock) { 15627 // Clean up both app data and code 15628 // All package moves are frozen until finished 15629 for (int userId : userIds) { 15630 try { 15631 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15632 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15633 } catch (InstallerException e) { 15634 Slog.w(TAG, String.valueOf(e)); 15635 } 15636 } 15637 removeCodePathLI(codeFile); 15638 } 15639 return true; 15640 } 15641 15642 void cleanUpResourcesLI() { 15643 throw new UnsupportedOperationException(); 15644 } 15645 15646 boolean doPostDeleteLI(boolean delete) { 15647 throw new UnsupportedOperationException(); 15648 } 15649 } 15650 15651 static String getAsecPackageName(String packageCid) { 15652 int idx = packageCid.lastIndexOf("-"); 15653 if (idx == -1) { 15654 return packageCid; 15655 } 15656 return packageCid.substring(0, idx); 15657 } 15658 15659 // Utility method used to create code paths based on package name and available index. 15660 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15661 String idxStr = ""; 15662 int idx = 1; 15663 // Fall back to default value of idx=1 if prefix is not 15664 // part of oldCodePath 15665 if (oldCodePath != null) { 15666 String subStr = oldCodePath; 15667 // Drop the suffix right away 15668 if (suffix != null && subStr.endsWith(suffix)) { 15669 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15670 } 15671 // If oldCodePath already contains prefix find out the 15672 // ending index to either increment or decrement. 15673 int sidx = subStr.lastIndexOf(prefix); 15674 if (sidx != -1) { 15675 subStr = subStr.substring(sidx + prefix.length()); 15676 if (subStr != null) { 15677 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15678 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15679 } 15680 try { 15681 idx = Integer.parseInt(subStr); 15682 if (idx <= 1) { 15683 idx++; 15684 } else { 15685 idx--; 15686 } 15687 } catch(NumberFormatException e) { 15688 } 15689 } 15690 } 15691 } 15692 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15693 return prefix + idxStr; 15694 } 15695 15696 private File getNextCodePath(File targetDir, String packageName) { 15697 File result; 15698 SecureRandom random = new SecureRandom(); 15699 byte[] bytes = new byte[16]; 15700 do { 15701 random.nextBytes(bytes); 15702 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15703 result = new File(targetDir, packageName + "-" + suffix); 15704 } while (result.exists()); 15705 return result; 15706 } 15707 15708 // Utility method that returns the relative package path with respect 15709 // to the installation directory. Like say for /data/data/com.test-1.apk 15710 // string com.test-1 is returned. 15711 static String deriveCodePathName(String codePath) { 15712 if (codePath == null) { 15713 return null; 15714 } 15715 final File codeFile = new File(codePath); 15716 final String name = codeFile.getName(); 15717 if (codeFile.isDirectory()) { 15718 return name; 15719 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15720 final int lastDot = name.lastIndexOf('.'); 15721 return name.substring(0, lastDot); 15722 } else { 15723 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15724 return null; 15725 } 15726 } 15727 15728 static class PackageInstalledInfo { 15729 String name; 15730 int uid; 15731 // The set of users that originally had this package installed. 15732 int[] origUsers; 15733 // The set of users that now have this package installed. 15734 int[] newUsers; 15735 PackageParser.Package pkg; 15736 int returnCode; 15737 String returnMsg; 15738 PackageRemovedInfo removedInfo; 15739 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15740 15741 public void setError(int code, String msg) { 15742 setReturnCode(code); 15743 setReturnMessage(msg); 15744 Slog.w(TAG, msg); 15745 } 15746 15747 public void setError(String msg, PackageParserException e) { 15748 setReturnCode(e.error); 15749 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15750 Slog.w(TAG, msg, e); 15751 } 15752 15753 public void setError(String msg, PackageManagerException e) { 15754 returnCode = e.error; 15755 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15756 Slog.w(TAG, msg, e); 15757 } 15758 15759 public void setReturnCode(int returnCode) { 15760 this.returnCode = returnCode; 15761 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15762 for (int i = 0; i < childCount; i++) { 15763 addedChildPackages.valueAt(i).returnCode = returnCode; 15764 } 15765 } 15766 15767 private void setReturnMessage(String returnMsg) { 15768 this.returnMsg = returnMsg; 15769 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15770 for (int i = 0; i < childCount; i++) { 15771 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15772 } 15773 } 15774 15775 // In some error cases we want to convey more info back to the observer 15776 String origPackage; 15777 String origPermission; 15778 } 15779 15780 /* 15781 * Install a non-existing package. 15782 */ 15783 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15784 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15785 PackageInstalledInfo res, int installReason) { 15786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15787 15788 // Remember this for later, in case we need to rollback this install 15789 String pkgName = pkg.packageName; 15790 15791 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15792 15793 synchronized(mPackages) { 15794 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15795 if (renamedPackage != null) { 15796 // A package with the same name is already installed, though 15797 // it has been renamed to an older name. The package we 15798 // are trying to install should be installed as an update to 15799 // the existing one, but that has not been requested, so bail. 15800 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15801 + " without first uninstalling package running as " 15802 + renamedPackage); 15803 return; 15804 } 15805 if (mPackages.containsKey(pkgName)) { 15806 // Don't allow installation over an existing package with the same name. 15807 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15808 + " without first uninstalling."); 15809 return; 15810 } 15811 } 15812 15813 try { 15814 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15815 System.currentTimeMillis(), user); 15816 15817 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15818 15819 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15820 prepareAppDataAfterInstallLIF(newPackage); 15821 15822 } else { 15823 // Remove package from internal structures, but keep around any 15824 // data that might have already existed 15825 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15826 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15827 } 15828 } catch (PackageManagerException e) { 15829 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15830 } 15831 15832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15833 } 15834 15835 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15836 // Can't rotate keys during boot or if sharedUser. 15837 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15838 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15839 return false; 15840 } 15841 // app is using upgradeKeySets; make sure all are valid 15842 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15843 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15844 for (int i = 0; i < upgradeKeySets.length; i++) { 15845 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15846 Slog.wtf(TAG, "Package " 15847 + (oldPs.name != null ? oldPs.name : "<null>") 15848 + " contains upgrade-key-set reference to unknown key-set: " 15849 + upgradeKeySets[i] 15850 + " reverting to signatures check."); 15851 return false; 15852 } 15853 } 15854 return true; 15855 } 15856 15857 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15858 // Upgrade keysets are being used. Determine if new package has a superset of the 15859 // required keys. 15860 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15861 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15862 for (int i = 0; i < upgradeKeySets.length; i++) { 15863 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15864 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15865 return true; 15866 } 15867 } 15868 return false; 15869 } 15870 15871 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15872 try (DigestInputStream digestStream = 15873 new DigestInputStream(new FileInputStream(file), digest)) { 15874 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15875 } 15876 } 15877 15878 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15879 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15880 int installReason) { 15881 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15882 15883 final PackageParser.Package oldPackage; 15884 final String pkgName = pkg.packageName; 15885 final int[] allUsers; 15886 final int[] installedUsers; 15887 15888 synchronized(mPackages) { 15889 oldPackage = mPackages.get(pkgName); 15890 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15891 15892 // don't allow upgrade to target a release SDK from a pre-release SDK 15893 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15894 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15895 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15896 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15897 if (oldTargetsPreRelease 15898 && !newTargetsPreRelease 15899 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15900 Slog.w(TAG, "Can't install package targeting released sdk"); 15901 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15902 return; 15903 } 15904 15905 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15906 15907 // verify signatures are valid 15908 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15909 if (!checkUpgradeKeySetLP(ps, pkg)) { 15910 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15911 "New package not signed by keys specified by upgrade-keysets: " 15912 + pkgName); 15913 return; 15914 } 15915 } else { 15916 // default to original signature matching 15917 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15918 != PackageManager.SIGNATURE_MATCH) { 15919 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15920 "New package has a different signature: " + pkgName); 15921 return; 15922 } 15923 } 15924 15925 // don't allow a system upgrade unless the upgrade hash matches 15926 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15927 byte[] digestBytes = null; 15928 try { 15929 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15930 updateDigest(digest, new File(pkg.baseCodePath)); 15931 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15932 for (String path : pkg.splitCodePaths) { 15933 updateDigest(digest, new File(path)); 15934 } 15935 } 15936 digestBytes = digest.digest(); 15937 } catch (NoSuchAlgorithmException | IOException e) { 15938 res.setError(INSTALL_FAILED_INVALID_APK, 15939 "Could not compute hash: " + pkgName); 15940 return; 15941 } 15942 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15943 res.setError(INSTALL_FAILED_INVALID_APK, 15944 "New package fails restrict-update check: " + pkgName); 15945 return; 15946 } 15947 // retain upgrade restriction 15948 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15949 } 15950 15951 // Check for shared user id changes 15952 String invalidPackageName = 15953 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15954 if (invalidPackageName != null) { 15955 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15956 "Package " + invalidPackageName + " tried to change user " 15957 + oldPackage.mSharedUserId); 15958 return; 15959 } 15960 15961 // In case of rollback, remember per-user/profile install state 15962 allUsers = sUserManager.getUserIds(); 15963 installedUsers = ps.queryInstalledUsers(allUsers, true); 15964 15965 // don't allow an upgrade from full to ephemeral 15966 if (isInstantApp) { 15967 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15968 for (int currentUser : allUsers) { 15969 if (!ps.getInstantApp(currentUser)) { 15970 // can't downgrade from full to instant 15971 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15972 + " for user: " + currentUser); 15973 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15974 return; 15975 } 15976 } 15977 } else if (!ps.getInstantApp(user.getIdentifier())) { 15978 // can't downgrade from full to instant 15979 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15980 + " for user: " + user.getIdentifier()); 15981 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15982 return; 15983 } 15984 } 15985 } 15986 15987 // Update what is removed 15988 res.removedInfo = new PackageRemovedInfo(); 15989 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15990 res.removedInfo.removedPackage = oldPackage.packageName; 15991 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15992 res.removedInfo.isUpdate = true; 15993 res.removedInfo.origUsers = installedUsers; 15994 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15995 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15996 for (int i = 0; i < installedUsers.length; i++) { 15997 final int userId = installedUsers[i]; 15998 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15999 } 16000 16001 final int childCount = (oldPackage.childPackages != null) 16002 ? oldPackage.childPackages.size() : 0; 16003 for (int i = 0; i < childCount; i++) { 16004 boolean childPackageUpdated = false; 16005 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16006 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16007 if (res.addedChildPackages != null) { 16008 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16009 if (childRes != null) { 16010 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16011 childRes.removedInfo.removedPackage = childPkg.packageName; 16012 childRes.removedInfo.isUpdate = true; 16013 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16014 childPackageUpdated = true; 16015 } 16016 } 16017 if (!childPackageUpdated) { 16018 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16019 childRemovedRes.removedPackage = childPkg.packageName; 16020 childRemovedRes.isUpdate = false; 16021 childRemovedRes.dataRemoved = true; 16022 synchronized (mPackages) { 16023 if (childPs != null) { 16024 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16025 } 16026 } 16027 if (res.removedInfo.removedChildPackages == null) { 16028 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16029 } 16030 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16031 } 16032 } 16033 16034 boolean sysPkg = (isSystemApp(oldPackage)); 16035 if (sysPkg) { 16036 // Set the system/privileged flags as needed 16037 final boolean privileged = 16038 (oldPackage.applicationInfo.privateFlags 16039 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16040 final int systemPolicyFlags = policyFlags 16041 | PackageParser.PARSE_IS_SYSTEM 16042 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16043 16044 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16045 user, allUsers, installerPackageName, res, installReason); 16046 } else { 16047 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16048 user, allUsers, installerPackageName, res, installReason); 16049 } 16050 } 16051 16052 public List<String> getPreviousCodePaths(String packageName) { 16053 final PackageSetting ps = mSettings.mPackages.get(packageName); 16054 final List<String> result = new ArrayList<String>(); 16055 if (ps != null && ps.oldCodePaths != null) { 16056 result.addAll(ps.oldCodePaths); 16057 } 16058 return result; 16059 } 16060 16061 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16062 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16063 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16064 int installReason) { 16065 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16066 + deletedPackage); 16067 16068 String pkgName = deletedPackage.packageName; 16069 boolean deletedPkg = true; 16070 boolean addedPkg = false; 16071 boolean updatedSettings = false; 16072 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16073 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16074 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16075 16076 final long origUpdateTime = (pkg.mExtras != null) 16077 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16078 16079 // First delete the existing package while retaining the data directory 16080 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16081 res.removedInfo, true, pkg)) { 16082 // If the existing package wasn't successfully deleted 16083 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16084 deletedPkg = false; 16085 } else { 16086 // Successfully deleted the old package; proceed with replace. 16087 16088 // If deleted package lived in a container, give users a chance to 16089 // relinquish resources before killing. 16090 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16091 if (DEBUG_INSTALL) { 16092 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16093 } 16094 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16095 final ArrayList<String> pkgList = new ArrayList<String>(1); 16096 pkgList.add(deletedPackage.applicationInfo.packageName); 16097 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16098 } 16099 16100 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16101 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16102 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16103 16104 try { 16105 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16106 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16107 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16108 installReason); 16109 16110 // Update the in-memory copy of the previous code paths. 16111 PackageSetting ps = mSettings.mPackages.get(pkgName); 16112 if (!killApp) { 16113 if (ps.oldCodePaths == null) { 16114 ps.oldCodePaths = new ArraySet<>(); 16115 } 16116 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16117 if (deletedPackage.splitCodePaths != null) { 16118 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16119 } 16120 } else { 16121 ps.oldCodePaths = null; 16122 } 16123 if (ps.childPackageNames != null) { 16124 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16125 final String childPkgName = ps.childPackageNames.get(i); 16126 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16127 childPs.oldCodePaths = ps.oldCodePaths; 16128 } 16129 } 16130 // set instant app status, but, only if it's explicitly specified 16131 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16132 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16133 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16134 prepareAppDataAfterInstallLIF(newPackage); 16135 addedPkg = true; 16136 mDexManager.notifyPackageUpdated(newPackage.packageName, 16137 newPackage.baseCodePath, newPackage.splitCodePaths); 16138 } catch (PackageManagerException e) { 16139 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16140 } 16141 } 16142 16143 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16144 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16145 16146 // Revert all internal state mutations and added folders for the failed install 16147 if (addedPkg) { 16148 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16149 res.removedInfo, true, null); 16150 } 16151 16152 // Restore the old package 16153 if (deletedPkg) { 16154 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16155 File restoreFile = new File(deletedPackage.codePath); 16156 // Parse old package 16157 boolean oldExternal = isExternal(deletedPackage); 16158 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16159 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16160 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16161 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16162 try { 16163 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16164 null); 16165 } catch (PackageManagerException e) { 16166 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16167 + e.getMessage()); 16168 return; 16169 } 16170 16171 synchronized (mPackages) { 16172 // Ensure the installer package name up to date 16173 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16174 16175 // Update permissions for restored package 16176 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16177 16178 mSettings.writeLPr(); 16179 } 16180 16181 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16182 } 16183 } else { 16184 synchronized (mPackages) { 16185 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16186 if (ps != null) { 16187 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16188 if (res.removedInfo.removedChildPackages != null) { 16189 final int childCount = res.removedInfo.removedChildPackages.size(); 16190 // Iterate in reverse as we may modify the collection 16191 for (int i = childCount - 1; i >= 0; i--) { 16192 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16193 if (res.addedChildPackages.containsKey(childPackageName)) { 16194 res.removedInfo.removedChildPackages.removeAt(i); 16195 } else { 16196 PackageRemovedInfo childInfo = res.removedInfo 16197 .removedChildPackages.valueAt(i); 16198 childInfo.removedForAllUsers = mPackages.get( 16199 childInfo.removedPackage) == null; 16200 } 16201 } 16202 } 16203 } 16204 } 16205 } 16206 } 16207 16208 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16209 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16210 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16211 int installReason) { 16212 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16213 + ", old=" + deletedPackage); 16214 16215 final boolean disabledSystem; 16216 16217 // Remove existing system package 16218 removePackageLI(deletedPackage, true); 16219 16220 synchronized (mPackages) { 16221 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16222 } 16223 if (!disabledSystem) { 16224 // We didn't need to disable the .apk as a current system package, 16225 // which means we are replacing another update that is already 16226 // installed. We need to make sure to delete the older one's .apk. 16227 res.removedInfo.args = createInstallArgsForExisting(0, 16228 deletedPackage.applicationInfo.getCodePath(), 16229 deletedPackage.applicationInfo.getResourcePath(), 16230 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16231 } else { 16232 res.removedInfo.args = null; 16233 } 16234 16235 // Successfully disabled the old package. Now proceed with re-installation 16236 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16237 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16238 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16239 16240 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16241 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16242 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16243 16244 PackageParser.Package newPackage = null; 16245 try { 16246 // Add the package to the internal data structures 16247 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16248 16249 // Set the update and install times 16250 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16251 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16252 System.currentTimeMillis()); 16253 16254 // Update the package dynamic state if succeeded 16255 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16256 // Now that the install succeeded make sure we remove data 16257 // directories for any child package the update removed. 16258 final int deletedChildCount = (deletedPackage.childPackages != null) 16259 ? deletedPackage.childPackages.size() : 0; 16260 final int newChildCount = (newPackage.childPackages != null) 16261 ? newPackage.childPackages.size() : 0; 16262 for (int i = 0; i < deletedChildCount; i++) { 16263 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16264 boolean childPackageDeleted = true; 16265 for (int j = 0; j < newChildCount; j++) { 16266 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16267 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16268 childPackageDeleted = false; 16269 break; 16270 } 16271 } 16272 if (childPackageDeleted) { 16273 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16274 deletedChildPkg.packageName); 16275 if (ps != null && res.removedInfo.removedChildPackages != null) { 16276 PackageRemovedInfo removedChildRes = res.removedInfo 16277 .removedChildPackages.get(deletedChildPkg.packageName); 16278 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16279 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16280 } 16281 } 16282 } 16283 16284 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16285 installReason); 16286 prepareAppDataAfterInstallLIF(newPackage); 16287 16288 mDexManager.notifyPackageUpdated(newPackage.packageName, 16289 newPackage.baseCodePath, newPackage.splitCodePaths); 16290 } 16291 } catch (PackageManagerException e) { 16292 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16293 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16294 } 16295 16296 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16297 // Re installation failed. Restore old information 16298 // Remove new pkg information 16299 if (newPackage != null) { 16300 removeInstalledPackageLI(newPackage, true); 16301 } 16302 // Add back the old system package 16303 try { 16304 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16305 } catch (PackageManagerException e) { 16306 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16307 } 16308 16309 synchronized (mPackages) { 16310 if (disabledSystem) { 16311 enableSystemPackageLPw(deletedPackage); 16312 } 16313 16314 // Ensure the installer package name up to date 16315 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16316 16317 // Update permissions for restored package 16318 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16319 16320 mSettings.writeLPr(); 16321 } 16322 16323 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16324 + " after failed upgrade"); 16325 } 16326 } 16327 16328 /** 16329 * Checks whether the parent or any of the child packages have a change shared 16330 * user. For a package to be a valid update the shred users of the parent and 16331 * the children should match. We may later support changing child shared users. 16332 * @param oldPkg The updated package. 16333 * @param newPkg The update package. 16334 * @return The shared user that change between the versions. 16335 */ 16336 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16337 PackageParser.Package newPkg) { 16338 // Check parent shared user 16339 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16340 return newPkg.packageName; 16341 } 16342 // Check child shared users 16343 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16344 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16345 for (int i = 0; i < newChildCount; i++) { 16346 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16347 // If this child was present, did it have the same shared user? 16348 for (int j = 0; j < oldChildCount; j++) { 16349 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16350 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16351 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16352 return newChildPkg.packageName; 16353 } 16354 } 16355 } 16356 return null; 16357 } 16358 16359 private void removeNativeBinariesLI(PackageSetting ps) { 16360 // Remove the lib path for the parent package 16361 if (ps != null) { 16362 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16363 // Remove the lib path for the child packages 16364 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16365 for (int i = 0; i < childCount; i++) { 16366 PackageSetting childPs = null; 16367 synchronized (mPackages) { 16368 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16369 } 16370 if (childPs != null) { 16371 NativeLibraryHelper.removeNativeBinariesLI(childPs 16372 .legacyNativeLibraryPathString); 16373 } 16374 } 16375 } 16376 } 16377 16378 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16379 // Enable the parent package 16380 mSettings.enableSystemPackageLPw(pkg.packageName); 16381 // Enable the child packages 16382 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16383 for (int i = 0; i < childCount; i++) { 16384 PackageParser.Package childPkg = pkg.childPackages.get(i); 16385 mSettings.enableSystemPackageLPw(childPkg.packageName); 16386 } 16387 } 16388 16389 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16390 PackageParser.Package newPkg) { 16391 // Disable the parent package (parent always replaced) 16392 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16393 // Disable the child packages 16394 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16395 for (int i = 0; i < childCount; i++) { 16396 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16397 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16398 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16399 } 16400 return disabled; 16401 } 16402 16403 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16404 String installerPackageName) { 16405 // Enable the parent package 16406 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16407 // Enable the child packages 16408 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16409 for (int i = 0; i < childCount; i++) { 16410 PackageParser.Package childPkg = pkg.childPackages.get(i); 16411 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16412 } 16413 } 16414 16415 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16416 // Collect all used permissions in the UID 16417 ArraySet<String> usedPermissions = new ArraySet<>(); 16418 final int packageCount = su.packages.size(); 16419 for (int i = 0; i < packageCount; i++) { 16420 PackageSetting ps = su.packages.valueAt(i); 16421 if (ps.pkg == null) { 16422 continue; 16423 } 16424 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16425 for (int j = 0; j < requestedPermCount; j++) { 16426 String permission = ps.pkg.requestedPermissions.get(j); 16427 BasePermission bp = mSettings.mPermissions.get(permission); 16428 if (bp != null) { 16429 usedPermissions.add(permission); 16430 } 16431 } 16432 } 16433 16434 PermissionsState permissionsState = su.getPermissionsState(); 16435 // Prune install permissions 16436 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16437 final int installPermCount = installPermStates.size(); 16438 for (int i = installPermCount - 1; i >= 0; i--) { 16439 PermissionState permissionState = installPermStates.get(i); 16440 if (!usedPermissions.contains(permissionState.getName())) { 16441 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16442 if (bp != null) { 16443 permissionsState.revokeInstallPermission(bp); 16444 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16445 PackageManager.MASK_PERMISSION_FLAGS, 0); 16446 } 16447 } 16448 } 16449 16450 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16451 16452 // Prune runtime permissions 16453 for (int userId : allUserIds) { 16454 List<PermissionState> runtimePermStates = permissionsState 16455 .getRuntimePermissionStates(userId); 16456 final int runtimePermCount = runtimePermStates.size(); 16457 for (int i = runtimePermCount - 1; i >= 0; i--) { 16458 PermissionState permissionState = runtimePermStates.get(i); 16459 if (!usedPermissions.contains(permissionState.getName())) { 16460 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16461 if (bp != null) { 16462 permissionsState.revokeRuntimePermission(bp, userId); 16463 permissionsState.updatePermissionFlags(bp, userId, 16464 PackageManager.MASK_PERMISSION_FLAGS, 0); 16465 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16466 runtimePermissionChangedUserIds, userId); 16467 } 16468 } 16469 } 16470 } 16471 16472 return runtimePermissionChangedUserIds; 16473 } 16474 16475 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16476 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16477 // Update the parent package setting 16478 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16479 res, user, installReason); 16480 // Update the child packages setting 16481 final int childCount = (newPackage.childPackages != null) 16482 ? newPackage.childPackages.size() : 0; 16483 for (int i = 0; i < childCount; i++) { 16484 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16485 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16486 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16487 childRes.origUsers, childRes, user, installReason); 16488 } 16489 } 16490 16491 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16492 String installerPackageName, int[] allUsers, int[] installedForUsers, 16493 PackageInstalledInfo res, UserHandle user, int installReason) { 16494 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16495 16496 String pkgName = newPackage.packageName; 16497 synchronized (mPackages) { 16498 //write settings. the installStatus will be incomplete at this stage. 16499 //note that the new package setting would have already been 16500 //added to mPackages. It hasn't been persisted yet. 16501 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16502 // TODO: Remove this write? It's also written at the end of this method 16503 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16504 mSettings.writeLPr(); 16505 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16506 } 16507 16508 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16509 synchronized (mPackages) { 16510 updatePermissionsLPw(newPackage.packageName, newPackage, 16511 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16512 ? UPDATE_PERMISSIONS_ALL : 0)); 16513 // For system-bundled packages, we assume that installing an upgraded version 16514 // of the package implies that the user actually wants to run that new code, 16515 // so we enable the package. 16516 PackageSetting ps = mSettings.mPackages.get(pkgName); 16517 final int userId = user.getIdentifier(); 16518 if (ps != null) { 16519 if (isSystemApp(newPackage)) { 16520 if (DEBUG_INSTALL) { 16521 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16522 } 16523 // Enable system package for requested users 16524 if (res.origUsers != null) { 16525 for (int origUserId : res.origUsers) { 16526 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16527 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16528 origUserId, installerPackageName); 16529 } 16530 } 16531 } 16532 // Also convey the prior install/uninstall state 16533 if (allUsers != null && installedForUsers != null) { 16534 for (int currentUserId : allUsers) { 16535 final boolean installed = ArrayUtils.contains( 16536 installedForUsers, currentUserId); 16537 if (DEBUG_INSTALL) { 16538 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16539 } 16540 ps.setInstalled(installed, currentUserId); 16541 } 16542 // these install state changes will be persisted in the 16543 // upcoming call to mSettings.writeLPr(). 16544 } 16545 } 16546 // It's implied that when a user requests installation, they want the app to be 16547 // installed and enabled. 16548 if (userId != UserHandle.USER_ALL) { 16549 ps.setInstalled(true, userId); 16550 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16551 } 16552 16553 // When replacing an existing package, preserve the original install reason for all 16554 // users that had the package installed before. 16555 final Set<Integer> previousUserIds = new ArraySet<>(); 16556 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16557 final int installReasonCount = res.removedInfo.installReasons.size(); 16558 for (int i = 0; i < installReasonCount; i++) { 16559 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16560 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16561 ps.setInstallReason(previousInstallReason, previousUserId); 16562 previousUserIds.add(previousUserId); 16563 } 16564 } 16565 16566 // Set install reason for users that are having the package newly installed. 16567 if (userId == UserHandle.USER_ALL) { 16568 for (int currentUserId : sUserManager.getUserIds()) { 16569 if (!previousUserIds.contains(currentUserId)) { 16570 ps.setInstallReason(installReason, currentUserId); 16571 } 16572 } 16573 } else if (!previousUserIds.contains(userId)) { 16574 ps.setInstallReason(installReason, userId); 16575 } 16576 mSettings.writeKernelMappingLPr(ps); 16577 } 16578 res.name = pkgName; 16579 res.uid = newPackage.applicationInfo.uid; 16580 res.pkg = newPackage; 16581 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16582 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16583 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16584 //to update install status 16585 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16586 mSettings.writeLPr(); 16587 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16588 } 16589 16590 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16591 } 16592 16593 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16594 try { 16595 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16596 installPackageLI(args, res); 16597 } finally { 16598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16599 } 16600 } 16601 16602 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16603 final int installFlags = args.installFlags; 16604 final String installerPackageName = args.installerPackageName; 16605 final String volumeUuid = args.volumeUuid; 16606 final File tmpPackageFile = new File(args.getCodePath()); 16607 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16608 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16609 || (args.volumeUuid != null)); 16610 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16611 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16612 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16613 boolean replace = false; 16614 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16615 if (args.move != null) { 16616 // moving a complete application; perform an initial scan on the new install location 16617 scanFlags |= SCAN_INITIAL; 16618 } 16619 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16620 scanFlags |= SCAN_DONT_KILL_APP; 16621 } 16622 if (instantApp) { 16623 scanFlags |= SCAN_AS_INSTANT_APP; 16624 } 16625 if (fullApp) { 16626 scanFlags |= SCAN_AS_FULL_APP; 16627 } 16628 16629 // Result object to be returned 16630 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16631 16632 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16633 16634 // Sanity check 16635 if (instantApp && (forwardLocked || onExternal)) { 16636 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16637 + " external=" + onExternal); 16638 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16639 return; 16640 } 16641 16642 // Retrieve PackageSettings and parse package 16643 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16644 | PackageParser.PARSE_ENFORCE_CODE 16645 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16646 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16647 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16648 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16649 PackageParser pp = new PackageParser(); 16650 pp.setSeparateProcesses(mSeparateProcesses); 16651 pp.setDisplayMetrics(mMetrics); 16652 pp.setCallback(mPackageParserCallback); 16653 16654 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16655 final PackageParser.Package pkg; 16656 try { 16657 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16658 } catch (PackageParserException e) { 16659 res.setError("Failed parse during installPackageLI", e); 16660 return; 16661 } finally { 16662 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16663 } 16664 16665 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16666 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16667 Slog.w(TAG, "Instant app package " + pkg.packageName 16668 + " does not target O, this will be a fatal error."); 16669 // STOPSHIP: Make this a fatal error 16670 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16671 } 16672 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16673 Slog.w(TAG, "Instant app package " + pkg.packageName 16674 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16675 // STOPSHIP: Make this a fatal error 16676 pkg.applicationInfo.targetSandboxVersion = 2; 16677 } 16678 16679 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16680 // Static shared libraries have synthetic package names 16681 renameStaticSharedLibraryPackage(pkg); 16682 16683 // No static shared libs on external storage 16684 if (onExternal) { 16685 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16686 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16687 "Packages declaring static-shared libs cannot be updated"); 16688 return; 16689 } 16690 } 16691 16692 // If we are installing a clustered package add results for the children 16693 if (pkg.childPackages != null) { 16694 synchronized (mPackages) { 16695 final int childCount = pkg.childPackages.size(); 16696 for (int i = 0; i < childCount; i++) { 16697 PackageParser.Package childPkg = pkg.childPackages.get(i); 16698 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16699 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16700 childRes.pkg = childPkg; 16701 childRes.name = childPkg.packageName; 16702 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16703 if (childPs != null) { 16704 childRes.origUsers = childPs.queryInstalledUsers( 16705 sUserManager.getUserIds(), true); 16706 } 16707 if ((mPackages.containsKey(childPkg.packageName))) { 16708 childRes.removedInfo = new PackageRemovedInfo(); 16709 childRes.removedInfo.removedPackage = childPkg.packageName; 16710 } 16711 if (res.addedChildPackages == null) { 16712 res.addedChildPackages = new ArrayMap<>(); 16713 } 16714 res.addedChildPackages.put(childPkg.packageName, childRes); 16715 } 16716 } 16717 } 16718 16719 // If package doesn't declare API override, mark that we have an install 16720 // time CPU ABI override. 16721 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16722 pkg.cpuAbiOverride = args.abiOverride; 16723 } 16724 16725 String pkgName = res.name = pkg.packageName; 16726 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16727 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16728 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16729 return; 16730 } 16731 } 16732 16733 try { 16734 // either use what we've been given or parse directly from the APK 16735 if (args.certificates != null) { 16736 try { 16737 PackageParser.populateCertificates(pkg, args.certificates); 16738 } catch (PackageParserException e) { 16739 // there was something wrong with the certificates we were given; 16740 // try to pull them from the APK 16741 PackageParser.collectCertificates(pkg, parseFlags); 16742 } 16743 } else { 16744 PackageParser.collectCertificates(pkg, parseFlags); 16745 } 16746 } catch (PackageParserException e) { 16747 res.setError("Failed collect during installPackageLI", e); 16748 return; 16749 } 16750 16751 // Get rid of all references to package scan path via parser. 16752 pp = null; 16753 String oldCodePath = null; 16754 boolean systemApp = false; 16755 synchronized (mPackages) { 16756 // Check if installing already existing package 16757 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16758 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16759 if (pkg.mOriginalPackages != null 16760 && pkg.mOriginalPackages.contains(oldName) 16761 && mPackages.containsKey(oldName)) { 16762 // This package is derived from an original package, 16763 // and this device has been updating from that original 16764 // name. We must continue using the original name, so 16765 // rename the new package here. 16766 pkg.setPackageName(oldName); 16767 pkgName = pkg.packageName; 16768 replace = true; 16769 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16770 + oldName + " pkgName=" + pkgName); 16771 } else if (mPackages.containsKey(pkgName)) { 16772 // This package, under its official name, already exists 16773 // on the device; we should replace it. 16774 replace = true; 16775 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16776 } 16777 16778 // Child packages are installed through the parent package 16779 if (pkg.parentPackage != null) { 16780 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16781 "Package " + pkg.packageName + " is child of package " 16782 + pkg.parentPackage.parentPackage + ". Child packages " 16783 + "can be updated only through the parent package."); 16784 return; 16785 } 16786 16787 if (replace) { 16788 // Prevent apps opting out from runtime permissions 16789 PackageParser.Package oldPackage = mPackages.get(pkgName); 16790 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16791 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16792 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16793 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16794 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16795 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16796 + " doesn't support runtime permissions but the old" 16797 + " target SDK " + oldTargetSdk + " does."); 16798 return; 16799 } 16800 16801 // Prevent installing of child packages 16802 if (oldPackage.parentPackage != null) { 16803 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16804 "Package " + pkg.packageName + " is child of package " 16805 + oldPackage.parentPackage + ". Child packages " 16806 + "can be updated only through the parent package."); 16807 return; 16808 } 16809 } 16810 } 16811 16812 PackageSetting ps = mSettings.mPackages.get(pkgName); 16813 if (ps != null) { 16814 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16815 16816 // Static shared libs have same package with different versions where 16817 // we internally use a synthetic package name to allow multiple versions 16818 // of the same package, therefore we need to compare signatures against 16819 // the package setting for the latest library version. 16820 PackageSetting signatureCheckPs = ps; 16821 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16822 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16823 if (libraryEntry != null) { 16824 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16825 } 16826 } 16827 16828 // Quick sanity check that we're signed correctly if updating; 16829 // we'll check this again later when scanning, but we want to 16830 // bail early here before tripping over redefined permissions. 16831 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16832 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16833 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16834 + pkg.packageName + " upgrade keys do not match the " 16835 + "previously installed version"); 16836 return; 16837 } 16838 } else { 16839 try { 16840 verifySignaturesLP(signatureCheckPs, pkg); 16841 } catch (PackageManagerException e) { 16842 res.setError(e.error, e.getMessage()); 16843 return; 16844 } 16845 } 16846 16847 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16848 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16849 systemApp = (ps.pkg.applicationInfo.flags & 16850 ApplicationInfo.FLAG_SYSTEM) != 0; 16851 } 16852 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16853 } 16854 16855 int N = pkg.permissions.size(); 16856 for (int i = N-1; i >= 0; i--) { 16857 PackageParser.Permission perm = pkg.permissions.get(i); 16858 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16859 16860 // Don't allow anyone but the platform to define ephemeral permissions. 16861 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16862 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16863 Slog.w(TAG, "Package " + pkg.packageName 16864 + " attempting to delcare ephemeral permission " 16865 + perm.info.name + "; Removing ephemeral."); 16866 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16867 } 16868 // Check whether the newly-scanned package wants to define an already-defined perm 16869 if (bp != null) { 16870 // If the defining package is signed with our cert, it's okay. This 16871 // also includes the "updating the same package" case, of course. 16872 // "updating same package" could also involve key-rotation. 16873 final boolean sigsOk; 16874 if (bp.sourcePackage.equals(pkg.packageName) 16875 && (bp.packageSetting instanceof PackageSetting) 16876 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16877 scanFlags))) { 16878 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16879 } else { 16880 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16881 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16882 } 16883 if (!sigsOk) { 16884 // If the owning package is the system itself, we log but allow 16885 // install to proceed; we fail the install on all other permission 16886 // redefinitions. 16887 if (!bp.sourcePackage.equals("android")) { 16888 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16889 + pkg.packageName + " attempting to redeclare permission " 16890 + perm.info.name + " already owned by " + bp.sourcePackage); 16891 res.origPermission = perm.info.name; 16892 res.origPackage = bp.sourcePackage; 16893 return; 16894 } else { 16895 Slog.w(TAG, "Package " + pkg.packageName 16896 + " attempting to redeclare system permission " 16897 + perm.info.name + "; ignoring new declaration"); 16898 pkg.permissions.remove(i); 16899 } 16900 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16901 // Prevent apps to change protection level to dangerous from any other 16902 // type as this would allow a privilege escalation where an app adds a 16903 // normal/signature permission in other app's group and later redefines 16904 // it as dangerous leading to the group auto-grant. 16905 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16906 == PermissionInfo.PROTECTION_DANGEROUS) { 16907 if (bp != null && !bp.isRuntime()) { 16908 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16909 + "non-runtime permission " + perm.info.name 16910 + " to runtime; keeping old protection level"); 16911 perm.info.protectionLevel = bp.protectionLevel; 16912 } 16913 } 16914 } 16915 } 16916 } 16917 } 16918 16919 if (systemApp) { 16920 if (onExternal) { 16921 // Abort update; system app can't be replaced with app on sdcard 16922 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16923 "Cannot install updates to system apps on sdcard"); 16924 return; 16925 } else if (instantApp) { 16926 // Abort update; system app can't be replaced with an instant app 16927 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16928 "Cannot update a system app with an instant app"); 16929 return; 16930 } 16931 } 16932 16933 if (args.move != null) { 16934 // We did an in-place move, so dex is ready to roll 16935 scanFlags |= SCAN_NO_DEX; 16936 scanFlags |= SCAN_MOVE; 16937 16938 synchronized (mPackages) { 16939 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16940 if (ps == null) { 16941 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16942 "Missing settings for moved package " + pkgName); 16943 } 16944 16945 // We moved the entire application as-is, so bring over the 16946 // previously derived ABI information. 16947 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16948 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16949 } 16950 16951 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16952 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16953 scanFlags |= SCAN_NO_DEX; 16954 16955 try { 16956 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16957 args.abiOverride : pkg.cpuAbiOverride); 16958 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16959 true /*extractLibs*/, mAppLib32InstallDir); 16960 } catch (PackageManagerException pme) { 16961 Slog.e(TAG, "Error deriving application ABI", pme); 16962 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16963 return; 16964 } 16965 16966 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16967 // Do not run PackageDexOptimizer through the local performDexOpt 16968 // method because `pkg` may not be in `mPackages` yet. 16969 // 16970 // Also, don't fail application installs if the dexopt step fails. 16971 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16972 null /* instructionSets */, false /* checkProfiles */, 16973 getCompilerFilterForReason(REASON_INSTALL), 16974 getOrCreateCompilerPackageStats(pkg), 16975 mDexManager.isUsedByOtherApps(pkg.packageName)); 16976 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16977 16978 // Notify BackgroundDexOptJobService that the package has been changed. 16979 // If this is an update of a package which used to fail to compile, 16980 // BDOS will remove it from its blacklist. 16981 // TODO: Layering violation 16982 BackgroundDexOptJobService.notifyPackageChanged(pkg.packageName); 16983 } 16984 16985 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16986 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16987 return; 16988 } 16989 16990 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16991 16992 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16993 "installPackageLI")) { 16994 if (replace) { 16995 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16996 // Static libs have a synthetic package name containing the version 16997 // and cannot be updated as an update would get a new package name, 16998 // unless this is the exact same version code which is useful for 16999 // development. 17000 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17001 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17002 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17003 + "static-shared libs cannot be updated"); 17004 return; 17005 } 17006 } 17007 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17008 installerPackageName, res, args.installReason); 17009 } else { 17010 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17011 args.user, installerPackageName, volumeUuid, res, args.installReason); 17012 } 17013 } 17014 synchronized (mPackages) { 17015 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17016 if (ps != null) { 17017 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17018 } 17019 17020 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17021 for (int i = 0; i < childCount; i++) { 17022 PackageParser.Package childPkg = pkg.childPackages.get(i); 17023 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17024 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17025 if (childPs != null) { 17026 childRes.newUsers = childPs.queryInstalledUsers( 17027 sUserManager.getUserIds(), true); 17028 } 17029 } 17030 17031 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17032 updateSequenceNumberLP(pkgName, res.newUsers); 17033 } 17034 } 17035 } 17036 17037 private void startIntentFilterVerifications(int userId, boolean replacing, 17038 PackageParser.Package pkg) { 17039 if (mIntentFilterVerifierComponent == null) { 17040 Slog.w(TAG, "No IntentFilter verification will not be done as " 17041 + "there is no IntentFilterVerifier available!"); 17042 return; 17043 } 17044 17045 final int verifierUid = getPackageUid( 17046 mIntentFilterVerifierComponent.getPackageName(), 17047 MATCH_DEBUG_TRIAGED_MISSING, 17048 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17049 17050 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17051 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17052 mHandler.sendMessage(msg); 17053 17054 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17055 for (int i = 0; i < childCount; i++) { 17056 PackageParser.Package childPkg = pkg.childPackages.get(i); 17057 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17058 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17059 mHandler.sendMessage(msg); 17060 } 17061 } 17062 17063 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17064 PackageParser.Package pkg) { 17065 int size = pkg.activities.size(); 17066 if (size == 0) { 17067 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17068 "No activity, so no need to verify any IntentFilter!"); 17069 return; 17070 } 17071 17072 final boolean hasDomainURLs = hasDomainURLs(pkg); 17073 if (!hasDomainURLs) { 17074 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17075 "No domain URLs, so no need to verify any IntentFilter!"); 17076 return; 17077 } 17078 17079 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17080 + " if any IntentFilter from the " + size 17081 + " Activities needs verification ..."); 17082 17083 int count = 0; 17084 final String packageName = pkg.packageName; 17085 17086 synchronized (mPackages) { 17087 // If this is a new install and we see that we've already run verification for this 17088 // package, we have nothing to do: it means the state was restored from backup. 17089 if (!replacing) { 17090 IntentFilterVerificationInfo ivi = 17091 mSettings.getIntentFilterVerificationLPr(packageName); 17092 if (ivi != null) { 17093 if (DEBUG_DOMAIN_VERIFICATION) { 17094 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17095 + ivi.getStatusString()); 17096 } 17097 return; 17098 } 17099 } 17100 17101 // If any filters need to be verified, then all need to be. 17102 boolean needToVerify = false; 17103 for (PackageParser.Activity a : pkg.activities) { 17104 for (ActivityIntentInfo filter : a.intents) { 17105 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17106 if (DEBUG_DOMAIN_VERIFICATION) { 17107 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17108 } 17109 needToVerify = true; 17110 break; 17111 } 17112 } 17113 } 17114 17115 if (needToVerify) { 17116 final int verificationId = mIntentFilterVerificationToken++; 17117 for (PackageParser.Activity a : pkg.activities) { 17118 for (ActivityIntentInfo filter : a.intents) { 17119 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17120 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17121 "Verification needed for IntentFilter:" + filter.toString()); 17122 mIntentFilterVerifier.addOneIntentFilterVerification( 17123 verifierUid, userId, verificationId, filter, packageName); 17124 count++; 17125 } 17126 } 17127 } 17128 } 17129 } 17130 17131 if (count > 0) { 17132 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17133 + " IntentFilter verification" + (count > 1 ? "s" : "") 17134 + " for userId:" + userId); 17135 mIntentFilterVerifier.startVerifications(userId); 17136 } else { 17137 if (DEBUG_DOMAIN_VERIFICATION) { 17138 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17139 } 17140 } 17141 } 17142 17143 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17144 final ComponentName cn = filter.activity.getComponentName(); 17145 final String packageName = cn.getPackageName(); 17146 17147 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17148 packageName); 17149 if (ivi == null) { 17150 return true; 17151 } 17152 int status = ivi.getStatus(); 17153 switch (status) { 17154 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17155 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17156 return true; 17157 17158 default: 17159 // Nothing to do 17160 return false; 17161 } 17162 } 17163 17164 private static boolean isMultiArch(ApplicationInfo info) { 17165 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17166 } 17167 17168 private static boolean isExternal(PackageParser.Package pkg) { 17169 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17170 } 17171 17172 private static boolean isExternal(PackageSetting ps) { 17173 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17174 } 17175 17176 private static boolean isSystemApp(PackageParser.Package pkg) { 17177 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17178 } 17179 17180 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17181 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17182 } 17183 17184 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17185 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17186 } 17187 17188 private static boolean isSystemApp(PackageSetting ps) { 17189 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17190 } 17191 17192 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17193 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17194 } 17195 17196 private int packageFlagsToInstallFlags(PackageSetting ps) { 17197 int installFlags = 0; 17198 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17199 // This existing package was an external ASEC install when we have 17200 // the external flag without a UUID 17201 installFlags |= PackageManager.INSTALL_EXTERNAL; 17202 } 17203 if (ps.isForwardLocked()) { 17204 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17205 } 17206 return installFlags; 17207 } 17208 17209 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17210 if (isExternal(pkg)) { 17211 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17212 return StorageManager.UUID_PRIMARY_PHYSICAL; 17213 } else { 17214 return pkg.volumeUuid; 17215 } 17216 } else { 17217 return StorageManager.UUID_PRIVATE_INTERNAL; 17218 } 17219 } 17220 17221 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17222 if (isExternal(pkg)) { 17223 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17224 return mSettings.getExternalVersion(); 17225 } else { 17226 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17227 } 17228 } else { 17229 return mSettings.getInternalVersion(); 17230 } 17231 } 17232 17233 private void deleteTempPackageFiles() { 17234 final FilenameFilter filter = new FilenameFilter() { 17235 public boolean accept(File dir, String name) { 17236 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17237 } 17238 }; 17239 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17240 file.delete(); 17241 } 17242 } 17243 17244 @Override 17245 public void deletePackageAsUser(String packageName, int versionCode, 17246 IPackageDeleteObserver observer, int userId, int flags) { 17247 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17248 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17249 } 17250 17251 @Override 17252 public void deletePackageVersioned(VersionedPackage versionedPackage, 17253 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17254 mContext.enforceCallingOrSelfPermission( 17255 android.Manifest.permission.DELETE_PACKAGES, null); 17256 Preconditions.checkNotNull(versionedPackage); 17257 Preconditions.checkNotNull(observer); 17258 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17259 PackageManager.VERSION_CODE_HIGHEST, 17260 Integer.MAX_VALUE, "versionCode must be >= -1"); 17261 17262 final String packageName = versionedPackage.getPackageName(); 17263 // TODO: We will change version code to long, so in the new API it is long 17264 final int versionCode = (int) versionedPackage.getVersionCode(); 17265 final String internalPackageName; 17266 synchronized (mPackages) { 17267 // Normalize package name to handle renamed packages and static libs 17268 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17269 // TODO: We will change version code to long, so in the new API it is long 17270 (int) versionedPackage.getVersionCode()); 17271 } 17272 17273 final int uid = Binder.getCallingUid(); 17274 if (!isOrphaned(internalPackageName) 17275 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17276 try { 17277 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17278 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17279 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17280 observer.onUserActionRequired(intent); 17281 } catch (RemoteException re) { 17282 } 17283 return; 17284 } 17285 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17286 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17287 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17288 mContext.enforceCallingOrSelfPermission( 17289 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17290 "deletePackage for user " + userId); 17291 } 17292 17293 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17294 try { 17295 observer.onPackageDeleted(packageName, 17296 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17297 } catch (RemoteException re) { 17298 } 17299 return; 17300 } 17301 17302 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17303 try { 17304 observer.onPackageDeleted(packageName, 17305 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17306 } catch (RemoteException re) { 17307 } 17308 return; 17309 } 17310 17311 if (DEBUG_REMOVE) { 17312 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17313 + " deleteAllUsers: " + deleteAllUsers + " version=" 17314 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17315 ? "VERSION_CODE_HIGHEST" : versionCode)); 17316 } 17317 // Queue up an async operation since the package deletion may take a little while. 17318 mHandler.post(new Runnable() { 17319 public void run() { 17320 mHandler.removeCallbacks(this); 17321 int returnCode; 17322 if (!deleteAllUsers) { 17323 returnCode = deletePackageX(internalPackageName, versionCode, 17324 userId, deleteFlags); 17325 } else { 17326 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17327 internalPackageName, users); 17328 // If nobody is blocking uninstall, proceed with delete for all users 17329 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17330 returnCode = deletePackageX(internalPackageName, versionCode, 17331 userId, deleteFlags); 17332 } else { 17333 // Otherwise uninstall individually for users with blockUninstalls=false 17334 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17335 for (int userId : users) { 17336 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17337 returnCode = deletePackageX(internalPackageName, versionCode, 17338 userId, userFlags); 17339 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17340 Slog.w(TAG, "Package delete failed for user " + userId 17341 + ", returnCode " + returnCode); 17342 } 17343 } 17344 } 17345 // The app has only been marked uninstalled for certain users. 17346 // We still need to report that delete was blocked 17347 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17348 } 17349 } 17350 try { 17351 observer.onPackageDeleted(packageName, returnCode, null); 17352 } catch (RemoteException e) { 17353 Log.i(TAG, "Observer no longer exists."); 17354 } //end catch 17355 } //end run 17356 }); 17357 } 17358 17359 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17360 if (pkg.staticSharedLibName != null) { 17361 return pkg.manifestPackageName; 17362 } 17363 return pkg.packageName; 17364 } 17365 17366 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17367 // Handle renamed packages 17368 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17369 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17370 17371 // Is this a static library? 17372 SparseArray<SharedLibraryEntry> versionedLib = 17373 mStaticLibsByDeclaringPackage.get(packageName); 17374 if (versionedLib == null || versionedLib.size() <= 0) { 17375 return packageName; 17376 } 17377 17378 // Figure out which lib versions the caller can see 17379 SparseIntArray versionsCallerCanSee = null; 17380 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17381 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17382 && callingAppId != Process.ROOT_UID) { 17383 versionsCallerCanSee = new SparseIntArray(); 17384 String libName = versionedLib.valueAt(0).info.getName(); 17385 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17386 if (uidPackages != null) { 17387 for (String uidPackage : uidPackages) { 17388 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17389 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17390 if (libIdx >= 0) { 17391 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17392 versionsCallerCanSee.append(libVersion, libVersion); 17393 } 17394 } 17395 } 17396 } 17397 17398 // Caller can see nothing - done 17399 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17400 return packageName; 17401 } 17402 17403 // Find the version the caller can see and the app version code 17404 SharedLibraryEntry highestVersion = null; 17405 final int versionCount = versionedLib.size(); 17406 for (int i = 0; i < versionCount; i++) { 17407 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17408 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17409 libEntry.info.getVersion()) < 0) { 17410 continue; 17411 } 17412 // TODO: We will change version code to long, so in the new API it is long 17413 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17414 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17415 if (libVersionCode == versionCode) { 17416 return libEntry.apk; 17417 } 17418 } else if (highestVersion == null) { 17419 highestVersion = libEntry; 17420 } else if (libVersionCode > highestVersion.info 17421 .getDeclaringPackage().getVersionCode()) { 17422 highestVersion = libEntry; 17423 } 17424 } 17425 17426 if (highestVersion != null) { 17427 return highestVersion.apk; 17428 } 17429 17430 return packageName; 17431 } 17432 17433 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17434 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17435 || callingUid == Process.SYSTEM_UID) { 17436 return true; 17437 } 17438 final int callingUserId = UserHandle.getUserId(callingUid); 17439 // If the caller installed the pkgName, then allow it to silently uninstall. 17440 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17441 return true; 17442 } 17443 17444 // Allow package verifier to silently uninstall. 17445 if (mRequiredVerifierPackage != null && 17446 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17447 return true; 17448 } 17449 17450 // Allow package uninstaller to silently uninstall. 17451 if (mRequiredUninstallerPackage != null && 17452 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17453 return true; 17454 } 17455 17456 // Allow storage manager to silently uninstall. 17457 if (mStorageManagerPackage != null && 17458 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17459 return true; 17460 } 17461 return false; 17462 } 17463 17464 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17465 int[] result = EMPTY_INT_ARRAY; 17466 for (int userId : userIds) { 17467 if (getBlockUninstallForUser(packageName, userId)) { 17468 result = ArrayUtils.appendInt(result, userId); 17469 } 17470 } 17471 return result; 17472 } 17473 17474 @Override 17475 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17476 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17477 } 17478 17479 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17480 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17481 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17482 try { 17483 if (dpm != null) { 17484 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17485 /* callingUserOnly =*/ false); 17486 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17487 : deviceOwnerComponentName.getPackageName(); 17488 // Does the package contains the device owner? 17489 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17490 // this check is probably not needed, since DO should be registered as a device 17491 // admin on some user too. (Original bug for this: b/17657954) 17492 if (packageName.equals(deviceOwnerPackageName)) { 17493 return true; 17494 } 17495 // Does it contain a device admin for any user? 17496 int[] users; 17497 if (userId == UserHandle.USER_ALL) { 17498 users = sUserManager.getUserIds(); 17499 } else { 17500 users = new int[]{userId}; 17501 } 17502 for (int i = 0; i < users.length; ++i) { 17503 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17504 return true; 17505 } 17506 } 17507 } 17508 } catch (RemoteException e) { 17509 } 17510 return false; 17511 } 17512 17513 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17514 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17515 } 17516 17517 /** 17518 * This method is an internal method that could be get invoked either 17519 * to delete an installed package or to clean up a failed installation. 17520 * After deleting an installed package, a broadcast is sent to notify any 17521 * listeners that the package has been removed. For cleaning up a failed 17522 * installation, the broadcast is not necessary since the package's 17523 * installation wouldn't have sent the initial broadcast either 17524 * The key steps in deleting a package are 17525 * deleting the package information in internal structures like mPackages, 17526 * deleting the packages base directories through installd 17527 * updating mSettings to reflect current status 17528 * persisting settings for later use 17529 * sending a broadcast if necessary 17530 */ 17531 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17532 final PackageRemovedInfo info = new PackageRemovedInfo(); 17533 final boolean res; 17534 17535 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17536 ? UserHandle.USER_ALL : userId; 17537 17538 if (isPackageDeviceAdmin(packageName, removeUser)) { 17539 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17540 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17541 } 17542 17543 PackageSetting uninstalledPs = null; 17544 17545 // for the uninstall-updates case and restricted profiles, remember the per- 17546 // user handle installed state 17547 int[] allUsers; 17548 synchronized (mPackages) { 17549 uninstalledPs = mSettings.mPackages.get(packageName); 17550 if (uninstalledPs == null) { 17551 Slog.w(TAG, "Not removing non-existent package " + packageName); 17552 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17553 } 17554 17555 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17556 && uninstalledPs.versionCode != versionCode) { 17557 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17558 + uninstalledPs.versionCode + " != " + versionCode); 17559 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17560 } 17561 17562 // Static shared libs can be declared by any package, so let us not 17563 // allow removing a package if it provides a lib others depend on. 17564 PackageParser.Package pkg = mPackages.get(packageName); 17565 if (pkg != null && pkg.staticSharedLibName != null) { 17566 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17567 pkg.staticSharedLibVersion); 17568 if (libEntry != null) { 17569 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17570 libEntry.info, 0, userId); 17571 if (!ArrayUtils.isEmpty(libClientPackages)) { 17572 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17573 + " hosting lib " + libEntry.info.getName() + " version " 17574 + libEntry.info.getVersion() + " used by " + libClientPackages); 17575 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17576 } 17577 } 17578 } 17579 17580 allUsers = sUserManager.getUserIds(); 17581 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17582 } 17583 17584 final int freezeUser; 17585 if (isUpdatedSystemApp(uninstalledPs) 17586 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17587 // We're downgrading a system app, which will apply to all users, so 17588 // freeze them all during the downgrade 17589 freezeUser = UserHandle.USER_ALL; 17590 } else { 17591 freezeUser = removeUser; 17592 } 17593 17594 synchronized (mInstallLock) { 17595 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17596 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17597 deleteFlags, "deletePackageX")) { 17598 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17599 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17600 } 17601 synchronized (mPackages) { 17602 if (res) { 17603 mInstantAppRegistry.onPackageUninstalledLPw(uninstalledPs.pkg, 17604 info.removedUsers); 17605 updateSequenceNumberLP(packageName, info.removedUsers); 17606 } 17607 } 17608 } 17609 17610 if (res) { 17611 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17612 info.sendPackageRemovedBroadcasts(killApp); 17613 info.sendSystemPackageUpdatedBroadcasts(); 17614 info.sendSystemPackageAppearedBroadcasts(); 17615 } 17616 // Force a gc here. 17617 Runtime.getRuntime().gc(); 17618 // Delete the resources here after sending the broadcast to let 17619 // other processes clean up before deleting resources. 17620 if (info.args != null) { 17621 synchronized (mInstallLock) { 17622 info.args.doPostDeleteLI(true); 17623 } 17624 } 17625 17626 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17627 } 17628 17629 class PackageRemovedInfo { 17630 String removedPackage; 17631 int uid = -1; 17632 int removedAppId = -1; 17633 int[] origUsers; 17634 int[] removedUsers = null; 17635 SparseArray<Integer> installReasons; 17636 boolean isRemovedPackageSystemUpdate = false; 17637 boolean isUpdate; 17638 boolean dataRemoved; 17639 boolean removedForAllUsers; 17640 boolean isStaticSharedLib; 17641 // Clean up resources deleted packages. 17642 InstallArgs args = null; 17643 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17644 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17645 17646 void sendPackageRemovedBroadcasts(boolean killApp) { 17647 sendPackageRemovedBroadcastInternal(killApp); 17648 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17649 for (int i = 0; i < childCount; i++) { 17650 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17651 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17652 } 17653 } 17654 17655 void sendSystemPackageUpdatedBroadcasts() { 17656 if (isRemovedPackageSystemUpdate) { 17657 sendSystemPackageUpdatedBroadcastsInternal(); 17658 final int childCount = (removedChildPackages != null) 17659 ? removedChildPackages.size() : 0; 17660 for (int i = 0; i < childCount; i++) { 17661 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17662 if (childInfo.isRemovedPackageSystemUpdate) { 17663 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17664 } 17665 } 17666 } 17667 } 17668 17669 void sendSystemPackageAppearedBroadcasts() { 17670 final int packageCount = (appearedChildPackages != null) 17671 ? appearedChildPackages.size() : 0; 17672 for (int i = 0; i < packageCount; i++) { 17673 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17674 sendPackageAddedForNewUsers(installedInfo.name, true, 17675 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17676 } 17677 } 17678 17679 private void sendSystemPackageUpdatedBroadcastsInternal() { 17680 Bundle extras = new Bundle(2); 17681 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17682 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17683 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17684 extras, 0, null, null, null); 17685 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17686 extras, 0, null, null, null); 17687 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17688 null, 0, removedPackage, null, null); 17689 } 17690 17691 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17692 // Don't send static shared library removal broadcasts as these 17693 // libs are visible only the the apps that depend on them an one 17694 // cannot remove the library if it has a dependency. 17695 if (isStaticSharedLib) { 17696 return; 17697 } 17698 Bundle extras = new Bundle(2); 17699 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17700 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17701 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17702 if (isUpdate || isRemovedPackageSystemUpdate) { 17703 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17704 } 17705 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17706 if (removedPackage != null) { 17707 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17708 extras, 0, null, null, removedUsers); 17709 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17710 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17711 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17712 null, null, removedUsers); 17713 } 17714 } 17715 if (removedAppId >= 0) { 17716 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17717 removedUsers); 17718 } 17719 } 17720 } 17721 17722 /* 17723 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17724 * flag is not set, the data directory is removed as well. 17725 * make sure this flag is set for partially installed apps. If not its meaningless to 17726 * delete a partially installed application. 17727 */ 17728 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17729 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17730 String packageName = ps.name; 17731 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17732 // Retrieve object to delete permissions for shared user later on 17733 final PackageParser.Package deletedPkg; 17734 final PackageSetting deletedPs; 17735 // reader 17736 synchronized (mPackages) { 17737 deletedPkg = mPackages.get(packageName); 17738 deletedPs = mSettings.mPackages.get(packageName); 17739 if (outInfo != null) { 17740 outInfo.removedPackage = packageName; 17741 outInfo.isStaticSharedLib = deletedPkg != null 17742 && deletedPkg.staticSharedLibName != null; 17743 outInfo.removedUsers = deletedPs != null 17744 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17745 : null; 17746 } 17747 } 17748 17749 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17750 17751 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17752 final PackageParser.Package resolvedPkg; 17753 if (deletedPkg != null) { 17754 resolvedPkg = deletedPkg; 17755 } else { 17756 // We don't have a parsed package when it lives on an ejected 17757 // adopted storage device, so fake something together 17758 resolvedPkg = new PackageParser.Package(ps.name); 17759 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17760 } 17761 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17762 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17763 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17764 if (outInfo != null) { 17765 outInfo.dataRemoved = true; 17766 } 17767 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17768 } 17769 17770 int removedAppId = -1; 17771 17772 // writer 17773 synchronized (mPackages) { 17774 boolean installedStateChanged = false; 17775 if (deletedPs != null) { 17776 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17777 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17778 clearDefaultBrowserIfNeeded(packageName); 17779 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17780 removedAppId = mSettings.removePackageLPw(packageName); 17781 if (outInfo != null) { 17782 outInfo.removedAppId = removedAppId; 17783 } 17784 updatePermissionsLPw(deletedPs.name, null, 0); 17785 if (deletedPs.sharedUser != null) { 17786 // Remove permissions associated with package. Since runtime 17787 // permissions are per user we have to kill the removed package 17788 // or packages running under the shared user of the removed 17789 // package if revoking the permissions requested only by the removed 17790 // package is successful and this causes a change in gids. 17791 for (int userId : UserManagerService.getInstance().getUserIds()) { 17792 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17793 userId); 17794 if (userIdToKill == UserHandle.USER_ALL 17795 || userIdToKill >= UserHandle.USER_SYSTEM) { 17796 // If gids changed for this user, kill all affected packages. 17797 mHandler.post(new Runnable() { 17798 @Override 17799 public void run() { 17800 // This has to happen with no lock held. 17801 killApplication(deletedPs.name, deletedPs.appId, 17802 KILL_APP_REASON_GIDS_CHANGED); 17803 } 17804 }); 17805 break; 17806 } 17807 } 17808 } 17809 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17810 } 17811 // make sure to preserve per-user disabled state if this removal was just 17812 // a downgrade of a system app to the factory package 17813 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17814 if (DEBUG_REMOVE) { 17815 Slog.d(TAG, "Propagating install state across downgrade"); 17816 } 17817 for (int userId : allUserHandles) { 17818 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17819 if (DEBUG_REMOVE) { 17820 Slog.d(TAG, " user " + userId + " => " + installed); 17821 } 17822 if (installed != ps.getInstalled(userId)) { 17823 installedStateChanged = true; 17824 } 17825 ps.setInstalled(installed, userId); 17826 } 17827 } 17828 } 17829 // can downgrade to reader 17830 if (writeSettings) { 17831 // Save settings now 17832 mSettings.writeLPr(); 17833 } 17834 if (installedStateChanged) { 17835 mSettings.writeKernelMappingLPr(ps); 17836 } 17837 } 17838 if (removedAppId != -1) { 17839 // A user ID was deleted here. Go through all users and remove it 17840 // from KeyStore. 17841 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17842 } 17843 } 17844 17845 static boolean locationIsPrivileged(File path) { 17846 try { 17847 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17848 .getCanonicalPath(); 17849 return path.getCanonicalPath().startsWith(privilegedAppDir); 17850 } catch (IOException e) { 17851 Slog.e(TAG, "Unable to access code path " + path); 17852 } 17853 return false; 17854 } 17855 17856 /* 17857 * Tries to delete system package. 17858 */ 17859 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17860 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17861 boolean writeSettings) { 17862 if (deletedPs.parentPackageName != null) { 17863 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17864 return false; 17865 } 17866 17867 final boolean applyUserRestrictions 17868 = (allUserHandles != null) && (outInfo.origUsers != null); 17869 final PackageSetting disabledPs; 17870 // Confirm if the system package has been updated 17871 // An updated system app can be deleted. This will also have to restore 17872 // the system pkg from system partition 17873 // reader 17874 synchronized (mPackages) { 17875 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17876 } 17877 17878 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17879 + " disabledPs=" + disabledPs); 17880 17881 if (disabledPs == null) { 17882 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17883 return false; 17884 } else if (DEBUG_REMOVE) { 17885 Slog.d(TAG, "Deleting system pkg from data partition"); 17886 } 17887 17888 if (DEBUG_REMOVE) { 17889 if (applyUserRestrictions) { 17890 Slog.d(TAG, "Remembering install states:"); 17891 for (int userId : allUserHandles) { 17892 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17893 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17894 } 17895 } 17896 } 17897 17898 // Delete the updated package 17899 outInfo.isRemovedPackageSystemUpdate = true; 17900 if (outInfo.removedChildPackages != null) { 17901 final int childCount = (deletedPs.childPackageNames != null) 17902 ? deletedPs.childPackageNames.size() : 0; 17903 for (int i = 0; i < childCount; i++) { 17904 String childPackageName = deletedPs.childPackageNames.get(i); 17905 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17906 .contains(childPackageName)) { 17907 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17908 childPackageName); 17909 if (childInfo != null) { 17910 childInfo.isRemovedPackageSystemUpdate = true; 17911 } 17912 } 17913 } 17914 } 17915 17916 if (disabledPs.versionCode < deletedPs.versionCode) { 17917 // Delete data for downgrades 17918 flags &= ~PackageManager.DELETE_KEEP_DATA; 17919 } else { 17920 // Preserve data by setting flag 17921 flags |= PackageManager.DELETE_KEEP_DATA; 17922 } 17923 17924 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17925 outInfo, writeSettings, disabledPs.pkg); 17926 if (!ret) { 17927 return false; 17928 } 17929 17930 // writer 17931 synchronized (mPackages) { 17932 // Reinstate the old system package 17933 enableSystemPackageLPw(disabledPs.pkg); 17934 // Remove any native libraries from the upgraded package. 17935 removeNativeBinariesLI(deletedPs); 17936 } 17937 17938 // Install the system package 17939 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17940 int parseFlags = mDefParseFlags 17941 | PackageParser.PARSE_MUST_BE_APK 17942 | PackageParser.PARSE_IS_SYSTEM 17943 | PackageParser.PARSE_IS_SYSTEM_DIR; 17944 if (locationIsPrivileged(disabledPs.codePath)) { 17945 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17946 } 17947 17948 final PackageParser.Package newPkg; 17949 try { 17950 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17951 0 /* currentTime */, null); 17952 } catch (PackageManagerException e) { 17953 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17954 + e.getMessage()); 17955 return false; 17956 } 17957 17958 try { 17959 // update shared libraries for the newly re-installed system package 17960 updateSharedLibrariesLPr(newPkg, null); 17961 } catch (PackageManagerException e) { 17962 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17963 } 17964 17965 prepareAppDataAfterInstallLIF(newPkg); 17966 17967 // writer 17968 synchronized (mPackages) { 17969 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17970 17971 // Propagate the permissions state as we do not want to drop on the floor 17972 // runtime permissions. The update permissions method below will take 17973 // care of removing obsolete permissions and grant install permissions. 17974 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17975 updatePermissionsLPw(newPkg.packageName, newPkg, 17976 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17977 17978 if (applyUserRestrictions) { 17979 boolean installedStateChanged = false; 17980 if (DEBUG_REMOVE) { 17981 Slog.d(TAG, "Propagating install state across reinstall"); 17982 } 17983 for (int userId : allUserHandles) { 17984 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17985 if (DEBUG_REMOVE) { 17986 Slog.d(TAG, " user " + userId + " => " + installed); 17987 } 17988 if (installed != ps.getInstalled(userId)) { 17989 installedStateChanged = true; 17990 } 17991 ps.setInstalled(installed, userId); 17992 17993 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17994 } 17995 // Regardless of writeSettings we need to ensure that this restriction 17996 // state propagation is persisted 17997 mSettings.writeAllUsersPackageRestrictionsLPr(); 17998 if (installedStateChanged) { 17999 mSettings.writeKernelMappingLPr(ps); 18000 } 18001 } 18002 // can downgrade to reader here 18003 if (writeSettings) { 18004 mSettings.writeLPr(); 18005 } 18006 } 18007 return true; 18008 } 18009 18010 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18011 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18012 PackageRemovedInfo outInfo, boolean writeSettings, 18013 PackageParser.Package replacingPackage) { 18014 synchronized (mPackages) { 18015 if (outInfo != null) { 18016 outInfo.uid = ps.appId; 18017 } 18018 18019 if (outInfo != null && outInfo.removedChildPackages != null) { 18020 final int childCount = (ps.childPackageNames != null) 18021 ? ps.childPackageNames.size() : 0; 18022 for (int i = 0; i < childCount; i++) { 18023 String childPackageName = ps.childPackageNames.get(i); 18024 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18025 if (childPs == null) { 18026 return false; 18027 } 18028 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18029 childPackageName); 18030 if (childInfo != null) { 18031 childInfo.uid = childPs.appId; 18032 } 18033 } 18034 } 18035 } 18036 18037 // Delete package data from internal structures and also remove data if flag is set 18038 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18039 18040 // Delete the child packages data 18041 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18042 for (int i = 0; i < childCount; i++) { 18043 PackageSetting childPs; 18044 synchronized (mPackages) { 18045 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18046 } 18047 if (childPs != null) { 18048 PackageRemovedInfo childOutInfo = (outInfo != null 18049 && outInfo.removedChildPackages != null) 18050 ? outInfo.removedChildPackages.get(childPs.name) : null; 18051 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18052 && (replacingPackage != null 18053 && !replacingPackage.hasChildPackage(childPs.name)) 18054 ? flags & ~DELETE_KEEP_DATA : flags; 18055 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18056 deleteFlags, writeSettings); 18057 } 18058 } 18059 18060 // Delete application code and resources only for parent packages 18061 if (ps.parentPackageName == null) { 18062 if (deleteCodeAndResources && (outInfo != null)) { 18063 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18064 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18065 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18066 } 18067 } 18068 18069 return true; 18070 } 18071 18072 @Override 18073 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18074 int userId) { 18075 mContext.enforceCallingOrSelfPermission( 18076 android.Manifest.permission.DELETE_PACKAGES, null); 18077 synchronized (mPackages) { 18078 PackageSetting ps = mSettings.mPackages.get(packageName); 18079 if (ps == null) { 18080 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18081 return false; 18082 } 18083 // Cannot block uninstall of static shared libs as they are 18084 // considered a part of the using app (emulating static linking). 18085 // Also static libs are installed always on internal storage. 18086 PackageParser.Package pkg = mPackages.get(packageName); 18087 if (pkg != null && pkg.staticSharedLibName != null) { 18088 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18089 + " providing static shared library: " + pkg.staticSharedLibName); 18090 return false; 18091 } 18092 if (!ps.getInstalled(userId)) { 18093 // Can't block uninstall for an app that is not installed or enabled. 18094 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18095 return false; 18096 } 18097 ps.setBlockUninstall(blockUninstall, userId); 18098 mSettings.writePackageRestrictionsLPr(userId); 18099 } 18100 return true; 18101 } 18102 18103 @Override 18104 public boolean getBlockUninstallForUser(String packageName, int userId) { 18105 synchronized (mPackages) { 18106 PackageSetting ps = mSettings.mPackages.get(packageName); 18107 if (ps == null) { 18108 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18109 return false; 18110 } 18111 return ps.getBlockUninstall(userId); 18112 } 18113 } 18114 18115 @Override 18116 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18117 int callingUid = Binder.getCallingUid(); 18118 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18119 throw new SecurityException( 18120 "setRequiredForSystemUser can only be run by the system or root"); 18121 } 18122 synchronized (mPackages) { 18123 PackageSetting ps = mSettings.mPackages.get(packageName); 18124 if (ps == null) { 18125 Log.w(TAG, "Package doesn't exist: " + packageName); 18126 return false; 18127 } 18128 if (systemUserApp) { 18129 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18130 } else { 18131 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18132 } 18133 mSettings.writeLPr(); 18134 } 18135 return true; 18136 } 18137 18138 /* 18139 * This method handles package deletion in general 18140 */ 18141 private boolean deletePackageLIF(String packageName, UserHandle user, 18142 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18143 PackageRemovedInfo outInfo, boolean writeSettings, 18144 PackageParser.Package replacingPackage) { 18145 if (packageName == null) { 18146 Slog.w(TAG, "Attempt to delete null packageName."); 18147 return false; 18148 } 18149 18150 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18151 18152 PackageSetting ps; 18153 synchronized (mPackages) { 18154 ps = mSettings.mPackages.get(packageName); 18155 if (ps == null) { 18156 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18157 return false; 18158 } 18159 18160 if (ps.parentPackageName != null && (!isSystemApp(ps) 18161 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18162 if (DEBUG_REMOVE) { 18163 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18164 + ((user == null) ? UserHandle.USER_ALL : user)); 18165 } 18166 final int removedUserId = (user != null) ? user.getIdentifier() 18167 : UserHandle.USER_ALL; 18168 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18169 return false; 18170 } 18171 markPackageUninstalledForUserLPw(ps, user); 18172 scheduleWritePackageRestrictionsLocked(user); 18173 return true; 18174 } 18175 } 18176 18177 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18178 && user.getIdentifier() != UserHandle.USER_ALL)) { 18179 // The caller is asking that the package only be deleted for a single 18180 // user. To do this, we just mark its uninstalled state and delete 18181 // its data. If this is a system app, we only allow this to happen if 18182 // they have set the special DELETE_SYSTEM_APP which requests different 18183 // semantics than normal for uninstalling system apps. 18184 markPackageUninstalledForUserLPw(ps, user); 18185 18186 if (!isSystemApp(ps)) { 18187 // Do not uninstall the APK if an app should be cached 18188 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18189 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18190 // Other user still have this package installed, so all 18191 // we need to do is clear this user's data and save that 18192 // it is uninstalled. 18193 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18194 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18195 return false; 18196 } 18197 scheduleWritePackageRestrictionsLocked(user); 18198 return true; 18199 } else { 18200 // We need to set it back to 'installed' so the uninstall 18201 // broadcasts will be sent correctly. 18202 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18203 ps.setInstalled(true, user.getIdentifier()); 18204 mSettings.writeKernelMappingLPr(ps); 18205 } 18206 } else { 18207 // This is a system app, so we assume that the 18208 // other users still have this package installed, so all 18209 // we need to do is clear this user's data and save that 18210 // it is uninstalled. 18211 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18212 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18213 return false; 18214 } 18215 scheduleWritePackageRestrictionsLocked(user); 18216 return true; 18217 } 18218 } 18219 18220 // If we are deleting a composite package for all users, keep track 18221 // of result for each child. 18222 if (ps.childPackageNames != null && outInfo != null) { 18223 synchronized (mPackages) { 18224 final int childCount = ps.childPackageNames.size(); 18225 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18226 for (int i = 0; i < childCount; i++) { 18227 String childPackageName = ps.childPackageNames.get(i); 18228 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18229 childInfo.removedPackage = childPackageName; 18230 outInfo.removedChildPackages.put(childPackageName, childInfo); 18231 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18232 if (childPs != null) { 18233 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18234 } 18235 } 18236 } 18237 } 18238 18239 boolean ret = false; 18240 if (isSystemApp(ps)) { 18241 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18242 // When an updated system application is deleted we delete the existing resources 18243 // as well and fall back to existing code in system partition 18244 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18245 } else { 18246 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18247 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18248 outInfo, writeSettings, replacingPackage); 18249 } 18250 18251 // Take a note whether we deleted the package for all users 18252 if (outInfo != null) { 18253 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18254 if (outInfo.removedChildPackages != null) { 18255 synchronized (mPackages) { 18256 final int childCount = outInfo.removedChildPackages.size(); 18257 for (int i = 0; i < childCount; i++) { 18258 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18259 if (childInfo != null) { 18260 childInfo.removedForAllUsers = mPackages.get( 18261 childInfo.removedPackage) == null; 18262 } 18263 } 18264 } 18265 } 18266 // If we uninstalled an update to a system app there may be some 18267 // child packages that appeared as they are declared in the system 18268 // app but were not declared in the update. 18269 if (isSystemApp(ps)) { 18270 synchronized (mPackages) { 18271 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18272 final int childCount = (updatedPs.childPackageNames != null) 18273 ? updatedPs.childPackageNames.size() : 0; 18274 for (int i = 0; i < childCount; i++) { 18275 String childPackageName = updatedPs.childPackageNames.get(i); 18276 if (outInfo.removedChildPackages == null 18277 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18278 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18279 if (childPs == null) { 18280 continue; 18281 } 18282 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18283 installRes.name = childPackageName; 18284 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18285 installRes.pkg = mPackages.get(childPackageName); 18286 installRes.uid = childPs.pkg.applicationInfo.uid; 18287 if (outInfo.appearedChildPackages == null) { 18288 outInfo.appearedChildPackages = new ArrayMap<>(); 18289 } 18290 outInfo.appearedChildPackages.put(childPackageName, installRes); 18291 } 18292 } 18293 } 18294 } 18295 } 18296 18297 return ret; 18298 } 18299 18300 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18301 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18302 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18303 for (int nextUserId : userIds) { 18304 if (DEBUG_REMOVE) { 18305 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18306 } 18307 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18308 false /*installed*/, 18309 true /*stopped*/, 18310 true /*notLaunched*/, 18311 false /*hidden*/, 18312 false /*suspended*/, 18313 false /*instantApp*/, 18314 null /*lastDisableAppCaller*/, 18315 null /*enabledComponents*/, 18316 null /*disabledComponents*/, 18317 false /*blockUninstall*/, 18318 ps.readUserState(nextUserId).domainVerificationStatus, 18319 0, PackageManager.INSTALL_REASON_UNKNOWN); 18320 } 18321 mSettings.writeKernelMappingLPr(ps); 18322 } 18323 18324 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18325 PackageRemovedInfo outInfo) { 18326 final PackageParser.Package pkg; 18327 synchronized (mPackages) { 18328 pkg = mPackages.get(ps.name); 18329 } 18330 18331 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18332 : new int[] {userId}; 18333 for (int nextUserId : userIds) { 18334 if (DEBUG_REMOVE) { 18335 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18336 + nextUserId); 18337 } 18338 18339 destroyAppDataLIF(pkg, userId, 18340 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18341 destroyAppProfilesLIF(pkg, userId); 18342 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18343 schedulePackageCleaning(ps.name, nextUserId, false); 18344 synchronized (mPackages) { 18345 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18346 scheduleWritePackageRestrictionsLocked(nextUserId); 18347 } 18348 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18349 } 18350 } 18351 18352 if (outInfo != null) { 18353 outInfo.removedPackage = ps.name; 18354 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18355 outInfo.removedAppId = ps.appId; 18356 outInfo.removedUsers = userIds; 18357 } 18358 18359 return true; 18360 } 18361 18362 private final class ClearStorageConnection implements ServiceConnection { 18363 IMediaContainerService mContainerService; 18364 18365 @Override 18366 public void onServiceConnected(ComponentName name, IBinder service) { 18367 synchronized (this) { 18368 mContainerService = IMediaContainerService.Stub 18369 .asInterface(Binder.allowBlocking(service)); 18370 notifyAll(); 18371 } 18372 } 18373 18374 @Override 18375 public void onServiceDisconnected(ComponentName name) { 18376 } 18377 } 18378 18379 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18380 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18381 18382 final boolean mounted; 18383 if (Environment.isExternalStorageEmulated()) { 18384 mounted = true; 18385 } else { 18386 final String status = Environment.getExternalStorageState(); 18387 18388 mounted = status.equals(Environment.MEDIA_MOUNTED) 18389 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18390 } 18391 18392 if (!mounted) { 18393 return; 18394 } 18395 18396 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18397 int[] users; 18398 if (userId == UserHandle.USER_ALL) { 18399 users = sUserManager.getUserIds(); 18400 } else { 18401 users = new int[] { userId }; 18402 } 18403 final ClearStorageConnection conn = new ClearStorageConnection(); 18404 if (mContext.bindServiceAsUser( 18405 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18406 try { 18407 for (int curUser : users) { 18408 long timeout = SystemClock.uptimeMillis() + 5000; 18409 synchronized (conn) { 18410 long now; 18411 while (conn.mContainerService == null && 18412 (now = SystemClock.uptimeMillis()) < timeout) { 18413 try { 18414 conn.wait(timeout - now); 18415 } catch (InterruptedException e) { 18416 } 18417 } 18418 } 18419 if (conn.mContainerService == null) { 18420 return; 18421 } 18422 18423 final UserEnvironment userEnv = new UserEnvironment(curUser); 18424 clearDirectory(conn.mContainerService, 18425 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18426 if (allData) { 18427 clearDirectory(conn.mContainerService, 18428 userEnv.buildExternalStorageAppDataDirs(packageName)); 18429 clearDirectory(conn.mContainerService, 18430 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18431 } 18432 } 18433 } finally { 18434 mContext.unbindService(conn); 18435 } 18436 } 18437 } 18438 18439 @Override 18440 public void clearApplicationProfileData(String packageName) { 18441 enforceSystemOrRoot("Only the system can clear all profile data"); 18442 18443 final PackageParser.Package pkg; 18444 synchronized (mPackages) { 18445 pkg = mPackages.get(packageName); 18446 } 18447 18448 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18449 synchronized (mInstallLock) { 18450 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18451 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 18452 true /* removeBaseMarker */); 18453 } 18454 } 18455 } 18456 18457 @Override 18458 public void clearApplicationUserData(final String packageName, 18459 final IPackageDataObserver observer, final int userId) { 18460 mContext.enforceCallingOrSelfPermission( 18461 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18462 18463 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18464 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18465 18466 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18467 throw new SecurityException("Cannot clear data for a protected package: " 18468 + packageName); 18469 } 18470 // Queue up an async operation since the package deletion may take a little while. 18471 mHandler.post(new Runnable() { 18472 public void run() { 18473 mHandler.removeCallbacks(this); 18474 final boolean succeeded; 18475 try (PackageFreezer freezer = freezePackage(packageName, 18476 "clearApplicationUserData")) { 18477 synchronized (mInstallLock) { 18478 succeeded = clearApplicationUserDataLIF(packageName, userId); 18479 } 18480 clearExternalStorageDataSync(packageName, userId, true); 18481 synchronized (mPackages) { 18482 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18483 packageName, userId); 18484 } 18485 } 18486 if (succeeded) { 18487 // invoke DeviceStorageMonitor's update method to clear any notifications 18488 DeviceStorageMonitorInternal dsm = LocalServices 18489 .getService(DeviceStorageMonitorInternal.class); 18490 if (dsm != null) { 18491 dsm.checkMemory(); 18492 } 18493 } 18494 if(observer != null) { 18495 try { 18496 observer.onRemoveCompleted(packageName, succeeded); 18497 } catch (RemoteException e) { 18498 Log.i(TAG, "Observer no longer exists."); 18499 } 18500 } //end if observer 18501 } //end run 18502 }); 18503 } 18504 18505 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18506 if (packageName == null) { 18507 Slog.w(TAG, "Attempt to delete null packageName."); 18508 return false; 18509 } 18510 18511 // Try finding details about the requested package 18512 PackageParser.Package pkg; 18513 synchronized (mPackages) { 18514 pkg = mPackages.get(packageName); 18515 if (pkg == null) { 18516 final PackageSetting ps = mSettings.mPackages.get(packageName); 18517 if (ps != null) { 18518 pkg = ps.pkg; 18519 } 18520 } 18521 18522 if (pkg == null) { 18523 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18524 return false; 18525 } 18526 18527 PackageSetting ps = (PackageSetting) pkg.mExtras; 18528 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18529 } 18530 18531 clearAppDataLIF(pkg, userId, 18532 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18533 18534 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18535 removeKeystoreDataIfNeeded(userId, appId); 18536 18537 UserManagerInternal umInternal = getUserManagerInternal(); 18538 final int flags; 18539 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18540 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18541 } else if (umInternal.isUserRunning(userId)) { 18542 flags = StorageManager.FLAG_STORAGE_DE; 18543 } else { 18544 flags = 0; 18545 } 18546 prepareAppDataContentsLIF(pkg, userId, flags); 18547 18548 return true; 18549 } 18550 18551 /** 18552 * Reverts user permission state changes (permissions and flags) in 18553 * all packages for a given user. 18554 * 18555 * @param userId The device user for which to do a reset. 18556 */ 18557 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18558 final int packageCount = mPackages.size(); 18559 for (int i = 0; i < packageCount; i++) { 18560 PackageParser.Package pkg = mPackages.valueAt(i); 18561 PackageSetting ps = (PackageSetting) pkg.mExtras; 18562 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18563 } 18564 } 18565 18566 private void resetNetworkPolicies(int userId) { 18567 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18568 } 18569 18570 /** 18571 * Reverts user permission state changes (permissions and flags). 18572 * 18573 * @param ps The package for which to reset. 18574 * @param userId The device user for which to do a reset. 18575 */ 18576 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18577 final PackageSetting ps, final int userId) { 18578 if (ps.pkg == null) { 18579 return; 18580 } 18581 18582 // These are flags that can change base on user actions. 18583 final int userSettableMask = FLAG_PERMISSION_USER_SET 18584 | FLAG_PERMISSION_USER_FIXED 18585 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18586 | FLAG_PERMISSION_REVIEW_REQUIRED; 18587 18588 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18589 | FLAG_PERMISSION_POLICY_FIXED; 18590 18591 boolean writeInstallPermissions = false; 18592 boolean writeRuntimePermissions = false; 18593 18594 final int permissionCount = ps.pkg.requestedPermissions.size(); 18595 for (int i = 0; i < permissionCount; i++) { 18596 String permission = ps.pkg.requestedPermissions.get(i); 18597 18598 BasePermission bp = mSettings.mPermissions.get(permission); 18599 if (bp == null) { 18600 continue; 18601 } 18602 18603 // If shared user we just reset the state to which only this app contributed. 18604 if (ps.sharedUser != null) { 18605 boolean used = false; 18606 final int packageCount = ps.sharedUser.packages.size(); 18607 for (int j = 0; j < packageCount; j++) { 18608 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18609 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18610 && pkg.pkg.requestedPermissions.contains(permission)) { 18611 used = true; 18612 break; 18613 } 18614 } 18615 if (used) { 18616 continue; 18617 } 18618 } 18619 18620 PermissionsState permissionsState = ps.getPermissionsState(); 18621 18622 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18623 18624 // Always clear the user settable flags. 18625 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18626 bp.name) != null; 18627 // If permission review is enabled and this is a legacy app, mark the 18628 // permission as requiring a review as this is the initial state. 18629 int flags = 0; 18630 if (mPermissionReviewRequired 18631 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18632 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18633 } 18634 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18635 if (hasInstallState) { 18636 writeInstallPermissions = true; 18637 } else { 18638 writeRuntimePermissions = true; 18639 } 18640 } 18641 18642 // Below is only runtime permission handling. 18643 if (!bp.isRuntime()) { 18644 continue; 18645 } 18646 18647 // Never clobber system or policy. 18648 if ((oldFlags & policyOrSystemFlags) != 0) { 18649 continue; 18650 } 18651 18652 // If this permission was granted by default, make sure it is. 18653 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18654 if (permissionsState.grantRuntimePermission(bp, userId) 18655 != PERMISSION_OPERATION_FAILURE) { 18656 writeRuntimePermissions = true; 18657 } 18658 // If permission review is enabled the permissions for a legacy apps 18659 // are represented as constantly granted runtime ones, so don't revoke. 18660 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18661 // Otherwise, reset the permission. 18662 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18663 switch (revokeResult) { 18664 case PERMISSION_OPERATION_SUCCESS: 18665 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18666 writeRuntimePermissions = true; 18667 final int appId = ps.appId; 18668 mHandler.post(new Runnable() { 18669 @Override 18670 public void run() { 18671 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18672 } 18673 }); 18674 } break; 18675 } 18676 } 18677 } 18678 18679 // Synchronously write as we are taking permissions away. 18680 if (writeRuntimePermissions) { 18681 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18682 } 18683 18684 // Synchronously write as we are taking permissions away. 18685 if (writeInstallPermissions) { 18686 mSettings.writeLPr(); 18687 } 18688 } 18689 18690 /** 18691 * Remove entries from the keystore daemon. Will only remove it if the 18692 * {@code appId} is valid. 18693 */ 18694 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18695 if (appId < 0) { 18696 return; 18697 } 18698 18699 final KeyStore keyStore = KeyStore.getInstance(); 18700 if (keyStore != null) { 18701 if (userId == UserHandle.USER_ALL) { 18702 for (final int individual : sUserManager.getUserIds()) { 18703 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18704 } 18705 } else { 18706 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18707 } 18708 } else { 18709 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18710 } 18711 } 18712 18713 @Override 18714 public void deleteApplicationCacheFiles(final String packageName, 18715 final IPackageDataObserver observer) { 18716 final int userId = UserHandle.getCallingUserId(); 18717 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18718 } 18719 18720 @Override 18721 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18722 final IPackageDataObserver observer) { 18723 mContext.enforceCallingOrSelfPermission( 18724 android.Manifest.permission.DELETE_CACHE_FILES, null); 18725 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18726 /* requireFullPermission= */ true, /* checkShell= */ false, 18727 "delete application cache files"); 18728 18729 final PackageParser.Package pkg; 18730 synchronized (mPackages) { 18731 pkg = mPackages.get(packageName); 18732 } 18733 18734 // Queue up an async operation since the package deletion may take a little while. 18735 mHandler.post(new Runnable() { 18736 public void run() { 18737 synchronized (mInstallLock) { 18738 final int flags = StorageManager.FLAG_STORAGE_DE 18739 | StorageManager.FLAG_STORAGE_CE; 18740 // We're only clearing cache files, so we don't care if the 18741 // app is unfrozen and still able to run 18742 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18743 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18744 } 18745 clearExternalStorageDataSync(packageName, userId, false); 18746 if (observer != null) { 18747 try { 18748 observer.onRemoveCompleted(packageName, true); 18749 } catch (RemoteException e) { 18750 Log.i(TAG, "Observer no longer exists."); 18751 } 18752 } 18753 } 18754 }); 18755 } 18756 18757 @Override 18758 public void getPackageSizeInfo(final String packageName, int userHandle, 18759 final IPackageStatsObserver observer) { 18760 Slog.w(TAG, "Shame on you for calling a hidden API. Shame!"); 18761 try { 18762 observer.onGetStatsCompleted(null, false); 18763 } catch (Throwable ignored) { 18764 } 18765 } 18766 18767 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18768 final PackageSetting ps; 18769 synchronized (mPackages) { 18770 ps = mSettings.mPackages.get(packageName); 18771 if (ps == null) { 18772 Slog.w(TAG, "Failed to find settings for " + packageName); 18773 return false; 18774 } 18775 } 18776 18777 final String[] packageNames = { packageName }; 18778 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18779 final String[] codePaths = { ps.codePathString }; 18780 18781 try { 18782 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18783 ps.appId, ceDataInodes, codePaths, stats); 18784 18785 // For now, ignore code size of packages on system partition 18786 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18787 stats.codeSize = 0; 18788 } 18789 18790 // External clients expect these to be tracked separately 18791 stats.dataSize -= stats.cacheSize; 18792 18793 } catch (InstallerException e) { 18794 Slog.w(TAG, String.valueOf(e)); 18795 return false; 18796 } 18797 18798 return true; 18799 } 18800 18801 private int getUidTargetSdkVersionLockedLPr(int uid) { 18802 Object obj = mSettings.getUserIdLPr(uid); 18803 if (obj instanceof SharedUserSetting) { 18804 final SharedUserSetting sus = (SharedUserSetting) obj; 18805 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18806 final Iterator<PackageSetting> it = sus.packages.iterator(); 18807 while (it.hasNext()) { 18808 final PackageSetting ps = it.next(); 18809 if (ps.pkg != null) { 18810 int v = ps.pkg.applicationInfo.targetSdkVersion; 18811 if (v < vers) vers = v; 18812 } 18813 } 18814 return vers; 18815 } else if (obj instanceof PackageSetting) { 18816 final PackageSetting ps = (PackageSetting) obj; 18817 if (ps.pkg != null) { 18818 return ps.pkg.applicationInfo.targetSdkVersion; 18819 } 18820 } 18821 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18822 } 18823 18824 @Override 18825 public void addPreferredActivity(IntentFilter filter, int match, 18826 ComponentName[] set, ComponentName activity, int userId) { 18827 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18828 "Adding preferred"); 18829 } 18830 18831 private void addPreferredActivityInternal(IntentFilter filter, int match, 18832 ComponentName[] set, ComponentName activity, boolean always, int userId, 18833 String opname) { 18834 // writer 18835 int callingUid = Binder.getCallingUid(); 18836 enforceCrossUserPermission(callingUid, userId, 18837 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18838 if (filter.countActions() == 0) { 18839 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18840 return; 18841 } 18842 synchronized (mPackages) { 18843 if (mContext.checkCallingOrSelfPermission( 18844 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18845 != PackageManager.PERMISSION_GRANTED) { 18846 if (getUidTargetSdkVersionLockedLPr(callingUid) 18847 < Build.VERSION_CODES.FROYO) { 18848 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18849 + callingUid); 18850 return; 18851 } 18852 mContext.enforceCallingOrSelfPermission( 18853 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18854 } 18855 18856 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18857 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18858 + userId + ":"); 18859 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18860 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18861 scheduleWritePackageRestrictionsLocked(userId); 18862 postPreferredActivityChangedBroadcast(userId); 18863 } 18864 } 18865 18866 private void postPreferredActivityChangedBroadcast(int userId) { 18867 mHandler.post(() -> { 18868 final IActivityManager am = ActivityManager.getService(); 18869 if (am == null) { 18870 return; 18871 } 18872 18873 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18874 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18875 try { 18876 am.broadcastIntent(null, intent, null, null, 18877 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18878 null, false, false, userId); 18879 } catch (RemoteException e) { 18880 } 18881 }); 18882 } 18883 18884 @Override 18885 public void replacePreferredActivity(IntentFilter filter, int match, 18886 ComponentName[] set, ComponentName activity, int userId) { 18887 if (filter.countActions() != 1) { 18888 throw new IllegalArgumentException( 18889 "replacePreferredActivity expects filter to have only 1 action."); 18890 } 18891 if (filter.countDataAuthorities() != 0 18892 || filter.countDataPaths() != 0 18893 || filter.countDataSchemes() > 1 18894 || filter.countDataTypes() != 0) { 18895 throw new IllegalArgumentException( 18896 "replacePreferredActivity expects filter to have no data authorities, " + 18897 "paths, or types; and at most one scheme."); 18898 } 18899 18900 final int callingUid = Binder.getCallingUid(); 18901 enforceCrossUserPermission(callingUid, userId, 18902 true /* requireFullPermission */, false /* checkShell */, 18903 "replace preferred activity"); 18904 synchronized (mPackages) { 18905 if (mContext.checkCallingOrSelfPermission( 18906 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18907 != PackageManager.PERMISSION_GRANTED) { 18908 if (getUidTargetSdkVersionLockedLPr(callingUid) 18909 < Build.VERSION_CODES.FROYO) { 18910 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18911 + Binder.getCallingUid()); 18912 return; 18913 } 18914 mContext.enforceCallingOrSelfPermission( 18915 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18916 } 18917 18918 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18919 if (pir != null) { 18920 // Get all of the existing entries that exactly match this filter. 18921 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18922 if (existing != null && existing.size() == 1) { 18923 PreferredActivity cur = existing.get(0); 18924 if (DEBUG_PREFERRED) { 18925 Slog.i(TAG, "Checking replace of preferred:"); 18926 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18927 if (!cur.mPref.mAlways) { 18928 Slog.i(TAG, " -- CUR; not mAlways!"); 18929 } else { 18930 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18931 Slog.i(TAG, " -- CUR: mSet=" 18932 + Arrays.toString(cur.mPref.mSetComponents)); 18933 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18934 Slog.i(TAG, " -- NEW: mMatch=" 18935 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18936 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18937 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18938 } 18939 } 18940 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18941 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18942 && cur.mPref.sameSet(set)) { 18943 // Setting the preferred activity to what it happens to be already 18944 if (DEBUG_PREFERRED) { 18945 Slog.i(TAG, "Replacing with same preferred activity " 18946 + cur.mPref.mShortComponent + " for user " 18947 + userId + ":"); 18948 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18949 } 18950 return; 18951 } 18952 } 18953 18954 if (existing != null) { 18955 if (DEBUG_PREFERRED) { 18956 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18957 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18958 } 18959 for (int i = 0; i < existing.size(); i++) { 18960 PreferredActivity pa = existing.get(i); 18961 if (DEBUG_PREFERRED) { 18962 Slog.i(TAG, "Removing existing preferred activity " 18963 + pa.mPref.mComponent + ":"); 18964 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18965 } 18966 pir.removeFilter(pa); 18967 } 18968 } 18969 } 18970 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18971 "Replacing preferred"); 18972 } 18973 } 18974 18975 @Override 18976 public void clearPackagePreferredActivities(String packageName) { 18977 final int uid = Binder.getCallingUid(); 18978 // writer 18979 synchronized (mPackages) { 18980 PackageParser.Package pkg = mPackages.get(packageName); 18981 if (pkg == null || pkg.applicationInfo.uid != uid) { 18982 if (mContext.checkCallingOrSelfPermission( 18983 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18984 != PackageManager.PERMISSION_GRANTED) { 18985 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18986 < Build.VERSION_CODES.FROYO) { 18987 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18988 + Binder.getCallingUid()); 18989 return; 18990 } 18991 mContext.enforceCallingOrSelfPermission( 18992 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18993 } 18994 } 18995 18996 int user = UserHandle.getCallingUserId(); 18997 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18998 scheduleWritePackageRestrictionsLocked(user); 18999 } 19000 } 19001 } 19002 19003 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19004 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19005 ArrayList<PreferredActivity> removed = null; 19006 boolean changed = false; 19007 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19008 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19009 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19010 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19011 continue; 19012 } 19013 Iterator<PreferredActivity> it = pir.filterIterator(); 19014 while (it.hasNext()) { 19015 PreferredActivity pa = it.next(); 19016 // Mark entry for removal only if it matches the package name 19017 // and the entry is of type "always". 19018 if (packageName == null || 19019 (pa.mPref.mComponent.getPackageName().equals(packageName) 19020 && pa.mPref.mAlways)) { 19021 if (removed == null) { 19022 removed = new ArrayList<PreferredActivity>(); 19023 } 19024 removed.add(pa); 19025 } 19026 } 19027 if (removed != null) { 19028 for (int j=0; j<removed.size(); j++) { 19029 PreferredActivity pa = removed.get(j); 19030 pir.removeFilter(pa); 19031 } 19032 changed = true; 19033 } 19034 } 19035 if (changed) { 19036 postPreferredActivityChangedBroadcast(userId); 19037 } 19038 return changed; 19039 } 19040 19041 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19042 private void clearIntentFilterVerificationsLPw(int userId) { 19043 final int packageCount = mPackages.size(); 19044 for (int i = 0; i < packageCount; i++) { 19045 PackageParser.Package pkg = mPackages.valueAt(i); 19046 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19047 } 19048 } 19049 19050 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19051 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19052 if (userId == UserHandle.USER_ALL) { 19053 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19054 sUserManager.getUserIds())) { 19055 for (int oneUserId : sUserManager.getUserIds()) { 19056 scheduleWritePackageRestrictionsLocked(oneUserId); 19057 } 19058 } 19059 } else { 19060 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19061 scheduleWritePackageRestrictionsLocked(userId); 19062 } 19063 } 19064 } 19065 19066 void clearDefaultBrowserIfNeeded(String packageName) { 19067 for (int oneUserId : sUserManager.getUserIds()) { 19068 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19069 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19070 if (packageName.equals(defaultBrowserPackageName)) { 19071 setDefaultBrowserPackageName(null, oneUserId); 19072 } 19073 } 19074 } 19075 19076 @Override 19077 public void resetApplicationPreferences(int userId) { 19078 mContext.enforceCallingOrSelfPermission( 19079 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19080 final long identity = Binder.clearCallingIdentity(); 19081 // writer 19082 try { 19083 synchronized (mPackages) { 19084 clearPackagePreferredActivitiesLPw(null, userId); 19085 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19086 // TODO: We have to reset the default SMS and Phone. This requires 19087 // significant refactoring to keep all default apps in the package 19088 // manager (cleaner but more work) or have the services provide 19089 // callbacks to the package manager to request a default app reset. 19090 applyFactoryDefaultBrowserLPw(userId); 19091 clearIntentFilterVerificationsLPw(userId); 19092 primeDomainVerificationsLPw(userId); 19093 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19094 scheduleWritePackageRestrictionsLocked(userId); 19095 } 19096 resetNetworkPolicies(userId); 19097 } finally { 19098 Binder.restoreCallingIdentity(identity); 19099 } 19100 } 19101 19102 @Override 19103 public int getPreferredActivities(List<IntentFilter> outFilters, 19104 List<ComponentName> outActivities, String packageName) { 19105 19106 int num = 0; 19107 final int userId = UserHandle.getCallingUserId(); 19108 // reader 19109 synchronized (mPackages) { 19110 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19111 if (pir != null) { 19112 final Iterator<PreferredActivity> it = pir.filterIterator(); 19113 while (it.hasNext()) { 19114 final PreferredActivity pa = it.next(); 19115 if (packageName == null 19116 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19117 && pa.mPref.mAlways)) { 19118 if (outFilters != null) { 19119 outFilters.add(new IntentFilter(pa)); 19120 } 19121 if (outActivities != null) { 19122 outActivities.add(pa.mPref.mComponent); 19123 } 19124 } 19125 } 19126 } 19127 } 19128 19129 return num; 19130 } 19131 19132 @Override 19133 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19134 int userId) { 19135 int callingUid = Binder.getCallingUid(); 19136 if (callingUid != Process.SYSTEM_UID) { 19137 throw new SecurityException( 19138 "addPersistentPreferredActivity can only be run by the system"); 19139 } 19140 if (filter.countActions() == 0) { 19141 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19142 return; 19143 } 19144 synchronized (mPackages) { 19145 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19146 ":"); 19147 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19148 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19149 new PersistentPreferredActivity(filter, activity)); 19150 scheduleWritePackageRestrictionsLocked(userId); 19151 postPreferredActivityChangedBroadcast(userId); 19152 } 19153 } 19154 19155 @Override 19156 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19157 int callingUid = Binder.getCallingUid(); 19158 if (callingUid != Process.SYSTEM_UID) { 19159 throw new SecurityException( 19160 "clearPackagePersistentPreferredActivities can only be run by the system"); 19161 } 19162 ArrayList<PersistentPreferredActivity> removed = null; 19163 boolean changed = false; 19164 synchronized (mPackages) { 19165 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19166 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19167 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19168 .valueAt(i); 19169 if (userId != thisUserId) { 19170 continue; 19171 } 19172 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19173 while (it.hasNext()) { 19174 PersistentPreferredActivity ppa = it.next(); 19175 // Mark entry for removal only if it matches the package name. 19176 if (ppa.mComponent.getPackageName().equals(packageName)) { 19177 if (removed == null) { 19178 removed = new ArrayList<PersistentPreferredActivity>(); 19179 } 19180 removed.add(ppa); 19181 } 19182 } 19183 if (removed != null) { 19184 for (int j=0; j<removed.size(); j++) { 19185 PersistentPreferredActivity ppa = removed.get(j); 19186 ppir.removeFilter(ppa); 19187 } 19188 changed = true; 19189 } 19190 } 19191 19192 if (changed) { 19193 scheduleWritePackageRestrictionsLocked(userId); 19194 postPreferredActivityChangedBroadcast(userId); 19195 } 19196 } 19197 } 19198 19199 /** 19200 * Common machinery for picking apart a restored XML blob and passing 19201 * it to a caller-supplied functor to be applied to the running system. 19202 */ 19203 private void restoreFromXml(XmlPullParser parser, int userId, 19204 String expectedStartTag, BlobXmlRestorer functor) 19205 throws IOException, XmlPullParserException { 19206 int type; 19207 while ((type = parser.next()) != XmlPullParser.START_TAG 19208 && type != XmlPullParser.END_DOCUMENT) { 19209 } 19210 if (type != XmlPullParser.START_TAG) { 19211 // oops didn't find a start tag?! 19212 if (DEBUG_BACKUP) { 19213 Slog.e(TAG, "Didn't find start tag during restore"); 19214 } 19215 return; 19216 } 19217Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19218 // this is supposed to be TAG_PREFERRED_BACKUP 19219 if (!expectedStartTag.equals(parser.getName())) { 19220 if (DEBUG_BACKUP) { 19221 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19222 } 19223 return; 19224 } 19225 19226 // skip interfering stuff, then we're aligned with the backing implementation 19227 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19228Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19229 functor.apply(parser, userId); 19230 } 19231 19232 private interface BlobXmlRestorer { 19233 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19234 } 19235 19236 /** 19237 * Non-Binder method, support for the backup/restore mechanism: write the 19238 * full set of preferred activities in its canonical XML format. Returns the 19239 * XML output as a byte array, or null if there is none. 19240 */ 19241 @Override 19242 public byte[] getPreferredActivityBackup(int userId) { 19243 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19244 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19245 } 19246 19247 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19248 try { 19249 final XmlSerializer serializer = new FastXmlSerializer(); 19250 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19251 serializer.startDocument(null, true); 19252 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19253 19254 synchronized (mPackages) { 19255 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19256 } 19257 19258 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19259 serializer.endDocument(); 19260 serializer.flush(); 19261 } catch (Exception e) { 19262 if (DEBUG_BACKUP) { 19263 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19264 } 19265 return null; 19266 } 19267 19268 return dataStream.toByteArray(); 19269 } 19270 19271 @Override 19272 public void restorePreferredActivities(byte[] backup, int userId) { 19273 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19274 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19275 } 19276 19277 try { 19278 final XmlPullParser parser = Xml.newPullParser(); 19279 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19280 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19281 new BlobXmlRestorer() { 19282 @Override 19283 public void apply(XmlPullParser parser, int userId) 19284 throws XmlPullParserException, IOException { 19285 synchronized (mPackages) { 19286 mSettings.readPreferredActivitiesLPw(parser, userId); 19287 } 19288 } 19289 } ); 19290 } catch (Exception e) { 19291 if (DEBUG_BACKUP) { 19292 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19293 } 19294 } 19295 } 19296 19297 /** 19298 * Non-Binder method, support for the backup/restore mechanism: write the 19299 * default browser (etc) settings in its canonical XML format. Returns the default 19300 * browser XML representation as a byte array, or null if there is none. 19301 */ 19302 @Override 19303 public byte[] getDefaultAppsBackup(int userId) { 19304 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19305 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19306 } 19307 19308 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19309 try { 19310 final XmlSerializer serializer = new FastXmlSerializer(); 19311 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19312 serializer.startDocument(null, true); 19313 serializer.startTag(null, TAG_DEFAULT_APPS); 19314 19315 synchronized (mPackages) { 19316 mSettings.writeDefaultAppsLPr(serializer, userId); 19317 } 19318 19319 serializer.endTag(null, TAG_DEFAULT_APPS); 19320 serializer.endDocument(); 19321 serializer.flush(); 19322 } catch (Exception e) { 19323 if (DEBUG_BACKUP) { 19324 Slog.e(TAG, "Unable to write default apps for backup", e); 19325 } 19326 return null; 19327 } 19328 19329 return dataStream.toByteArray(); 19330 } 19331 19332 @Override 19333 public void restoreDefaultApps(byte[] backup, int userId) { 19334 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19335 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19336 } 19337 19338 try { 19339 final XmlPullParser parser = Xml.newPullParser(); 19340 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19341 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19342 new BlobXmlRestorer() { 19343 @Override 19344 public void apply(XmlPullParser parser, int userId) 19345 throws XmlPullParserException, IOException { 19346 synchronized (mPackages) { 19347 mSettings.readDefaultAppsLPw(parser, userId); 19348 } 19349 } 19350 } ); 19351 } catch (Exception e) { 19352 if (DEBUG_BACKUP) { 19353 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19354 } 19355 } 19356 } 19357 19358 @Override 19359 public byte[] getIntentFilterVerificationBackup(int userId) { 19360 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19361 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19362 } 19363 19364 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19365 try { 19366 final XmlSerializer serializer = new FastXmlSerializer(); 19367 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19368 serializer.startDocument(null, true); 19369 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19370 19371 synchronized (mPackages) { 19372 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19373 } 19374 19375 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19376 serializer.endDocument(); 19377 serializer.flush(); 19378 } catch (Exception e) { 19379 if (DEBUG_BACKUP) { 19380 Slog.e(TAG, "Unable to write default apps for backup", e); 19381 } 19382 return null; 19383 } 19384 19385 return dataStream.toByteArray(); 19386 } 19387 19388 @Override 19389 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19390 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19391 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19392 } 19393 19394 try { 19395 final XmlPullParser parser = Xml.newPullParser(); 19396 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19397 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19398 new BlobXmlRestorer() { 19399 @Override 19400 public void apply(XmlPullParser parser, int userId) 19401 throws XmlPullParserException, IOException { 19402 synchronized (mPackages) { 19403 mSettings.readAllDomainVerificationsLPr(parser, userId); 19404 mSettings.writeLPr(); 19405 } 19406 } 19407 } ); 19408 } catch (Exception e) { 19409 if (DEBUG_BACKUP) { 19410 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19411 } 19412 } 19413 } 19414 19415 @Override 19416 public byte[] getPermissionGrantBackup(int userId) { 19417 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19418 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19419 } 19420 19421 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19422 try { 19423 final XmlSerializer serializer = new FastXmlSerializer(); 19424 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19425 serializer.startDocument(null, true); 19426 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19427 19428 synchronized (mPackages) { 19429 serializeRuntimePermissionGrantsLPr(serializer, userId); 19430 } 19431 19432 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19433 serializer.endDocument(); 19434 serializer.flush(); 19435 } catch (Exception e) { 19436 if (DEBUG_BACKUP) { 19437 Slog.e(TAG, "Unable to write default apps for backup", e); 19438 } 19439 return null; 19440 } 19441 19442 return dataStream.toByteArray(); 19443 } 19444 19445 @Override 19446 public void restorePermissionGrants(byte[] backup, int userId) { 19447 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19448 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19449 } 19450 19451 try { 19452 final XmlPullParser parser = Xml.newPullParser(); 19453 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19454 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19455 new BlobXmlRestorer() { 19456 @Override 19457 public void apply(XmlPullParser parser, int userId) 19458 throws XmlPullParserException, IOException { 19459 synchronized (mPackages) { 19460 processRestoredPermissionGrantsLPr(parser, userId); 19461 } 19462 } 19463 } ); 19464 } catch (Exception e) { 19465 if (DEBUG_BACKUP) { 19466 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19467 } 19468 } 19469 } 19470 19471 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19472 throws IOException { 19473 serializer.startTag(null, TAG_ALL_GRANTS); 19474 19475 final int N = mSettings.mPackages.size(); 19476 for (int i = 0; i < N; i++) { 19477 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19478 boolean pkgGrantsKnown = false; 19479 19480 PermissionsState packagePerms = ps.getPermissionsState(); 19481 19482 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19483 final int grantFlags = state.getFlags(); 19484 // only look at grants that are not system/policy fixed 19485 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19486 final boolean isGranted = state.isGranted(); 19487 // And only back up the user-twiddled state bits 19488 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19489 final String packageName = mSettings.mPackages.keyAt(i); 19490 if (!pkgGrantsKnown) { 19491 serializer.startTag(null, TAG_GRANT); 19492 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19493 pkgGrantsKnown = true; 19494 } 19495 19496 final boolean userSet = 19497 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19498 final boolean userFixed = 19499 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19500 final boolean revoke = 19501 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19502 19503 serializer.startTag(null, TAG_PERMISSION); 19504 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19505 if (isGranted) { 19506 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19507 } 19508 if (userSet) { 19509 serializer.attribute(null, ATTR_USER_SET, "true"); 19510 } 19511 if (userFixed) { 19512 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19513 } 19514 if (revoke) { 19515 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19516 } 19517 serializer.endTag(null, TAG_PERMISSION); 19518 } 19519 } 19520 } 19521 19522 if (pkgGrantsKnown) { 19523 serializer.endTag(null, TAG_GRANT); 19524 } 19525 } 19526 19527 serializer.endTag(null, TAG_ALL_GRANTS); 19528 } 19529 19530 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19531 throws XmlPullParserException, IOException { 19532 String pkgName = null; 19533 int outerDepth = parser.getDepth(); 19534 int type; 19535 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19536 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19537 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19538 continue; 19539 } 19540 19541 final String tagName = parser.getName(); 19542 if (tagName.equals(TAG_GRANT)) { 19543 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19544 if (DEBUG_BACKUP) { 19545 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19546 } 19547 } else if (tagName.equals(TAG_PERMISSION)) { 19548 19549 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19550 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19551 19552 int newFlagSet = 0; 19553 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19554 newFlagSet |= FLAG_PERMISSION_USER_SET; 19555 } 19556 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19557 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19558 } 19559 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19560 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19561 } 19562 if (DEBUG_BACKUP) { 19563 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19564 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19565 } 19566 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19567 if (ps != null) { 19568 // Already installed so we apply the grant immediately 19569 if (DEBUG_BACKUP) { 19570 Slog.v(TAG, " + already installed; applying"); 19571 } 19572 PermissionsState perms = ps.getPermissionsState(); 19573 BasePermission bp = mSettings.mPermissions.get(permName); 19574 if (bp != null) { 19575 if (isGranted) { 19576 perms.grantRuntimePermission(bp, userId); 19577 } 19578 if (newFlagSet != 0) { 19579 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19580 } 19581 } 19582 } else { 19583 // Need to wait for post-restore install to apply the grant 19584 if (DEBUG_BACKUP) { 19585 Slog.v(TAG, " - not yet installed; saving for later"); 19586 } 19587 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19588 isGranted, newFlagSet, userId); 19589 } 19590 } else { 19591 PackageManagerService.reportSettingsProblem(Log.WARN, 19592 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19593 XmlUtils.skipCurrentTag(parser); 19594 } 19595 } 19596 19597 scheduleWriteSettingsLocked(); 19598 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19599 } 19600 19601 @Override 19602 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19603 int sourceUserId, int targetUserId, int flags) { 19604 mContext.enforceCallingOrSelfPermission( 19605 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19606 int callingUid = Binder.getCallingUid(); 19607 enforceOwnerRights(ownerPackage, callingUid); 19608 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19609 if (intentFilter.countActions() == 0) { 19610 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19611 return; 19612 } 19613 synchronized (mPackages) { 19614 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19615 ownerPackage, targetUserId, flags); 19616 CrossProfileIntentResolver resolver = 19617 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19618 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19619 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19620 if (existing != null) { 19621 int size = existing.size(); 19622 for (int i = 0; i < size; i++) { 19623 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19624 return; 19625 } 19626 } 19627 } 19628 resolver.addFilter(newFilter); 19629 scheduleWritePackageRestrictionsLocked(sourceUserId); 19630 } 19631 } 19632 19633 @Override 19634 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19635 mContext.enforceCallingOrSelfPermission( 19636 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19637 int callingUid = Binder.getCallingUid(); 19638 enforceOwnerRights(ownerPackage, callingUid); 19639 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19640 synchronized (mPackages) { 19641 CrossProfileIntentResolver resolver = 19642 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19643 ArraySet<CrossProfileIntentFilter> set = 19644 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19645 for (CrossProfileIntentFilter filter : set) { 19646 if (filter.getOwnerPackage().equals(ownerPackage)) { 19647 resolver.removeFilter(filter); 19648 } 19649 } 19650 scheduleWritePackageRestrictionsLocked(sourceUserId); 19651 } 19652 } 19653 19654 // Enforcing that callingUid is owning pkg on userId 19655 private void enforceOwnerRights(String pkg, int callingUid) { 19656 // The system owns everything. 19657 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19658 return; 19659 } 19660 int callingUserId = UserHandle.getUserId(callingUid); 19661 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19662 if (pi == null) { 19663 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19664 + callingUserId); 19665 } 19666 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19667 throw new SecurityException("Calling uid " + callingUid 19668 + " does not own package " + pkg); 19669 } 19670 } 19671 19672 @Override 19673 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19674 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19675 } 19676 19677 /** 19678 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19679 * then reports the most likely home activity or null if there are more than one. 19680 */ 19681 public ComponentName getDefaultHomeActivity(int userId) { 19682 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19683 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19684 if (cn != null) { 19685 return cn; 19686 } 19687 19688 // Find the launcher with the highest priority and return that component if there are no 19689 // other home activity with the same priority. 19690 int lastPriority = Integer.MIN_VALUE; 19691 ComponentName lastComponent = null; 19692 final int size = allHomeCandidates.size(); 19693 for (int i = 0; i < size; i++) { 19694 final ResolveInfo ri = allHomeCandidates.get(i); 19695 if (ri.priority > lastPriority) { 19696 lastComponent = ri.activityInfo.getComponentName(); 19697 lastPriority = ri.priority; 19698 } else if (ri.priority == lastPriority) { 19699 // Two components found with same priority. 19700 lastComponent = null; 19701 } 19702 } 19703 return lastComponent; 19704 } 19705 19706 private Intent getHomeIntent() { 19707 Intent intent = new Intent(Intent.ACTION_MAIN); 19708 intent.addCategory(Intent.CATEGORY_HOME); 19709 intent.addCategory(Intent.CATEGORY_DEFAULT); 19710 return intent; 19711 } 19712 19713 private IntentFilter getHomeFilter() { 19714 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19715 filter.addCategory(Intent.CATEGORY_HOME); 19716 filter.addCategory(Intent.CATEGORY_DEFAULT); 19717 return filter; 19718 } 19719 19720 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19721 int userId) { 19722 Intent intent = getHomeIntent(); 19723 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19724 PackageManager.GET_META_DATA, userId); 19725 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19726 true, false, false, userId); 19727 19728 allHomeCandidates.clear(); 19729 if (list != null) { 19730 for (ResolveInfo ri : list) { 19731 allHomeCandidates.add(ri); 19732 } 19733 } 19734 return (preferred == null || preferred.activityInfo == null) 19735 ? null 19736 : new ComponentName(preferred.activityInfo.packageName, 19737 preferred.activityInfo.name); 19738 } 19739 19740 @Override 19741 public void setHomeActivity(ComponentName comp, int userId) { 19742 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19743 getHomeActivitiesAsUser(homeActivities, userId); 19744 19745 boolean found = false; 19746 19747 final int size = homeActivities.size(); 19748 final ComponentName[] set = new ComponentName[size]; 19749 for (int i = 0; i < size; i++) { 19750 final ResolveInfo candidate = homeActivities.get(i); 19751 final ActivityInfo info = candidate.activityInfo; 19752 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19753 set[i] = activityName; 19754 if (!found && activityName.equals(comp)) { 19755 found = true; 19756 } 19757 } 19758 if (!found) { 19759 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19760 + userId); 19761 } 19762 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19763 set, comp, userId); 19764 } 19765 19766 private @Nullable String getSetupWizardPackageName() { 19767 final Intent intent = new Intent(Intent.ACTION_MAIN); 19768 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19769 19770 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19771 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19772 | MATCH_DISABLED_COMPONENTS, 19773 UserHandle.myUserId()); 19774 if (matches.size() == 1) { 19775 return matches.get(0).getComponentInfo().packageName; 19776 } else { 19777 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19778 + ": matches=" + matches); 19779 return null; 19780 } 19781 } 19782 19783 private @Nullable String getStorageManagerPackageName() { 19784 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19785 19786 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19787 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19788 | MATCH_DISABLED_COMPONENTS, 19789 UserHandle.myUserId()); 19790 if (matches.size() == 1) { 19791 return matches.get(0).getComponentInfo().packageName; 19792 } else { 19793 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19794 + matches.size() + ": matches=" + matches); 19795 return null; 19796 } 19797 } 19798 19799 @Override 19800 public void setApplicationEnabledSetting(String appPackageName, 19801 int newState, int flags, int userId, String callingPackage) { 19802 if (!sUserManager.exists(userId)) return; 19803 if (callingPackage == null) { 19804 callingPackage = Integer.toString(Binder.getCallingUid()); 19805 } 19806 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19807 } 19808 19809 @Override 19810 public void setComponentEnabledSetting(ComponentName componentName, 19811 int newState, int flags, int userId) { 19812 if (!sUserManager.exists(userId)) return; 19813 setEnabledSetting(componentName.getPackageName(), 19814 componentName.getClassName(), newState, flags, userId, null); 19815 } 19816 19817 private void setEnabledSetting(final String packageName, String className, int newState, 19818 final int flags, int userId, String callingPackage) { 19819 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19820 || newState == COMPONENT_ENABLED_STATE_ENABLED 19821 || newState == COMPONENT_ENABLED_STATE_DISABLED 19822 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19823 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19824 throw new IllegalArgumentException("Invalid new component state: " 19825 + newState); 19826 } 19827 PackageSetting pkgSetting; 19828 final int uid = Binder.getCallingUid(); 19829 final int permission; 19830 if (uid == Process.SYSTEM_UID) { 19831 permission = PackageManager.PERMISSION_GRANTED; 19832 } else { 19833 permission = mContext.checkCallingOrSelfPermission( 19834 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19835 } 19836 enforceCrossUserPermission(uid, userId, 19837 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19838 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19839 boolean sendNow = false; 19840 boolean isApp = (className == null); 19841 String componentName = isApp ? packageName : className; 19842 int packageUid = -1; 19843 ArrayList<String> components; 19844 19845 // writer 19846 synchronized (mPackages) { 19847 pkgSetting = mSettings.mPackages.get(packageName); 19848 if (pkgSetting == null) { 19849 if (className == null) { 19850 throw new IllegalArgumentException("Unknown package: " + packageName); 19851 } 19852 throw new IllegalArgumentException( 19853 "Unknown component: " + packageName + "/" + className); 19854 } 19855 } 19856 19857 // Limit who can change which apps 19858 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19859 // Don't allow apps that don't have permission to modify other apps 19860 if (!allowedByPermission) { 19861 throw new SecurityException( 19862 "Permission Denial: attempt to change component state from pid=" 19863 + Binder.getCallingPid() 19864 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19865 } 19866 // Don't allow changing protected packages. 19867 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19868 throw new SecurityException("Cannot disable a protected package: " + packageName); 19869 } 19870 } 19871 19872 synchronized (mPackages) { 19873 if (uid == Process.SHELL_UID 19874 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19875 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19876 // unless it is a test package. 19877 int oldState = pkgSetting.getEnabled(userId); 19878 if (className == null 19879 && 19880 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19881 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19882 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19883 && 19884 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19885 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19886 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19887 // ok 19888 } else { 19889 throw new SecurityException( 19890 "Shell cannot change component state for " + packageName + "/" 19891 + className + " to " + newState); 19892 } 19893 } 19894 if (className == null) { 19895 // We're dealing with an application/package level state change 19896 if (pkgSetting.getEnabled(userId) == newState) { 19897 // Nothing to do 19898 return; 19899 } 19900 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19901 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19902 // Don't care about who enables an app. 19903 callingPackage = null; 19904 } 19905 pkgSetting.setEnabled(newState, userId, callingPackage); 19906 // pkgSetting.pkg.mSetEnabled = newState; 19907 } else { 19908 // We're dealing with a component level state change 19909 // First, verify that this is a valid class name. 19910 PackageParser.Package pkg = pkgSetting.pkg; 19911 if (pkg == null || !pkg.hasComponentClassName(className)) { 19912 if (pkg != null && 19913 pkg.applicationInfo.targetSdkVersion >= 19914 Build.VERSION_CODES.JELLY_BEAN) { 19915 throw new IllegalArgumentException("Component class " + className 19916 + " does not exist in " + packageName); 19917 } else { 19918 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19919 + className + " does not exist in " + packageName); 19920 } 19921 } 19922 switch (newState) { 19923 case COMPONENT_ENABLED_STATE_ENABLED: 19924 if (!pkgSetting.enableComponentLPw(className, userId)) { 19925 return; 19926 } 19927 break; 19928 case COMPONENT_ENABLED_STATE_DISABLED: 19929 if (!pkgSetting.disableComponentLPw(className, userId)) { 19930 return; 19931 } 19932 break; 19933 case COMPONENT_ENABLED_STATE_DEFAULT: 19934 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19935 return; 19936 } 19937 break; 19938 default: 19939 Slog.e(TAG, "Invalid new component state: " + newState); 19940 return; 19941 } 19942 } 19943 scheduleWritePackageRestrictionsLocked(userId); 19944 updateSequenceNumberLP(packageName, new int[] { userId }); 19945 components = mPendingBroadcasts.get(userId, packageName); 19946 final boolean newPackage = components == null; 19947 if (newPackage) { 19948 components = new ArrayList<String>(); 19949 } 19950 if (!components.contains(componentName)) { 19951 components.add(componentName); 19952 } 19953 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19954 sendNow = true; 19955 // Purge entry from pending broadcast list if another one exists already 19956 // since we are sending one right away. 19957 mPendingBroadcasts.remove(userId, packageName); 19958 } else { 19959 if (newPackage) { 19960 mPendingBroadcasts.put(userId, packageName, components); 19961 } 19962 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19963 // Schedule a message 19964 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19965 } 19966 } 19967 } 19968 19969 long callingId = Binder.clearCallingIdentity(); 19970 try { 19971 if (sendNow) { 19972 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19973 sendPackageChangedBroadcast(packageName, 19974 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19975 } 19976 } finally { 19977 Binder.restoreCallingIdentity(callingId); 19978 } 19979 } 19980 19981 @Override 19982 public void flushPackageRestrictionsAsUser(int userId) { 19983 if (!sUserManager.exists(userId)) { 19984 return; 19985 } 19986 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19987 false /* checkShell */, "flushPackageRestrictions"); 19988 synchronized (mPackages) { 19989 mSettings.writePackageRestrictionsLPr(userId); 19990 mDirtyUsers.remove(userId); 19991 if (mDirtyUsers.isEmpty()) { 19992 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19993 } 19994 } 19995 } 19996 19997 private void sendPackageChangedBroadcast(String packageName, 19998 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19999 if (DEBUG_INSTALL) 20000 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20001 + componentNames); 20002 Bundle extras = new Bundle(4); 20003 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20004 String nameList[] = new String[componentNames.size()]; 20005 componentNames.toArray(nameList); 20006 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20007 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20008 extras.putInt(Intent.EXTRA_UID, packageUid); 20009 // If this is not reporting a change of the overall package, then only send it 20010 // to registered receivers. We don't want to launch a swath of apps for every 20011 // little component state change. 20012 final int flags = !componentNames.contains(packageName) 20013 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20014 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20015 new int[] {UserHandle.getUserId(packageUid)}); 20016 } 20017 20018 @Override 20019 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20020 if (!sUserManager.exists(userId)) return; 20021 final int uid = Binder.getCallingUid(); 20022 final int permission = mContext.checkCallingOrSelfPermission( 20023 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20024 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20025 enforceCrossUserPermission(uid, userId, 20026 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20027 // writer 20028 synchronized (mPackages) { 20029 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20030 allowedByPermission, uid, userId)) { 20031 scheduleWritePackageRestrictionsLocked(userId); 20032 } 20033 } 20034 } 20035 20036 @Override 20037 public String getInstallerPackageName(String packageName) { 20038 // reader 20039 synchronized (mPackages) { 20040 return mSettings.getInstallerPackageNameLPr(packageName); 20041 } 20042 } 20043 20044 public boolean isOrphaned(String packageName) { 20045 // reader 20046 synchronized (mPackages) { 20047 return mSettings.isOrphaned(packageName); 20048 } 20049 } 20050 20051 @Override 20052 public int getApplicationEnabledSetting(String packageName, int userId) { 20053 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20054 int uid = Binder.getCallingUid(); 20055 enforceCrossUserPermission(uid, userId, 20056 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20057 // reader 20058 synchronized (mPackages) { 20059 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20060 } 20061 } 20062 20063 @Override 20064 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20065 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20066 int uid = Binder.getCallingUid(); 20067 enforceCrossUserPermission(uid, userId, 20068 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20069 // reader 20070 synchronized (mPackages) { 20071 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20072 } 20073 } 20074 20075 @Override 20076 public void enterSafeMode() { 20077 enforceSystemOrRoot("Only the system can request entering safe mode"); 20078 20079 if (!mSystemReady) { 20080 mSafeMode = true; 20081 } 20082 } 20083 20084 @Override 20085 public void systemReady() { 20086 mSystemReady = true; 20087 20088 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20089 // disabled after already being started. 20090 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20091 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20092 20093 // Read the compatibilty setting when the system is ready. 20094 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20095 mContext.getContentResolver(), 20096 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20097 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20098 if (DEBUG_SETTINGS) { 20099 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20100 } 20101 20102 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20103 20104 synchronized (mPackages) { 20105 // Verify that all of the preferred activity components actually 20106 // exist. It is possible for applications to be updated and at 20107 // that point remove a previously declared activity component that 20108 // had been set as a preferred activity. We try to clean this up 20109 // the next time we encounter that preferred activity, but it is 20110 // possible for the user flow to never be able to return to that 20111 // situation so here we do a sanity check to make sure we haven't 20112 // left any junk around. 20113 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20114 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20115 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20116 removed.clear(); 20117 for (PreferredActivity pa : pir.filterSet()) { 20118 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20119 removed.add(pa); 20120 } 20121 } 20122 if (removed.size() > 0) { 20123 for (int r=0; r<removed.size(); r++) { 20124 PreferredActivity pa = removed.get(r); 20125 Slog.w(TAG, "Removing dangling preferred activity: " 20126 + pa.mPref.mComponent); 20127 pir.removeFilter(pa); 20128 } 20129 mSettings.writePackageRestrictionsLPr( 20130 mSettings.mPreferredActivities.keyAt(i)); 20131 } 20132 } 20133 20134 for (int userId : UserManagerService.getInstance().getUserIds()) { 20135 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20136 grantPermissionsUserIds = ArrayUtils.appendInt( 20137 grantPermissionsUserIds, userId); 20138 } 20139 } 20140 } 20141 sUserManager.systemReady(); 20142 20143 // If we upgraded grant all default permissions before kicking off. 20144 for (int userId : grantPermissionsUserIds) { 20145 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20146 } 20147 20148 // If we did not grant default permissions, we preload from this the 20149 // default permission exceptions lazily to ensure we don't hit the 20150 // disk on a new user creation. 20151 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20152 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20153 } 20154 20155 // Kick off any messages waiting for system ready 20156 if (mPostSystemReadyMessages != null) { 20157 for (Message msg : mPostSystemReadyMessages) { 20158 msg.sendToTarget(); 20159 } 20160 mPostSystemReadyMessages = null; 20161 } 20162 20163 // Watch for external volumes that come and go over time 20164 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20165 storage.registerListener(mStorageListener); 20166 20167 mInstallerService.systemReady(); 20168 mPackageDexOptimizer.systemReady(); 20169 20170 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20171 StorageManagerInternal.class); 20172 StorageManagerInternal.addExternalStoragePolicy( 20173 new StorageManagerInternal.ExternalStorageMountPolicy() { 20174 @Override 20175 public int getMountMode(int uid, String packageName) { 20176 if (Process.isIsolated(uid)) { 20177 return Zygote.MOUNT_EXTERNAL_NONE; 20178 } 20179 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20180 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20181 } 20182 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20183 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20184 } 20185 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20186 return Zygote.MOUNT_EXTERNAL_READ; 20187 } 20188 return Zygote.MOUNT_EXTERNAL_WRITE; 20189 } 20190 20191 @Override 20192 public boolean hasExternalStorage(int uid, String packageName) { 20193 return true; 20194 } 20195 }); 20196 20197 // Now that we're mostly running, clean up stale users and apps 20198 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20199 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20200 20201 if (mPrivappPermissionsViolations != null) { 20202 Slog.wtf(TAG,"Signature|privileged permissions not in " 20203 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20204 mPrivappPermissionsViolations = null; 20205 } 20206 } 20207 20208 public void waitForAppDataPrepared() { 20209 if (mPrepareAppDataFuture == null) { 20210 return; 20211 } 20212 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20213 mPrepareAppDataFuture = null; 20214 } 20215 20216 @Override 20217 public boolean isSafeMode() { 20218 return mSafeMode; 20219 } 20220 20221 @Override 20222 public boolean hasSystemUidErrors() { 20223 return mHasSystemUidErrors; 20224 } 20225 20226 static String arrayToString(int[] array) { 20227 StringBuffer buf = new StringBuffer(128); 20228 buf.append('['); 20229 if (array != null) { 20230 for (int i=0; i<array.length; i++) { 20231 if (i > 0) buf.append(", "); 20232 buf.append(array[i]); 20233 } 20234 } 20235 buf.append(']'); 20236 return buf.toString(); 20237 } 20238 20239 static class DumpState { 20240 public static final int DUMP_LIBS = 1 << 0; 20241 public static final int DUMP_FEATURES = 1 << 1; 20242 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20243 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20244 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20245 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20246 public static final int DUMP_PERMISSIONS = 1 << 6; 20247 public static final int DUMP_PACKAGES = 1 << 7; 20248 public static final int DUMP_SHARED_USERS = 1 << 8; 20249 public static final int DUMP_MESSAGES = 1 << 9; 20250 public static final int DUMP_PROVIDERS = 1 << 10; 20251 public static final int DUMP_VERIFIERS = 1 << 11; 20252 public static final int DUMP_PREFERRED = 1 << 12; 20253 public static final int DUMP_PREFERRED_XML = 1 << 13; 20254 public static final int DUMP_KEYSETS = 1 << 14; 20255 public static final int DUMP_VERSION = 1 << 15; 20256 public static final int DUMP_INSTALLS = 1 << 16; 20257 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20258 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20259 public static final int DUMP_FROZEN = 1 << 19; 20260 public static final int DUMP_DEXOPT = 1 << 20; 20261 public static final int DUMP_COMPILER_STATS = 1 << 21; 20262 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20263 20264 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20265 20266 private int mTypes; 20267 20268 private int mOptions; 20269 20270 private boolean mTitlePrinted; 20271 20272 private SharedUserSetting mSharedUser; 20273 20274 public boolean isDumping(int type) { 20275 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20276 return true; 20277 } 20278 20279 return (mTypes & type) != 0; 20280 } 20281 20282 public void setDump(int type) { 20283 mTypes |= type; 20284 } 20285 20286 public boolean isOptionEnabled(int option) { 20287 return (mOptions & option) != 0; 20288 } 20289 20290 public void setOptionEnabled(int option) { 20291 mOptions |= option; 20292 } 20293 20294 public boolean onTitlePrinted() { 20295 final boolean printed = mTitlePrinted; 20296 mTitlePrinted = true; 20297 return printed; 20298 } 20299 20300 public boolean getTitlePrinted() { 20301 return mTitlePrinted; 20302 } 20303 20304 public void setTitlePrinted(boolean enabled) { 20305 mTitlePrinted = enabled; 20306 } 20307 20308 public SharedUserSetting getSharedUser() { 20309 return mSharedUser; 20310 } 20311 20312 public void setSharedUser(SharedUserSetting user) { 20313 mSharedUser = user; 20314 } 20315 } 20316 20317 @Override 20318 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20319 FileDescriptor err, String[] args, ShellCallback callback, 20320 ResultReceiver resultReceiver) { 20321 (new PackageManagerShellCommand(this)).exec( 20322 this, in, out, err, args, callback, resultReceiver); 20323 } 20324 20325 @Override 20326 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20327 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20328 != PackageManager.PERMISSION_GRANTED) { 20329 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20330 + Binder.getCallingPid() 20331 + ", uid=" + Binder.getCallingUid() 20332 + " without permission " 20333 + android.Manifest.permission.DUMP); 20334 return; 20335 } 20336 20337 DumpState dumpState = new DumpState(); 20338 boolean fullPreferred = false; 20339 boolean checkin = false; 20340 20341 String packageName = null; 20342 ArraySet<String> permissionNames = null; 20343 20344 int opti = 0; 20345 while (opti < args.length) { 20346 String opt = args[opti]; 20347 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20348 break; 20349 } 20350 opti++; 20351 20352 if ("-a".equals(opt)) { 20353 // Right now we only know how to print all. 20354 } else if ("-h".equals(opt)) { 20355 pw.println("Package manager dump options:"); 20356 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20357 pw.println(" --checkin: dump for a checkin"); 20358 pw.println(" -f: print details of intent filters"); 20359 pw.println(" -h: print this help"); 20360 pw.println(" cmd may be one of:"); 20361 pw.println(" l[ibraries]: list known shared libraries"); 20362 pw.println(" f[eatures]: list device features"); 20363 pw.println(" k[eysets]: print known keysets"); 20364 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20365 pw.println(" perm[issions]: dump permissions"); 20366 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20367 pw.println(" pref[erred]: print preferred package settings"); 20368 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20369 pw.println(" prov[iders]: dump content providers"); 20370 pw.println(" p[ackages]: dump installed packages"); 20371 pw.println(" s[hared-users]: dump shared user IDs"); 20372 pw.println(" m[essages]: print collected runtime messages"); 20373 pw.println(" v[erifiers]: print package verifier info"); 20374 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20375 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20376 pw.println(" version: print database version info"); 20377 pw.println(" write: write current settings now"); 20378 pw.println(" installs: details about install sessions"); 20379 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20380 pw.println(" dexopt: dump dexopt state"); 20381 pw.println(" compiler-stats: dump compiler statistics"); 20382 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20383 pw.println(" <package.name>: info about given package"); 20384 return; 20385 } else if ("--checkin".equals(opt)) { 20386 checkin = true; 20387 } else if ("-f".equals(opt)) { 20388 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20389 } else if ("--proto".equals(opt)) { 20390 dumpProto(fd); 20391 return; 20392 } else { 20393 pw.println("Unknown argument: " + opt + "; use -h for help"); 20394 } 20395 } 20396 20397 // Is the caller requesting to dump a particular piece of data? 20398 if (opti < args.length) { 20399 String cmd = args[opti]; 20400 opti++; 20401 // Is this a package name? 20402 if ("android".equals(cmd) || cmd.contains(".")) { 20403 packageName = cmd; 20404 // When dumping a single package, we always dump all of its 20405 // filter information since the amount of data will be reasonable. 20406 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20407 } else if ("check-permission".equals(cmd)) { 20408 if (opti >= args.length) { 20409 pw.println("Error: check-permission missing permission argument"); 20410 return; 20411 } 20412 String perm = args[opti]; 20413 opti++; 20414 if (opti >= args.length) { 20415 pw.println("Error: check-permission missing package argument"); 20416 return; 20417 } 20418 20419 String pkg = args[opti]; 20420 opti++; 20421 int user = UserHandle.getUserId(Binder.getCallingUid()); 20422 if (opti < args.length) { 20423 try { 20424 user = Integer.parseInt(args[opti]); 20425 } catch (NumberFormatException e) { 20426 pw.println("Error: check-permission user argument is not a number: " 20427 + args[opti]); 20428 return; 20429 } 20430 } 20431 20432 // Normalize package name to handle renamed packages and static libs 20433 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20434 20435 pw.println(checkPermission(perm, pkg, user)); 20436 return; 20437 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20438 dumpState.setDump(DumpState.DUMP_LIBS); 20439 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20440 dumpState.setDump(DumpState.DUMP_FEATURES); 20441 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20442 if (opti >= args.length) { 20443 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20444 | DumpState.DUMP_SERVICE_RESOLVERS 20445 | DumpState.DUMP_RECEIVER_RESOLVERS 20446 | DumpState.DUMP_CONTENT_RESOLVERS); 20447 } else { 20448 while (opti < args.length) { 20449 String name = args[opti]; 20450 if ("a".equals(name) || "activity".equals(name)) { 20451 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20452 } else if ("s".equals(name) || "service".equals(name)) { 20453 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20454 } else if ("r".equals(name) || "receiver".equals(name)) { 20455 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20456 } else if ("c".equals(name) || "content".equals(name)) { 20457 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20458 } else { 20459 pw.println("Error: unknown resolver table type: " + name); 20460 return; 20461 } 20462 opti++; 20463 } 20464 } 20465 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20466 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20467 } else if ("permission".equals(cmd)) { 20468 if (opti >= args.length) { 20469 pw.println("Error: permission requires permission name"); 20470 return; 20471 } 20472 permissionNames = new ArraySet<>(); 20473 while (opti < args.length) { 20474 permissionNames.add(args[opti]); 20475 opti++; 20476 } 20477 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20478 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20479 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20480 dumpState.setDump(DumpState.DUMP_PREFERRED); 20481 } else if ("preferred-xml".equals(cmd)) { 20482 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20483 if (opti < args.length && "--full".equals(args[opti])) { 20484 fullPreferred = true; 20485 opti++; 20486 } 20487 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20488 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20489 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20490 dumpState.setDump(DumpState.DUMP_PACKAGES); 20491 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20492 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20493 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20494 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20495 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20496 dumpState.setDump(DumpState.DUMP_MESSAGES); 20497 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20498 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20499 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20500 || "intent-filter-verifiers".equals(cmd)) { 20501 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20502 } else if ("version".equals(cmd)) { 20503 dumpState.setDump(DumpState.DUMP_VERSION); 20504 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20505 dumpState.setDump(DumpState.DUMP_KEYSETS); 20506 } else if ("installs".equals(cmd)) { 20507 dumpState.setDump(DumpState.DUMP_INSTALLS); 20508 } else if ("frozen".equals(cmd)) { 20509 dumpState.setDump(DumpState.DUMP_FROZEN); 20510 } else if ("dexopt".equals(cmd)) { 20511 dumpState.setDump(DumpState.DUMP_DEXOPT); 20512 } else if ("compiler-stats".equals(cmd)) { 20513 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20514 } else if ("enabled-overlays".equals(cmd)) { 20515 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20516 } else if ("write".equals(cmd)) { 20517 synchronized (mPackages) { 20518 mSettings.writeLPr(); 20519 pw.println("Settings written."); 20520 return; 20521 } 20522 } 20523 } 20524 20525 if (checkin) { 20526 pw.println("vers,1"); 20527 } 20528 20529 // reader 20530 synchronized (mPackages) { 20531 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20532 if (!checkin) { 20533 if (dumpState.onTitlePrinted()) 20534 pw.println(); 20535 pw.println("Database versions:"); 20536 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20537 } 20538 } 20539 20540 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20541 if (!checkin) { 20542 if (dumpState.onTitlePrinted()) 20543 pw.println(); 20544 pw.println("Verifiers:"); 20545 pw.print(" Required: "); 20546 pw.print(mRequiredVerifierPackage); 20547 pw.print(" (uid="); 20548 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20549 UserHandle.USER_SYSTEM)); 20550 pw.println(")"); 20551 } else if (mRequiredVerifierPackage != null) { 20552 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20553 pw.print(","); 20554 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20555 UserHandle.USER_SYSTEM)); 20556 } 20557 } 20558 20559 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20560 packageName == null) { 20561 if (mIntentFilterVerifierComponent != null) { 20562 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20563 if (!checkin) { 20564 if (dumpState.onTitlePrinted()) 20565 pw.println(); 20566 pw.println("Intent Filter Verifier:"); 20567 pw.print(" Using: "); 20568 pw.print(verifierPackageName); 20569 pw.print(" (uid="); 20570 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20571 UserHandle.USER_SYSTEM)); 20572 pw.println(")"); 20573 } else if (verifierPackageName != null) { 20574 pw.print("ifv,"); pw.print(verifierPackageName); 20575 pw.print(","); 20576 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20577 UserHandle.USER_SYSTEM)); 20578 } 20579 } else { 20580 pw.println(); 20581 pw.println("No Intent Filter Verifier available!"); 20582 } 20583 } 20584 20585 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20586 boolean printedHeader = false; 20587 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20588 while (it.hasNext()) { 20589 String libName = it.next(); 20590 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20591 if (versionedLib == null) { 20592 continue; 20593 } 20594 final int versionCount = versionedLib.size(); 20595 for (int i = 0; i < versionCount; i++) { 20596 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20597 if (!checkin) { 20598 if (!printedHeader) { 20599 if (dumpState.onTitlePrinted()) 20600 pw.println(); 20601 pw.println("Libraries:"); 20602 printedHeader = true; 20603 } 20604 pw.print(" "); 20605 } else { 20606 pw.print("lib,"); 20607 } 20608 pw.print(libEntry.info.getName()); 20609 if (libEntry.info.isStatic()) { 20610 pw.print(" version=" + libEntry.info.getVersion()); 20611 } 20612 if (!checkin) { 20613 pw.print(" -> "); 20614 } 20615 if (libEntry.path != null) { 20616 pw.print(" (jar) "); 20617 pw.print(libEntry.path); 20618 } else { 20619 pw.print(" (apk) "); 20620 pw.print(libEntry.apk); 20621 } 20622 pw.println(); 20623 } 20624 } 20625 } 20626 20627 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20628 if (dumpState.onTitlePrinted()) 20629 pw.println(); 20630 if (!checkin) { 20631 pw.println("Features:"); 20632 } 20633 20634 synchronized (mAvailableFeatures) { 20635 for (FeatureInfo feat : mAvailableFeatures.values()) { 20636 if (checkin) { 20637 pw.print("feat,"); 20638 pw.print(feat.name); 20639 pw.print(","); 20640 pw.println(feat.version); 20641 } else { 20642 pw.print(" "); 20643 pw.print(feat.name); 20644 if (feat.version > 0) { 20645 pw.print(" version="); 20646 pw.print(feat.version); 20647 } 20648 pw.println(); 20649 } 20650 } 20651 } 20652 } 20653 20654 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20655 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20656 : "Activity Resolver Table:", " ", packageName, 20657 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20658 dumpState.setTitlePrinted(true); 20659 } 20660 } 20661 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20662 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20663 : "Receiver Resolver Table:", " ", packageName, 20664 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20665 dumpState.setTitlePrinted(true); 20666 } 20667 } 20668 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20669 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20670 : "Service Resolver Table:", " ", packageName, 20671 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20672 dumpState.setTitlePrinted(true); 20673 } 20674 } 20675 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20676 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20677 : "Provider Resolver Table:", " ", packageName, 20678 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20679 dumpState.setTitlePrinted(true); 20680 } 20681 } 20682 20683 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20684 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20685 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20686 int user = mSettings.mPreferredActivities.keyAt(i); 20687 if (pir.dump(pw, 20688 dumpState.getTitlePrinted() 20689 ? "\nPreferred Activities User " + user + ":" 20690 : "Preferred Activities User " + user + ":", " ", 20691 packageName, true, false)) { 20692 dumpState.setTitlePrinted(true); 20693 } 20694 } 20695 } 20696 20697 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20698 pw.flush(); 20699 FileOutputStream fout = new FileOutputStream(fd); 20700 BufferedOutputStream str = new BufferedOutputStream(fout); 20701 XmlSerializer serializer = new FastXmlSerializer(); 20702 try { 20703 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20704 serializer.startDocument(null, true); 20705 serializer.setFeature( 20706 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20707 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20708 serializer.endDocument(); 20709 serializer.flush(); 20710 } catch (IllegalArgumentException e) { 20711 pw.println("Failed writing: " + e); 20712 } catch (IllegalStateException e) { 20713 pw.println("Failed writing: " + e); 20714 } catch (IOException e) { 20715 pw.println("Failed writing: " + e); 20716 } 20717 } 20718 20719 if (!checkin 20720 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20721 && packageName == null) { 20722 pw.println(); 20723 int count = mSettings.mPackages.size(); 20724 if (count == 0) { 20725 pw.println("No applications!"); 20726 pw.println(); 20727 } else { 20728 final String prefix = " "; 20729 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20730 if (allPackageSettings.size() == 0) { 20731 pw.println("No domain preferred apps!"); 20732 pw.println(); 20733 } else { 20734 pw.println("App verification status:"); 20735 pw.println(); 20736 count = 0; 20737 for (PackageSetting ps : allPackageSettings) { 20738 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20739 if (ivi == null || ivi.getPackageName() == null) continue; 20740 pw.println(prefix + "Package: " + ivi.getPackageName()); 20741 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20742 pw.println(prefix + "Status: " + ivi.getStatusString()); 20743 pw.println(); 20744 count++; 20745 } 20746 if (count == 0) { 20747 pw.println(prefix + "No app verification established."); 20748 pw.println(); 20749 } 20750 for (int userId : sUserManager.getUserIds()) { 20751 pw.println("App linkages for user " + userId + ":"); 20752 pw.println(); 20753 count = 0; 20754 for (PackageSetting ps : allPackageSettings) { 20755 final long status = ps.getDomainVerificationStatusForUser(userId); 20756 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20757 && !DEBUG_DOMAIN_VERIFICATION) { 20758 continue; 20759 } 20760 pw.println(prefix + "Package: " + ps.name); 20761 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20762 String statusStr = IntentFilterVerificationInfo. 20763 getStatusStringFromValue(status); 20764 pw.println(prefix + "Status: " + statusStr); 20765 pw.println(); 20766 count++; 20767 } 20768 if (count == 0) { 20769 pw.println(prefix + "No configured app linkages."); 20770 pw.println(); 20771 } 20772 } 20773 } 20774 } 20775 } 20776 20777 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20778 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20779 if (packageName == null && permissionNames == null) { 20780 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20781 if (iperm == 0) { 20782 if (dumpState.onTitlePrinted()) 20783 pw.println(); 20784 pw.println("AppOp Permissions:"); 20785 } 20786 pw.print(" AppOp Permission "); 20787 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20788 pw.println(":"); 20789 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20790 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20791 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20792 } 20793 } 20794 } 20795 } 20796 20797 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20798 boolean printedSomething = false; 20799 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20800 if (packageName != null && !packageName.equals(p.info.packageName)) { 20801 continue; 20802 } 20803 if (!printedSomething) { 20804 if (dumpState.onTitlePrinted()) 20805 pw.println(); 20806 pw.println("Registered ContentProviders:"); 20807 printedSomething = true; 20808 } 20809 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20810 pw.print(" "); pw.println(p.toString()); 20811 } 20812 printedSomething = false; 20813 for (Map.Entry<String, PackageParser.Provider> entry : 20814 mProvidersByAuthority.entrySet()) { 20815 PackageParser.Provider p = entry.getValue(); 20816 if (packageName != null && !packageName.equals(p.info.packageName)) { 20817 continue; 20818 } 20819 if (!printedSomething) { 20820 if (dumpState.onTitlePrinted()) 20821 pw.println(); 20822 pw.println("ContentProvider Authorities:"); 20823 printedSomething = true; 20824 } 20825 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20826 pw.print(" "); pw.println(p.toString()); 20827 if (p.info != null && p.info.applicationInfo != null) { 20828 final String appInfo = p.info.applicationInfo.toString(); 20829 pw.print(" applicationInfo="); pw.println(appInfo); 20830 } 20831 } 20832 } 20833 20834 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20835 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20836 } 20837 20838 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20839 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20840 } 20841 20842 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20843 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20844 } 20845 20846 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20847 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20848 } 20849 20850 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20851 // XXX should handle packageName != null by dumping only install data that 20852 // the given package is involved with. 20853 if (dumpState.onTitlePrinted()) pw.println(); 20854 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20855 } 20856 20857 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20858 // XXX should handle packageName != null by dumping only install data that 20859 // the given package is involved with. 20860 if (dumpState.onTitlePrinted()) pw.println(); 20861 20862 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20863 ipw.println(); 20864 ipw.println("Frozen packages:"); 20865 ipw.increaseIndent(); 20866 if (mFrozenPackages.size() == 0) { 20867 ipw.println("(none)"); 20868 } else { 20869 for (int i = 0; i < mFrozenPackages.size(); i++) { 20870 ipw.println(mFrozenPackages.valueAt(i)); 20871 } 20872 } 20873 ipw.decreaseIndent(); 20874 } 20875 20876 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20877 if (dumpState.onTitlePrinted()) pw.println(); 20878 dumpDexoptStateLPr(pw, packageName); 20879 } 20880 20881 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20882 if (dumpState.onTitlePrinted()) pw.println(); 20883 dumpCompilerStatsLPr(pw, packageName); 20884 } 20885 20886 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20887 if (dumpState.onTitlePrinted()) pw.println(); 20888 dumpEnabledOverlaysLPr(pw); 20889 } 20890 20891 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20892 if (dumpState.onTitlePrinted()) pw.println(); 20893 mSettings.dumpReadMessagesLPr(pw, dumpState); 20894 20895 pw.println(); 20896 pw.println("Package warning messages:"); 20897 BufferedReader in = null; 20898 String line = null; 20899 try { 20900 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20901 while ((line = in.readLine()) != null) { 20902 if (line.contains("ignored: updated version")) continue; 20903 pw.println(line); 20904 } 20905 } catch (IOException ignored) { 20906 } finally { 20907 IoUtils.closeQuietly(in); 20908 } 20909 } 20910 20911 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20912 BufferedReader in = null; 20913 String line = null; 20914 try { 20915 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20916 while ((line = in.readLine()) != null) { 20917 if (line.contains("ignored: updated version")) continue; 20918 pw.print("msg,"); 20919 pw.println(line); 20920 } 20921 } catch (IOException ignored) { 20922 } finally { 20923 IoUtils.closeQuietly(in); 20924 } 20925 } 20926 } 20927 } 20928 20929 private void dumpProto(FileDescriptor fd) { 20930 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20931 20932 synchronized (mPackages) { 20933 final long requiredVerifierPackageToken = 20934 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20935 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20936 proto.write( 20937 PackageServiceDumpProto.PackageShortProto.UID, 20938 getPackageUid( 20939 mRequiredVerifierPackage, 20940 MATCH_DEBUG_TRIAGED_MISSING, 20941 UserHandle.USER_SYSTEM)); 20942 proto.end(requiredVerifierPackageToken); 20943 20944 if (mIntentFilterVerifierComponent != null) { 20945 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20946 final long verifierPackageToken = 20947 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20948 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20949 proto.write( 20950 PackageServiceDumpProto.PackageShortProto.UID, 20951 getPackageUid( 20952 verifierPackageName, 20953 MATCH_DEBUG_TRIAGED_MISSING, 20954 UserHandle.USER_SYSTEM)); 20955 proto.end(verifierPackageToken); 20956 } 20957 20958 dumpSharedLibrariesProto(proto); 20959 dumpFeaturesProto(proto); 20960 mSettings.dumpPackagesProto(proto); 20961 mSettings.dumpSharedUsersProto(proto); 20962 dumpMessagesProto(proto); 20963 } 20964 proto.flush(); 20965 } 20966 20967 private void dumpMessagesProto(ProtoOutputStream proto) { 20968 BufferedReader in = null; 20969 String line = null; 20970 try { 20971 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20972 while ((line = in.readLine()) != null) { 20973 if (line.contains("ignored: updated version")) continue; 20974 proto.write(PackageServiceDumpProto.MESSAGES, line); 20975 } 20976 } catch (IOException ignored) { 20977 } finally { 20978 IoUtils.closeQuietly(in); 20979 } 20980 } 20981 20982 private void dumpFeaturesProto(ProtoOutputStream proto) { 20983 synchronized (mAvailableFeatures) { 20984 final int count = mAvailableFeatures.size(); 20985 for (int i = 0; i < count; i++) { 20986 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20987 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20988 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20989 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20990 proto.end(featureToken); 20991 } 20992 } 20993 } 20994 20995 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20996 final int count = mSharedLibraries.size(); 20997 for (int i = 0; i < count; i++) { 20998 final String libName = mSharedLibraries.keyAt(i); 20999 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21000 if (versionedLib == null) { 21001 continue; 21002 } 21003 final int versionCount = versionedLib.size(); 21004 for (int j = 0; j < versionCount; j++) { 21005 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21006 final long sharedLibraryToken = 21007 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21008 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21009 final boolean isJar = (libEntry.path != null); 21010 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21011 if (isJar) { 21012 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21013 } else { 21014 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21015 } 21016 proto.end(sharedLibraryToken); 21017 } 21018 } 21019 } 21020 21021 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21022 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21023 ipw.println(); 21024 ipw.println("Dexopt state:"); 21025 ipw.increaseIndent(); 21026 Collection<PackageParser.Package> packages = null; 21027 if (packageName != null) { 21028 PackageParser.Package targetPackage = mPackages.get(packageName); 21029 if (targetPackage != null) { 21030 packages = Collections.singletonList(targetPackage); 21031 } else { 21032 ipw.println("Unable to find package: " + packageName); 21033 return; 21034 } 21035 } else { 21036 packages = mPackages.values(); 21037 } 21038 21039 for (PackageParser.Package pkg : packages) { 21040 ipw.println("[" + pkg.packageName + "]"); 21041 ipw.increaseIndent(); 21042 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21043 ipw.decreaseIndent(); 21044 } 21045 } 21046 21047 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21048 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21049 ipw.println(); 21050 ipw.println("Compiler stats:"); 21051 ipw.increaseIndent(); 21052 Collection<PackageParser.Package> packages = null; 21053 if (packageName != null) { 21054 PackageParser.Package targetPackage = mPackages.get(packageName); 21055 if (targetPackage != null) { 21056 packages = Collections.singletonList(targetPackage); 21057 } else { 21058 ipw.println("Unable to find package: " + packageName); 21059 return; 21060 } 21061 } else { 21062 packages = mPackages.values(); 21063 } 21064 21065 for (PackageParser.Package pkg : packages) { 21066 ipw.println("[" + pkg.packageName + "]"); 21067 ipw.increaseIndent(); 21068 21069 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21070 if (stats == null) { 21071 ipw.println("(No recorded stats)"); 21072 } else { 21073 stats.dump(ipw); 21074 } 21075 ipw.decreaseIndent(); 21076 } 21077 } 21078 21079 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21080 pw.println("Enabled overlay paths:"); 21081 final int N = mEnabledOverlayPaths.size(); 21082 for (int i = 0; i < N; i++) { 21083 final int userId = mEnabledOverlayPaths.keyAt(i); 21084 pw.println(String.format(" User %d:", userId)); 21085 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21086 mEnabledOverlayPaths.valueAt(i); 21087 final int M = userSpecificOverlays.size(); 21088 for (int j = 0; j < M; j++) { 21089 final String targetPackageName = userSpecificOverlays.keyAt(j); 21090 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21091 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21092 } 21093 } 21094 } 21095 21096 private String dumpDomainString(String packageName) { 21097 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21098 .getList(); 21099 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21100 21101 ArraySet<String> result = new ArraySet<>(); 21102 if (iviList.size() > 0) { 21103 for (IntentFilterVerificationInfo ivi : iviList) { 21104 for (String host : ivi.getDomains()) { 21105 result.add(host); 21106 } 21107 } 21108 } 21109 if (filters != null && filters.size() > 0) { 21110 for (IntentFilter filter : filters) { 21111 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21112 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21113 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21114 result.addAll(filter.getHostsList()); 21115 } 21116 } 21117 } 21118 21119 StringBuilder sb = new StringBuilder(result.size() * 16); 21120 for (String domain : result) { 21121 if (sb.length() > 0) sb.append(" "); 21122 sb.append(domain); 21123 } 21124 return sb.toString(); 21125 } 21126 21127 // ------- apps on sdcard specific code ------- 21128 static final boolean DEBUG_SD_INSTALL = false; 21129 21130 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21131 21132 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21133 21134 private boolean mMediaMounted = false; 21135 21136 static String getEncryptKey() { 21137 try { 21138 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21139 SD_ENCRYPTION_KEYSTORE_NAME); 21140 if (sdEncKey == null) { 21141 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21142 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21143 if (sdEncKey == null) { 21144 Slog.e(TAG, "Failed to create encryption keys"); 21145 return null; 21146 } 21147 } 21148 return sdEncKey; 21149 } catch (NoSuchAlgorithmException nsae) { 21150 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21151 return null; 21152 } catch (IOException ioe) { 21153 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21154 return null; 21155 } 21156 } 21157 21158 /* 21159 * Update media status on PackageManager. 21160 */ 21161 @Override 21162 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21163 int callingUid = Binder.getCallingUid(); 21164 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21165 throw new SecurityException("Media status can only be updated by the system"); 21166 } 21167 // reader; this apparently protects mMediaMounted, but should probably 21168 // be a different lock in that case. 21169 synchronized (mPackages) { 21170 Log.i(TAG, "Updating external media status from " 21171 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21172 + (mediaStatus ? "mounted" : "unmounted")); 21173 if (DEBUG_SD_INSTALL) 21174 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21175 + ", mMediaMounted=" + mMediaMounted); 21176 if (mediaStatus == mMediaMounted) { 21177 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21178 : 0, -1); 21179 mHandler.sendMessage(msg); 21180 return; 21181 } 21182 mMediaMounted = mediaStatus; 21183 } 21184 // Queue up an async operation since the package installation may take a 21185 // little while. 21186 mHandler.post(new Runnable() { 21187 public void run() { 21188 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21189 } 21190 }); 21191 } 21192 21193 /** 21194 * Called by StorageManagerService when the initial ASECs to scan are available. 21195 * Should block until all the ASEC containers are finished being scanned. 21196 */ 21197 public void scanAvailableAsecs() { 21198 updateExternalMediaStatusInner(true, false, false); 21199 } 21200 21201 /* 21202 * Collect information of applications on external media, map them against 21203 * existing containers and update information based on current mount status. 21204 * Please note that we always have to report status if reportStatus has been 21205 * set to true especially when unloading packages. 21206 */ 21207 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21208 boolean externalStorage) { 21209 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21210 int[] uidArr = EmptyArray.INT; 21211 21212 final String[] list = PackageHelper.getSecureContainerList(); 21213 if (ArrayUtils.isEmpty(list)) { 21214 Log.i(TAG, "No secure containers found"); 21215 } else { 21216 // Process list of secure containers and categorize them 21217 // as active or stale based on their package internal state. 21218 21219 // reader 21220 synchronized (mPackages) { 21221 for (String cid : list) { 21222 // Leave stages untouched for now; installer service owns them 21223 if (PackageInstallerService.isStageName(cid)) continue; 21224 21225 if (DEBUG_SD_INSTALL) 21226 Log.i(TAG, "Processing container " + cid); 21227 String pkgName = getAsecPackageName(cid); 21228 if (pkgName == null) { 21229 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21230 continue; 21231 } 21232 if (DEBUG_SD_INSTALL) 21233 Log.i(TAG, "Looking for pkg : " + pkgName); 21234 21235 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21236 if (ps == null) { 21237 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21238 continue; 21239 } 21240 21241 /* 21242 * Skip packages that are not external if we're unmounting 21243 * external storage. 21244 */ 21245 if (externalStorage && !isMounted && !isExternal(ps)) { 21246 continue; 21247 } 21248 21249 final AsecInstallArgs args = new AsecInstallArgs(cid, 21250 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21251 // The package status is changed only if the code path 21252 // matches between settings and the container id. 21253 if (ps.codePathString != null 21254 && ps.codePathString.startsWith(args.getCodePath())) { 21255 if (DEBUG_SD_INSTALL) { 21256 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21257 + " at code path: " + ps.codePathString); 21258 } 21259 21260 // We do have a valid package installed on sdcard 21261 processCids.put(args, ps.codePathString); 21262 final int uid = ps.appId; 21263 if (uid != -1) { 21264 uidArr = ArrayUtils.appendInt(uidArr, uid); 21265 } 21266 } else { 21267 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21268 + ps.codePathString); 21269 } 21270 } 21271 } 21272 21273 Arrays.sort(uidArr); 21274 } 21275 21276 // Process packages with valid entries. 21277 if (isMounted) { 21278 if (DEBUG_SD_INSTALL) 21279 Log.i(TAG, "Loading packages"); 21280 loadMediaPackages(processCids, uidArr, externalStorage); 21281 startCleaningPackages(); 21282 mInstallerService.onSecureContainersAvailable(); 21283 } else { 21284 if (DEBUG_SD_INSTALL) 21285 Log.i(TAG, "Unloading packages"); 21286 unloadMediaPackages(processCids, uidArr, reportStatus); 21287 } 21288 } 21289 21290 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21291 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21292 final int size = infos.size(); 21293 final String[] packageNames = new String[size]; 21294 final int[] packageUids = new int[size]; 21295 for (int i = 0; i < size; i++) { 21296 final ApplicationInfo info = infos.get(i); 21297 packageNames[i] = info.packageName; 21298 packageUids[i] = info.uid; 21299 } 21300 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21301 finishedReceiver); 21302 } 21303 21304 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21305 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21306 sendResourcesChangedBroadcast(mediaStatus, replacing, 21307 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21308 } 21309 21310 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21311 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21312 int size = pkgList.length; 21313 if (size > 0) { 21314 // Send broadcasts here 21315 Bundle extras = new Bundle(); 21316 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21317 if (uidArr != null) { 21318 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21319 } 21320 if (replacing) { 21321 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21322 } 21323 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21324 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21325 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21326 } 21327 } 21328 21329 /* 21330 * Look at potentially valid container ids from processCids If package 21331 * information doesn't match the one on record or package scanning fails, 21332 * the cid is added to list of removeCids. We currently don't delete stale 21333 * containers. 21334 */ 21335 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21336 boolean externalStorage) { 21337 ArrayList<String> pkgList = new ArrayList<String>(); 21338 Set<AsecInstallArgs> keys = processCids.keySet(); 21339 21340 for (AsecInstallArgs args : keys) { 21341 String codePath = processCids.get(args); 21342 if (DEBUG_SD_INSTALL) 21343 Log.i(TAG, "Loading container : " + args.cid); 21344 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21345 try { 21346 // Make sure there are no container errors first. 21347 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21348 Slog.e(TAG, "Failed to mount cid : " + args.cid 21349 + " when installing from sdcard"); 21350 continue; 21351 } 21352 // Check code path here. 21353 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21354 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21355 + " does not match one in settings " + codePath); 21356 continue; 21357 } 21358 // Parse package 21359 int parseFlags = mDefParseFlags; 21360 if (args.isExternalAsec()) { 21361 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21362 } 21363 if (args.isFwdLocked()) { 21364 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21365 } 21366 21367 synchronized (mInstallLock) { 21368 PackageParser.Package pkg = null; 21369 try { 21370 // Sadly we don't know the package name yet to freeze it 21371 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21372 SCAN_IGNORE_FROZEN, 0, null); 21373 } catch (PackageManagerException e) { 21374 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21375 } 21376 // Scan the package 21377 if (pkg != null) { 21378 /* 21379 * TODO why is the lock being held? doPostInstall is 21380 * called in other places without the lock. This needs 21381 * to be straightened out. 21382 */ 21383 // writer 21384 synchronized (mPackages) { 21385 retCode = PackageManager.INSTALL_SUCCEEDED; 21386 pkgList.add(pkg.packageName); 21387 // Post process args 21388 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21389 pkg.applicationInfo.uid); 21390 } 21391 } else { 21392 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21393 } 21394 } 21395 21396 } finally { 21397 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21398 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21399 } 21400 } 21401 } 21402 // writer 21403 synchronized (mPackages) { 21404 // If the platform SDK has changed since the last time we booted, 21405 // we need to re-grant app permission to catch any new ones that 21406 // appear. This is really a hack, and means that apps can in some 21407 // cases get permissions that the user didn't initially explicitly 21408 // allow... it would be nice to have some better way to handle 21409 // this situation. 21410 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21411 : mSettings.getInternalVersion(); 21412 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21413 : StorageManager.UUID_PRIVATE_INTERNAL; 21414 21415 int updateFlags = UPDATE_PERMISSIONS_ALL; 21416 if (ver.sdkVersion != mSdkVersion) { 21417 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21418 + mSdkVersion + "; regranting permissions for external"); 21419 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21420 } 21421 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21422 21423 // Yay, everything is now upgraded 21424 ver.forceCurrent(); 21425 21426 // can downgrade to reader 21427 // Persist settings 21428 mSettings.writeLPr(); 21429 } 21430 // Send a broadcast to let everyone know we are done processing 21431 if (pkgList.size() > 0) { 21432 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21433 } 21434 } 21435 21436 /* 21437 * Utility method to unload a list of specified containers 21438 */ 21439 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21440 // Just unmount all valid containers. 21441 for (AsecInstallArgs arg : cidArgs) { 21442 synchronized (mInstallLock) { 21443 arg.doPostDeleteLI(false); 21444 } 21445 } 21446 } 21447 21448 /* 21449 * Unload packages mounted on external media. This involves deleting package 21450 * data from internal structures, sending broadcasts about disabled packages, 21451 * gc'ing to free up references, unmounting all secure containers 21452 * corresponding to packages on external media, and posting a 21453 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21454 * that we always have to post this message if status has been requested no 21455 * matter what. 21456 */ 21457 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21458 final boolean reportStatus) { 21459 if (DEBUG_SD_INSTALL) 21460 Log.i(TAG, "unloading media packages"); 21461 ArrayList<String> pkgList = new ArrayList<String>(); 21462 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21463 final Set<AsecInstallArgs> keys = processCids.keySet(); 21464 for (AsecInstallArgs args : keys) { 21465 String pkgName = args.getPackageName(); 21466 if (DEBUG_SD_INSTALL) 21467 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21468 // Delete package internally 21469 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21470 synchronized (mInstallLock) { 21471 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21472 final boolean res; 21473 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21474 "unloadMediaPackages")) { 21475 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21476 null); 21477 } 21478 if (res) { 21479 pkgList.add(pkgName); 21480 } else { 21481 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21482 failedList.add(args); 21483 } 21484 } 21485 } 21486 21487 // reader 21488 synchronized (mPackages) { 21489 // We didn't update the settings after removing each package; 21490 // write them now for all packages. 21491 mSettings.writeLPr(); 21492 } 21493 21494 // We have to absolutely send UPDATED_MEDIA_STATUS only 21495 // after confirming that all the receivers processed the ordered 21496 // broadcast when packages get disabled, force a gc to clean things up. 21497 // and unload all the containers. 21498 if (pkgList.size() > 0) { 21499 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21500 new IIntentReceiver.Stub() { 21501 public void performReceive(Intent intent, int resultCode, String data, 21502 Bundle extras, boolean ordered, boolean sticky, 21503 int sendingUser) throws RemoteException { 21504 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21505 reportStatus ? 1 : 0, 1, keys); 21506 mHandler.sendMessage(msg); 21507 } 21508 }); 21509 } else { 21510 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21511 keys); 21512 mHandler.sendMessage(msg); 21513 } 21514 } 21515 21516 private void loadPrivatePackages(final VolumeInfo vol) { 21517 mHandler.post(new Runnable() { 21518 @Override 21519 public void run() { 21520 loadPrivatePackagesInner(vol); 21521 } 21522 }); 21523 } 21524 21525 private void loadPrivatePackagesInner(VolumeInfo vol) { 21526 final String volumeUuid = vol.fsUuid; 21527 if (TextUtils.isEmpty(volumeUuid)) { 21528 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21529 return; 21530 } 21531 21532 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21533 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21534 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21535 21536 final VersionInfo ver; 21537 final List<PackageSetting> packages; 21538 synchronized (mPackages) { 21539 ver = mSettings.findOrCreateVersion(volumeUuid); 21540 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21541 } 21542 21543 for (PackageSetting ps : packages) { 21544 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21545 synchronized (mInstallLock) { 21546 final PackageParser.Package pkg; 21547 try { 21548 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21549 loaded.add(pkg.applicationInfo); 21550 21551 } catch (PackageManagerException e) { 21552 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21553 } 21554 21555 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21556 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21557 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21558 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21559 } 21560 } 21561 } 21562 21563 // Reconcile app data for all started/unlocked users 21564 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21565 final UserManager um = mContext.getSystemService(UserManager.class); 21566 UserManagerInternal umInternal = getUserManagerInternal(); 21567 for (UserInfo user : um.getUsers()) { 21568 final int flags; 21569 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21570 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21571 } else if (umInternal.isUserRunning(user.id)) { 21572 flags = StorageManager.FLAG_STORAGE_DE; 21573 } else { 21574 continue; 21575 } 21576 21577 try { 21578 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21579 synchronized (mInstallLock) { 21580 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21581 } 21582 } catch (IllegalStateException e) { 21583 // Device was probably ejected, and we'll process that event momentarily 21584 Slog.w(TAG, "Failed to prepare storage: " + e); 21585 } 21586 } 21587 21588 synchronized (mPackages) { 21589 int updateFlags = UPDATE_PERMISSIONS_ALL; 21590 if (ver.sdkVersion != mSdkVersion) { 21591 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21592 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21593 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21594 } 21595 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21596 21597 // Yay, everything is now upgraded 21598 ver.forceCurrent(); 21599 21600 mSettings.writeLPr(); 21601 } 21602 21603 for (PackageFreezer freezer : freezers) { 21604 freezer.close(); 21605 } 21606 21607 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21608 sendResourcesChangedBroadcast(true, false, loaded, null); 21609 } 21610 21611 private void unloadPrivatePackages(final VolumeInfo vol) { 21612 mHandler.post(new Runnable() { 21613 @Override 21614 public void run() { 21615 unloadPrivatePackagesInner(vol); 21616 } 21617 }); 21618 } 21619 21620 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21621 final String volumeUuid = vol.fsUuid; 21622 if (TextUtils.isEmpty(volumeUuid)) { 21623 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21624 return; 21625 } 21626 21627 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21628 synchronized (mInstallLock) { 21629 synchronized (mPackages) { 21630 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21631 for (PackageSetting ps : packages) { 21632 if (ps.pkg == null) continue; 21633 21634 final ApplicationInfo info = ps.pkg.applicationInfo; 21635 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21636 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21637 21638 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21639 "unloadPrivatePackagesInner")) { 21640 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21641 false, null)) { 21642 unloaded.add(info); 21643 } else { 21644 Slog.w(TAG, "Failed to unload " + ps.codePath); 21645 } 21646 } 21647 21648 // Try very hard to release any references to this package 21649 // so we don't risk the system server being killed due to 21650 // open FDs 21651 AttributeCache.instance().removePackage(ps.name); 21652 } 21653 21654 mSettings.writeLPr(); 21655 } 21656 } 21657 21658 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21659 sendResourcesChangedBroadcast(false, false, unloaded, null); 21660 21661 // Try very hard to release any references to this path so we don't risk 21662 // the system server being killed due to open FDs 21663 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21664 21665 for (int i = 0; i < 3; i++) { 21666 System.gc(); 21667 System.runFinalization(); 21668 } 21669 } 21670 21671 private void assertPackageKnown(String volumeUuid, String packageName) 21672 throws PackageManagerException { 21673 synchronized (mPackages) { 21674 // Normalize package name to handle renamed packages 21675 packageName = normalizePackageNameLPr(packageName); 21676 21677 final PackageSetting ps = mSettings.mPackages.get(packageName); 21678 if (ps == null) { 21679 throw new PackageManagerException("Package " + packageName + " is unknown"); 21680 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21681 throw new PackageManagerException( 21682 "Package " + packageName + " found on unknown volume " + volumeUuid 21683 + "; expected volume " + ps.volumeUuid); 21684 } 21685 } 21686 } 21687 21688 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21689 throws PackageManagerException { 21690 synchronized (mPackages) { 21691 // Normalize package name to handle renamed packages 21692 packageName = normalizePackageNameLPr(packageName); 21693 21694 final PackageSetting ps = mSettings.mPackages.get(packageName); 21695 if (ps == null) { 21696 throw new PackageManagerException("Package " + packageName + " is unknown"); 21697 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21698 throw new PackageManagerException( 21699 "Package " + packageName + " found on unknown volume " + volumeUuid 21700 + "; expected volume " + ps.volumeUuid); 21701 } else if (!ps.getInstalled(userId)) { 21702 throw new PackageManagerException( 21703 "Package " + packageName + " not installed for user " + userId); 21704 } 21705 } 21706 } 21707 21708 private List<String> collectAbsoluteCodePaths() { 21709 synchronized (mPackages) { 21710 List<String> codePaths = new ArrayList<>(); 21711 final int packageCount = mSettings.mPackages.size(); 21712 for (int i = 0; i < packageCount; i++) { 21713 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21714 codePaths.add(ps.codePath.getAbsolutePath()); 21715 } 21716 return codePaths; 21717 } 21718 } 21719 21720 /** 21721 * Examine all apps present on given mounted volume, and destroy apps that 21722 * aren't expected, either due to uninstallation or reinstallation on 21723 * another volume. 21724 */ 21725 private void reconcileApps(String volumeUuid) { 21726 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21727 List<File> filesToDelete = null; 21728 21729 final File[] files = FileUtils.listFilesOrEmpty( 21730 Environment.getDataAppDirectory(volumeUuid)); 21731 for (File file : files) { 21732 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21733 && !PackageInstallerService.isStageName(file.getName()); 21734 if (!isPackage) { 21735 // Ignore entries which are not packages 21736 continue; 21737 } 21738 21739 String absolutePath = file.getAbsolutePath(); 21740 21741 boolean pathValid = false; 21742 final int absoluteCodePathCount = absoluteCodePaths.size(); 21743 for (int i = 0; i < absoluteCodePathCount; i++) { 21744 String absoluteCodePath = absoluteCodePaths.get(i); 21745 if (absolutePath.startsWith(absoluteCodePath)) { 21746 pathValid = true; 21747 break; 21748 } 21749 } 21750 21751 if (!pathValid) { 21752 if (filesToDelete == null) { 21753 filesToDelete = new ArrayList<>(); 21754 } 21755 filesToDelete.add(file); 21756 } 21757 } 21758 21759 if (filesToDelete != null) { 21760 final int fileToDeleteCount = filesToDelete.size(); 21761 for (int i = 0; i < fileToDeleteCount; i++) { 21762 File fileToDelete = filesToDelete.get(i); 21763 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21764 synchronized (mInstallLock) { 21765 removeCodePathLI(fileToDelete); 21766 } 21767 } 21768 } 21769 } 21770 21771 /** 21772 * Reconcile all app data for the given user. 21773 * <p> 21774 * Verifies that directories exist and that ownership and labeling is 21775 * correct for all installed apps on all mounted volumes. 21776 */ 21777 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21778 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21779 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21780 final String volumeUuid = vol.getFsUuid(); 21781 synchronized (mInstallLock) { 21782 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21783 } 21784 } 21785 } 21786 21787 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21788 boolean migrateAppData) { 21789 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21790 } 21791 21792 /** 21793 * Reconcile all app data on given mounted volume. 21794 * <p> 21795 * Destroys app data that isn't expected, either due to uninstallation or 21796 * reinstallation on another volume. 21797 * <p> 21798 * Verifies that directories exist and that ownership and labeling is 21799 * correct for all installed apps. 21800 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21801 */ 21802 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21803 boolean migrateAppData, boolean onlyCoreApps) { 21804 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21805 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21806 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21807 21808 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21809 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21810 21811 // First look for stale data that doesn't belong, and check if things 21812 // have changed since we did our last restorecon 21813 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21814 if (StorageManager.isFileEncryptedNativeOrEmulated() 21815 && !StorageManager.isUserKeyUnlocked(userId)) { 21816 throw new RuntimeException( 21817 "Yikes, someone asked us to reconcile CE storage while " + userId 21818 + " was still locked; this would have caused massive data loss!"); 21819 } 21820 21821 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21822 for (File file : files) { 21823 final String packageName = file.getName(); 21824 try { 21825 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21826 } catch (PackageManagerException e) { 21827 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21828 try { 21829 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21830 StorageManager.FLAG_STORAGE_CE, 0); 21831 } catch (InstallerException e2) { 21832 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21833 } 21834 } 21835 } 21836 } 21837 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21838 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21839 for (File file : files) { 21840 final String packageName = file.getName(); 21841 try { 21842 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21843 } catch (PackageManagerException e) { 21844 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21845 try { 21846 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21847 StorageManager.FLAG_STORAGE_DE, 0); 21848 } catch (InstallerException e2) { 21849 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21850 } 21851 } 21852 } 21853 } 21854 21855 // Ensure that data directories are ready to roll for all packages 21856 // installed for this volume and user 21857 final List<PackageSetting> packages; 21858 synchronized (mPackages) { 21859 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21860 } 21861 int preparedCount = 0; 21862 for (PackageSetting ps : packages) { 21863 final String packageName = ps.name; 21864 if (ps.pkg == null) { 21865 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21866 // TODO: might be due to legacy ASEC apps; we should circle back 21867 // and reconcile again once they're scanned 21868 continue; 21869 } 21870 // Skip non-core apps if requested 21871 if (onlyCoreApps && !ps.pkg.coreApp) { 21872 result.add(packageName); 21873 continue; 21874 } 21875 21876 if (ps.getInstalled(userId)) { 21877 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21878 preparedCount++; 21879 } 21880 } 21881 21882 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21883 return result; 21884 } 21885 21886 /** 21887 * Prepare app data for the given app just after it was installed or 21888 * upgraded. This method carefully only touches users that it's installed 21889 * for, and it forces a restorecon to handle any seinfo changes. 21890 * <p> 21891 * Verifies that directories exist and that ownership and labeling is 21892 * correct for all installed apps. If there is an ownership mismatch, it 21893 * will try recovering system apps by wiping data; third-party app data is 21894 * left intact. 21895 * <p> 21896 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21897 */ 21898 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21899 final PackageSetting ps; 21900 synchronized (mPackages) { 21901 ps = mSettings.mPackages.get(pkg.packageName); 21902 mSettings.writeKernelMappingLPr(ps); 21903 } 21904 21905 final UserManager um = mContext.getSystemService(UserManager.class); 21906 UserManagerInternal umInternal = getUserManagerInternal(); 21907 for (UserInfo user : um.getUsers()) { 21908 final int flags; 21909 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21910 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21911 } else if (umInternal.isUserRunning(user.id)) { 21912 flags = StorageManager.FLAG_STORAGE_DE; 21913 } else { 21914 continue; 21915 } 21916 21917 if (ps.getInstalled(user.id)) { 21918 // TODO: when user data is locked, mark that we're still dirty 21919 prepareAppDataLIF(pkg, user.id, flags); 21920 } 21921 } 21922 } 21923 21924 /** 21925 * Prepare app data for the given app. 21926 * <p> 21927 * Verifies that directories exist and that ownership and labeling is 21928 * correct for all installed apps. If there is an ownership mismatch, this 21929 * will try recovering system apps by wiping data; third-party app data is 21930 * left intact. 21931 */ 21932 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21933 if (pkg == null) { 21934 Slog.wtf(TAG, "Package was null!", new Throwable()); 21935 return; 21936 } 21937 prepareAppDataLeafLIF(pkg, userId, flags); 21938 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21939 for (int i = 0; i < childCount; i++) { 21940 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21941 } 21942 } 21943 21944 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21945 boolean maybeMigrateAppData) { 21946 prepareAppDataLIF(pkg, userId, flags); 21947 21948 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21949 // We may have just shuffled around app data directories, so 21950 // prepare them one more time 21951 prepareAppDataLIF(pkg, userId, flags); 21952 } 21953 } 21954 21955 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21956 if (DEBUG_APP_DATA) { 21957 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21958 + Integer.toHexString(flags)); 21959 } 21960 21961 final String volumeUuid = pkg.volumeUuid; 21962 final String packageName = pkg.packageName; 21963 final ApplicationInfo app = pkg.applicationInfo; 21964 final int appId = UserHandle.getAppId(app.uid); 21965 21966 Preconditions.checkNotNull(app.seInfo); 21967 21968 long ceDataInode = -1; 21969 try { 21970 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21971 appId, app.seInfo, app.targetSdkVersion); 21972 } catch (InstallerException e) { 21973 if (app.isSystemApp()) { 21974 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21975 + ", but trying to recover: " + e); 21976 destroyAppDataLeafLIF(pkg, userId, flags); 21977 try { 21978 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21979 appId, app.seInfo, app.targetSdkVersion); 21980 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21981 } catch (InstallerException e2) { 21982 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21983 } 21984 } else { 21985 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21986 } 21987 } 21988 21989 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21990 // TODO: mark this structure as dirty so we persist it! 21991 synchronized (mPackages) { 21992 final PackageSetting ps = mSettings.mPackages.get(packageName); 21993 if (ps != null) { 21994 ps.setCeDataInode(ceDataInode, userId); 21995 } 21996 } 21997 } 21998 21999 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22000 } 22001 22002 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22003 if (pkg == null) { 22004 Slog.wtf(TAG, "Package was null!", new Throwable()); 22005 return; 22006 } 22007 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22008 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22009 for (int i = 0; i < childCount; i++) { 22010 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22011 } 22012 } 22013 22014 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22015 final String volumeUuid = pkg.volumeUuid; 22016 final String packageName = pkg.packageName; 22017 final ApplicationInfo app = pkg.applicationInfo; 22018 22019 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22020 // Create a native library symlink only if we have native libraries 22021 // and if the native libraries are 32 bit libraries. We do not provide 22022 // this symlink for 64 bit libraries. 22023 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22024 final String nativeLibPath = app.nativeLibraryDir; 22025 try { 22026 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22027 nativeLibPath, userId); 22028 } catch (InstallerException e) { 22029 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22030 } 22031 } 22032 } 22033 } 22034 22035 /** 22036 * For system apps on non-FBE devices, this method migrates any existing 22037 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22038 * requested by the app. 22039 */ 22040 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22041 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22042 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22043 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22044 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22045 try { 22046 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22047 storageTarget); 22048 } catch (InstallerException e) { 22049 logCriticalInfo(Log.WARN, 22050 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22051 } 22052 return true; 22053 } else { 22054 return false; 22055 } 22056 } 22057 22058 public PackageFreezer freezePackage(String packageName, String killReason) { 22059 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22060 } 22061 22062 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22063 return new PackageFreezer(packageName, userId, killReason); 22064 } 22065 22066 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22067 String killReason) { 22068 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22069 } 22070 22071 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22072 String killReason) { 22073 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22074 return new PackageFreezer(); 22075 } else { 22076 return freezePackage(packageName, userId, killReason); 22077 } 22078 } 22079 22080 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22081 String killReason) { 22082 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22083 } 22084 22085 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22086 String killReason) { 22087 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22088 return new PackageFreezer(); 22089 } else { 22090 return freezePackage(packageName, userId, killReason); 22091 } 22092 } 22093 22094 /** 22095 * Class that freezes and kills the given package upon creation, and 22096 * unfreezes it upon closing. This is typically used when doing surgery on 22097 * app code/data to prevent the app from running while you're working. 22098 */ 22099 private class PackageFreezer implements AutoCloseable { 22100 private final String mPackageName; 22101 private final PackageFreezer[] mChildren; 22102 22103 private final boolean mWeFroze; 22104 22105 private final AtomicBoolean mClosed = new AtomicBoolean(); 22106 private final CloseGuard mCloseGuard = CloseGuard.get(); 22107 22108 /** 22109 * Create and return a stub freezer that doesn't actually do anything, 22110 * typically used when someone requested 22111 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22112 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22113 */ 22114 public PackageFreezer() { 22115 mPackageName = null; 22116 mChildren = null; 22117 mWeFroze = false; 22118 mCloseGuard.open("close"); 22119 } 22120 22121 public PackageFreezer(String packageName, int userId, String killReason) { 22122 synchronized (mPackages) { 22123 mPackageName = packageName; 22124 mWeFroze = mFrozenPackages.add(mPackageName); 22125 22126 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22127 if (ps != null) { 22128 killApplication(ps.name, ps.appId, userId, killReason); 22129 } 22130 22131 final PackageParser.Package p = mPackages.get(packageName); 22132 if (p != null && p.childPackages != null) { 22133 final int N = p.childPackages.size(); 22134 mChildren = new PackageFreezer[N]; 22135 for (int i = 0; i < N; i++) { 22136 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22137 userId, killReason); 22138 } 22139 } else { 22140 mChildren = null; 22141 } 22142 } 22143 mCloseGuard.open("close"); 22144 } 22145 22146 @Override 22147 protected void finalize() throws Throwable { 22148 try { 22149 mCloseGuard.warnIfOpen(); 22150 close(); 22151 } finally { 22152 super.finalize(); 22153 } 22154 } 22155 22156 @Override 22157 public void close() { 22158 mCloseGuard.close(); 22159 if (mClosed.compareAndSet(false, true)) { 22160 synchronized (mPackages) { 22161 if (mWeFroze) { 22162 mFrozenPackages.remove(mPackageName); 22163 } 22164 22165 if (mChildren != null) { 22166 for (PackageFreezer freezer : mChildren) { 22167 freezer.close(); 22168 } 22169 } 22170 } 22171 } 22172 } 22173 } 22174 22175 /** 22176 * Verify that given package is currently frozen. 22177 */ 22178 private void checkPackageFrozen(String packageName) { 22179 synchronized (mPackages) { 22180 if (!mFrozenPackages.contains(packageName)) { 22181 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22182 } 22183 } 22184 } 22185 22186 @Override 22187 public int movePackage(final String packageName, final String volumeUuid) { 22188 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22189 22190 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22191 final int moveId = mNextMoveId.getAndIncrement(); 22192 mHandler.post(new Runnable() { 22193 @Override 22194 public void run() { 22195 try { 22196 movePackageInternal(packageName, volumeUuid, moveId, user); 22197 } catch (PackageManagerException e) { 22198 Slog.w(TAG, "Failed to move " + packageName, e); 22199 mMoveCallbacks.notifyStatusChanged(moveId, 22200 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22201 } 22202 } 22203 }); 22204 return moveId; 22205 } 22206 22207 private void movePackageInternal(final String packageName, final String volumeUuid, 22208 final int moveId, UserHandle user) throws PackageManagerException { 22209 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22210 final PackageManager pm = mContext.getPackageManager(); 22211 22212 final boolean currentAsec; 22213 final String currentVolumeUuid; 22214 final File codeFile; 22215 final String installerPackageName; 22216 final String packageAbiOverride; 22217 final int appId; 22218 final String seinfo; 22219 final String label; 22220 final int targetSdkVersion; 22221 final PackageFreezer freezer; 22222 final int[] installedUserIds; 22223 22224 // reader 22225 synchronized (mPackages) { 22226 final PackageParser.Package pkg = mPackages.get(packageName); 22227 final PackageSetting ps = mSettings.mPackages.get(packageName); 22228 if (pkg == null || ps == null) { 22229 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22230 } 22231 22232 if (pkg.applicationInfo.isSystemApp()) { 22233 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22234 "Cannot move system application"); 22235 } 22236 22237 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22238 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22239 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22240 if (isInternalStorage && !allow3rdPartyOnInternal) { 22241 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22242 "3rd party apps are not allowed on internal storage"); 22243 } 22244 22245 if (pkg.applicationInfo.isExternalAsec()) { 22246 currentAsec = true; 22247 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22248 } else if (pkg.applicationInfo.isForwardLocked()) { 22249 currentAsec = true; 22250 currentVolumeUuid = "forward_locked"; 22251 } else { 22252 currentAsec = false; 22253 currentVolumeUuid = ps.volumeUuid; 22254 22255 final File probe = new File(pkg.codePath); 22256 final File probeOat = new File(probe, "oat"); 22257 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22258 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22259 "Move only supported for modern cluster style installs"); 22260 } 22261 } 22262 22263 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22264 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22265 "Package already moved to " + volumeUuid); 22266 } 22267 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22268 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22269 "Device admin cannot be moved"); 22270 } 22271 22272 if (mFrozenPackages.contains(packageName)) { 22273 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22274 "Failed to move already frozen package"); 22275 } 22276 22277 codeFile = new File(pkg.codePath); 22278 installerPackageName = ps.installerPackageName; 22279 packageAbiOverride = ps.cpuAbiOverrideString; 22280 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22281 seinfo = pkg.applicationInfo.seInfo; 22282 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22283 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22284 freezer = freezePackage(packageName, "movePackageInternal"); 22285 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22286 } 22287 22288 final Bundle extras = new Bundle(); 22289 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22290 extras.putString(Intent.EXTRA_TITLE, label); 22291 mMoveCallbacks.notifyCreated(moveId, extras); 22292 22293 int installFlags; 22294 final boolean moveCompleteApp; 22295 final File measurePath; 22296 22297 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22298 installFlags = INSTALL_INTERNAL; 22299 moveCompleteApp = !currentAsec; 22300 measurePath = Environment.getDataAppDirectory(volumeUuid); 22301 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22302 installFlags = INSTALL_EXTERNAL; 22303 moveCompleteApp = false; 22304 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22305 } else { 22306 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22307 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22308 || !volume.isMountedWritable()) { 22309 freezer.close(); 22310 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22311 "Move location not mounted private volume"); 22312 } 22313 22314 Preconditions.checkState(!currentAsec); 22315 22316 installFlags = INSTALL_INTERNAL; 22317 moveCompleteApp = true; 22318 measurePath = Environment.getDataAppDirectory(volumeUuid); 22319 } 22320 22321 final PackageStats stats = new PackageStats(null, -1); 22322 synchronized (mInstaller) { 22323 for (int userId : installedUserIds) { 22324 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22325 freezer.close(); 22326 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22327 "Failed to measure package size"); 22328 } 22329 } 22330 } 22331 22332 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22333 + stats.dataSize); 22334 22335 final long startFreeBytes = measurePath.getFreeSpace(); 22336 final long sizeBytes; 22337 if (moveCompleteApp) { 22338 sizeBytes = stats.codeSize + stats.dataSize; 22339 } else { 22340 sizeBytes = stats.codeSize; 22341 } 22342 22343 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22344 freezer.close(); 22345 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22346 "Not enough free space to move"); 22347 } 22348 22349 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22350 22351 final CountDownLatch installedLatch = new CountDownLatch(1); 22352 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22353 @Override 22354 public void onUserActionRequired(Intent intent) throws RemoteException { 22355 throw new IllegalStateException(); 22356 } 22357 22358 @Override 22359 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22360 Bundle extras) throws RemoteException { 22361 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22362 + PackageManager.installStatusToString(returnCode, msg)); 22363 22364 installedLatch.countDown(); 22365 freezer.close(); 22366 22367 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22368 switch (status) { 22369 case PackageInstaller.STATUS_SUCCESS: 22370 mMoveCallbacks.notifyStatusChanged(moveId, 22371 PackageManager.MOVE_SUCCEEDED); 22372 break; 22373 case PackageInstaller.STATUS_FAILURE_STORAGE: 22374 mMoveCallbacks.notifyStatusChanged(moveId, 22375 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22376 break; 22377 default: 22378 mMoveCallbacks.notifyStatusChanged(moveId, 22379 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22380 break; 22381 } 22382 } 22383 }; 22384 22385 final MoveInfo move; 22386 if (moveCompleteApp) { 22387 // Kick off a thread to report progress estimates 22388 new Thread() { 22389 @Override 22390 public void run() { 22391 while (true) { 22392 try { 22393 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22394 break; 22395 } 22396 } catch (InterruptedException ignored) { 22397 } 22398 22399 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22400 final int progress = 10 + (int) MathUtils.constrain( 22401 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22402 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22403 } 22404 } 22405 }.start(); 22406 22407 final String dataAppName = codeFile.getName(); 22408 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22409 dataAppName, appId, seinfo, targetSdkVersion); 22410 } else { 22411 move = null; 22412 } 22413 22414 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22415 22416 final Message msg = mHandler.obtainMessage(INIT_COPY); 22417 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22418 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22419 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22420 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22421 PackageManager.INSTALL_REASON_UNKNOWN); 22422 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22423 msg.obj = params; 22424 22425 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22426 System.identityHashCode(msg.obj)); 22427 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22428 System.identityHashCode(msg.obj)); 22429 22430 mHandler.sendMessage(msg); 22431 } 22432 22433 @Override 22434 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22435 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22436 22437 final int realMoveId = mNextMoveId.getAndIncrement(); 22438 final Bundle extras = new Bundle(); 22439 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22440 mMoveCallbacks.notifyCreated(realMoveId, extras); 22441 22442 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22443 @Override 22444 public void onCreated(int moveId, Bundle extras) { 22445 // Ignored 22446 } 22447 22448 @Override 22449 public void onStatusChanged(int moveId, int status, long estMillis) { 22450 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22451 } 22452 }; 22453 22454 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22455 storage.setPrimaryStorageUuid(volumeUuid, callback); 22456 return realMoveId; 22457 } 22458 22459 @Override 22460 public int getMoveStatus(int moveId) { 22461 mContext.enforceCallingOrSelfPermission( 22462 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22463 return mMoveCallbacks.mLastStatus.get(moveId); 22464 } 22465 22466 @Override 22467 public void registerMoveCallback(IPackageMoveObserver callback) { 22468 mContext.enforceCallingOrSelfPermission( 22469 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22470 mMoveCallbacks.register(callback); 22471 } 22472 22473 @Override 22474 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22475 mContext.enforceCallingOrSelfPermission( 22476 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22477 mMoveCallbacks.unregister(callback); 22478 } 22479 22480 @Override 22481 public boolean setInstallLocation(int loc) { 22482 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22483 null); 22484 if (getInstallLocation() == loc) { 22485 return true; 22486 } 22487 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22488 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22489 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22490 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22491 return true; 22492 } 22493 return false; 22494 } 22495 22496 @Override 22497 public int getInstallLocation() { 22498 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22499 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22500 PackageHelper.APP_INSTALL_AUTO); 22501 } 22502 22503 /** Called by UserManagerService */ 22504 void cleanUpUser(UserManagerService userManager, int userHandle) { 22505 synchronized (mPackages) { 22506 mDirtyUsers.remove(userHandle); 22507 mUserNeedsBadging.delete(userHandle); 22508 mSettings.removeUserLPw(userHandle); 22509 mPendingBroadcasts.remove(userHandle); 22510 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22511 removeUnusedPackagesLPw(userManager, userHandle); 22512 } 22513 } 22514 22515 /** 22516 * We're removing userHandle and would like to remove any downloaded packages 22517 * that are no longer in use by any other user. 22518 * @param userHandle the user being removed 22519 */ 22520 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22521 final boolean DEBUG_CLEAN_APKS = false; 22522 int [] users = userManager.getUserIds(); 22523 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22524 while (psit.hasNext()) { 22525 PackageSetting ps = psit.next(); 22526 if (ps.pkg == null) { 22527 continue; 22528 } 22529 final String packageName = ps.pkg.packageName; 22530 // Skip over if system app 22531 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22532 continue; 22533 } 22534 if (DEBUG_CLEAN_APKS) { 22535 Slog.i(TAG, "Checking package " + packageName); 22536 } 22537 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22538 if (keep) { 22539 if (DEBUG_CLEAN_APKS) { 22540 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22541 } 22542 } else { 22543 for (int i = 0; i < users.length; i++) { 22544 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22545 keep = true; 22546 if (DEBUG_CLEAN_APKS) { 22547 Slog.i(TAG, " Keeping package " + packageName + " for user " 22548 + users[i]); 22549 } 22550 break; 22551 } 22552 } 22553 } 22554 if (!keep) { 22555 if (DEBUG_CLEAN_APKS) { 22556 Slog.i(TAG, " Removing package " + packageName); 22557 } 22558 mHandler.post(new Runnable() { 22559 public void run() { 22560 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22561 userHandle, 0); 22562 } //end run 22563 }); 22564 } 22565 } 22566 } 22567 22568 /** Called by UserManagerService */ 22569 void createNewUser(int userId, String[] disallowedPackages) { 22570 synchronized (mInstallLock) { 22571 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22572 } 22573 synchronized (mPackages) { 22574 scheduleWritePackageRestrictionsLocked(userId); 22575 scheduleWritePackageListLocked(userId); 22576 applyFactoryDefaultBrowserLPw(userId); 22577 primeDomainVerificationsLPw(userId); 22578 } 22579 } 22580 22581 void onNewUserCreated(final int userId) { 22582 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22583 // If permission review for legacy apps is required, we represent 22584 // dagerous permissions for such apps as always granted runtime 22585 // permissions to keep per user flag state whether review is needed. 22586 // Hence, if a new user is added we have to propagate dangerous 22587 // permission grants for these legacy apps. 22588 if (mPermissionReviewRequired) { 22589 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22590 | UPDATE_PERMISSIONS_REPLACE_ALL); 22591 } 22592 } 22593 22594 @Override 22595 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22596 mContext.enforceCallingOrSelfPermission( 22597 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22598 "Only package verification agents can read the verifier device identity"); 22599 22600 synchronized (mPackages) { 22601 return mSettings.getVerifierDeviceIdentityLPw(); 22602 } 22603 } 22604 22605 @Override 22606 public void setPermissionEnforced(String permission, boolean enforced) { 22607 // TODO: Now that we no longer change GID for storage, this should to away. 22608 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22609 "setPermissionEnforced"); 22610 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22611 synchronized (mPackages) { 22612 if (mSettings.mReadExternalStorageEnforced == null 22613 || mSettings.mReadExternalStorageEnforced != enforced) { 22614 mSettings.mReadExternalStorageEnforced = enforced; 22615 mSettings.writeLPr(); 22616 } 22617 } 22618 // kill any non-foreground processes so we restart them and 22619 // grant/revoke the GID. 22620 final IActivityManager am = ActivityManager.getService(); 22621 if (am != null) { 22622 final long token = Binder.clearCallingIdentity(); 22623 try { 22624 am.killProcessesBelowForeground("setPermissionEnforcement"); 22625 } catch (RemoteException e) { 22626 } finally { 22627 Binder.restoreCallingIdentity(token); 22628 } 22629 } 22630 } else { 22631 throw new IllegalArgumentException("No selective enforcement for " + permission); 22632 } 22633 } 22634 22635 @Override 22636 @Deprecated 22637 public boolean isPermissionEnforced(String permission) { 22638 return true; 22639 } 22640 22641 @Override 22642 public boolean isStorageLow() { 22643 final long token = Binder.clearCallingIdentity(); 22644 try { 22645 final DeviceStorageMonitorInternal 22646 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22647 if (dsm != null) { 22648 return dsm.isMemoryLow(); 22649 } else { 22650 return false; 22651 } 22652 } finally { 22653 Binder.restoreCallingIdentity(token); 22654 } 22655 } 22656 22657 @Override 22658 public IPackageInstaller getPackageInstaller() { 22659 return mInstallerService; 22660 } 22661 22662 private boolean userNeedsBadging(int userId) { 22663 int index = mUserNeedsBadging.indexOfKey(userId); 22664 if (index < 0) { 22665 final UserInfo userInfo; 22666 final long token = Binder.clearCallingIdentity(); 22667 try { 22668 userInfo = sUserManager.getUserInfo(userId); 22669 } finally { 22670 Binder.restoreCallingIdentity(token); 22671 } 22672 final boolean b; 22673 if (userInfo != null && userInfo.isManagedProfile()) { 22674 b = true; 22675 } else { 22676 b = false; 22677 } 22678 mUserNeedsBadging.put(userId, b); 22679 return b; 22680 } 22681 return mUserNeedsBadging.valueAt(index); 22682 } 22683 22684 @Override 22685 public KeySet getKeySetByAlias(String packageName, String alias) { 22686 if (packageName == null || alias == null) { 22687 return null; 22688 } 22689 synchronized(mPackages) { 22690 final PackageParser.Package pkg = mPackages.get(packageName); 22691 if (pkg == null) { 22692 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22693 throw new IllegalArgumentException("Unknown package: " + packageName); 22694 } 22695 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22696 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22697 } 22698 } 22699 22700 @Override 22701 public KeySet getSigningKeySet(String packageName) { 22702 if (packageName == null) { 22703 return null; 22704 } 22705 synchronized(mPackages) { 22706 final PackageParser.Package pkg = mPackages.get(packageName); 22707 if (pkg == null) { 22708 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22709 throw new IllegalArgumentException("Unknown package: " + packageName); 22710 } 22711 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22712 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22713 throw new SecurityException("May not access signing KeySet of other apps."); 22714 } 22715 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22716 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22717 } 22718 } 22719 22720 @Override 22721 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22722 if (packageName == null || ks == null) { 22723 return false; 22724 } 22725 synchronized(mPackages) { 22726 final PackageParser.Package pkg = mPackages.get(packageName); 22727 if (pkg == null) { 22728 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22729 throw new IllegalArgumentException("Unknown package: " + packageName); 22730 } 22731 IBinder ksh = ks.getToken(); 22732 if (ksh instanceof KeySetHandle) { 22733 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22734 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22735 } 22736 return false; 22737 } 22738 } 22739 22740 @Override 22741 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22742 if (packageName == null || ks == null) { 22743 return false; 22744 } 22745 synchronized(mPackages) { 22746 final PackageParser.Package pkg = mPackages.get(packageName); 22747 if (pkg == null) { 22748 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22749 throw new IllegalArgumentException("Unknown package: " + packageName); 22750 } 22751 IBinder ksh = ks.getToken(); 22752 if (ksh instanceof KeySetHandle) { 22753 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22754 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22755 } 22756 return false; 22757 } 22758 } 22759 22760 private void deletePackageIfUnusedLPr(final String packageName) { 22761 PackageSetting ps = mSettings.mPackages.get(packageName); 22762 if (ps == null) { 22763 return; 22764 } 22765 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22766 // TODO Implement atomic delete if package is unused 22767 // It is currently possible that the package will be deleted even if it is installed 22768 // after this method returns. 22769 mHandler.post(new Runnable() { 22770 public void run() { 22771 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22772 0, PackageManager.DELETE_ALL_USERS); 22773 } 22774 }); 22775 } 22776 } 22777 22778 /** 22779 * Check and throw if the given before/after packages would be considered a 22780 * downgrade. 22781 */ 22782 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22783 throws PackageManagerException { 22784 if (after.versionCode < before.mVersionCode) { 22785 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22786 "Update version code " + after.versionCode + " is older than current " 22787 + before.mVersionCode); 22788 } else if (after.versionCode == before.mVersionCode) { 22789 if (after.baseRevisionCode < before.baseRevisionCode) { 22790 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22791 "Update base revision code " + after.baseRevisionCode 22792 + " is older than current " + before.baseRevisionCode); 22793 } 22794 22795 if (!ArrayUtils.isEmpty(after.splitNames)) { 22796 for (int i = 0; i < after.splitNames.length; i++) { 22797 final String splitName = after.splitNames[i]; 22798 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22799 if (j != -1) { 22800 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22801 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22802 "Update split " + splitName + " revision code " 22803 + after.splitRevisionCodes[i] + " is older than current " 22804 + before.splitRevisionCodes[j]); 22805 } 22806 } 22807 } 22808 } 22809 } 22810 } 22811 22812 private static class MoveCallbacks extends Handler { 22813 private static final int MSG_CREATED = 1; 22814 private static final int MSG_STATUS_CHANGED = 2; 22815 22816 private final RemoteCallbackList<IPackageMoveObserver> 22817 mCallbacks = new RemoteCallbackList<>(); 22818 22819 private final SparseIntArray mLastStatus = new SparseIntArray(); 22820 22821 public MoveCallbacks(Looper looper) { 22822 super(looper); 22823 } 22824 22825 public void register(IPackageMoveObserver callback) { 22826 mCallbacks.register(callback); 22827 } 22828 22829 public void unregister(IPackageMoveObserver callback) { 22830 mCallbacks.unregister(callback); 22831 } 22832 22833 @Override 22834 public void handleMessage(Message msg) { 22835 final SomeArgs args = (SomeArgs) msg.obj; 22836 final int n = mCallbacks.beginBroadcast(); 22837 for (int i = 0; i < n; i++) { 22838 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22839 try { 22840 invokeCallback(callback, msg.what, args); 22841 } catch (RemoteException ignored) { 22842 } 22843 } 22844 mCallbacks.finishBroadcast(); 22845 args.recycle(); 22846 } 22847 22848 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22849 throws RemoteException { 22850 switch (what) { 22851 case MSG_CREATED: { 22852 callback.onCreated(args.argi1, (Bundle) args.arg2); 22853 break; 22854 } 22855 case MSG_STATUS_CHANGED: { 22856 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22857 break; 22858 } 22859 } 22860 } 22861 22862 private void notifyCreated(int moveId, Bundle extras) { 22863 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22864 22865 final SomeArgs args = SomeArgs.obtain(); 22866 args.argi1 = moveId; 22867 args.arg2 = extras; 22868 obtainMessage(MSG_CREATED, args).sendToTarget(); 22869 } 22870 22871 private void notifyStatusChanged(int moveId, int status) { 22872 notifyStatusChanged(moveId, status, -1); 22873 } 22874 22875 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22876 Slog.v(TAG, "Move " + moveId + " status " + status); 22877 22878 final SomeArgs args = SomeArgs.obtain(); 22879 args.argi1 = moveId; 22880 args.argi2 = status; 22881 args.arg3 = estMillis; 22882 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22883 22884 synchronized (mLastStatus) { 22885 mLastStatus.put(moveId, status); 22886 } 22887 } 22888 } 22889 22890 private final static class OnPermissionChangeListeners extends Handler { 22891 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22892 22893 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22894 new RemoteCallbackList<>(); 22895 22896 public OnPermissionChangeListeners(Looper looper) { 22897 super(looper); 22898 } 22899 22900 @Override 22901 public void handleMessage(Message msg) { 22902 switch (msg.what) { 22903 case MSG_ON_PERMISSIONS_CHANGED: { 22904 final int uid = msg.arg1; 22905 handleOnPermissionsChanged(uid); 22906 } break; 22907 } 22908 } 22909 22910 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22911 mPermissionListeners.register(listener); 22912 22913 } 22914 22915 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22916 mPermissionListeners.unregister(listener); 22917 } 22918 22919 public void onPermissionsChanged(int uid) { 22920 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22921 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22922 } 22923 } 22924 22925 private void handleOnPermissionsChanged(int uid) { 22926 final int count = mPermissionListeners.beginBroadcast(); 22927 try { 22928 for (int i = 0; i < count; i++) { 22929 IOnPermissionsChangeListener callback = mPermissionListeners 22930 .getBroadcastItem(i); 22931 try { 22932 callback.onPermissionsChanged(uid); 22933 } catch (RemoteException e) { 22934 Log.e(TAG, "Permission listener is dead", e); 22935 } 22936 } 22937 } finally { 22938 mPermissionListeners.finishBroadcast(); 22939 } 22940 } 22941 } 22942 22943 private class PackageManagerInternalImpl extends PackageManagerInternal { 22944 @Override 22945 public void setLocationPackagesProvider(PackagesProvider provider) { 22946 synchronized (mPackages) { 22947 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22948 } 22949 } 22950 22951 @Override 22952 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22953 synchronized (mPackages) { 22954 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22955 } 22956 } 22957 22958 @Override 22959 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22960 synchronized (mPackages) { 22961 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22962 } 22963 } 22964 22965 @Override 22966 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22967 synchronized (mPackages) { 22968 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22969 } 22970 } 22971 22972 @Override 22973 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22974 synchronized (mPackages) { 22975 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22976 } 22977 } 22978 22979 @Override 22980 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22981 synchronized (mPackages) { 22982 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22983 } 22984 } 22985 22986 @Override 22987 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22988 synchronized (mPackages) { 22989 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22990 packageName, userId); 22991 } 22992 } 22993 22994 @Override 22995 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22996 synchronized (mPackages) { 22997 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22998 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22999 packageName, userId); 23000 } 23001 } 23002 23003 @Override 23004 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23005 synchronized (mPackages) { 23006 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23007 packageName, userId); 23008 } 23009 } 23010 23011 @Override 23012 public void setKeepUninstalledPackages(final List<String> packageList) { 23013 Preconditions.checkNotNull(packageList); 23014 List<String> removedFromList = null; 23015 synchronized (mPackages) { 23016 if (mKeepUninstalledPackages != null) { 23017 final int packagesCount = mKeepUninstalledPackages.size(); 23018 for (int i = 0; i < packagesCount; i++) { 23019 String oldPackage = mKeepUninstalledPackages.get(i); 23020 if (packageList != null && packageList.contains(oldPackage)) { 23021 continue; 23022 } 23023 if (removedFromList == null) { 23024 removedFromList = new ArrayList<>(); 23025 } 23026 removedFromList.add(oldPackage); 23027 } 23028 } 23029 mKeepUninstalledPackages = new ArrayList<>(packageList); 23030 if (removedFromList != null) { 23031 final int removedCount = removedFromList.size(); 23032 for (int i = 0; i < removedCount; i++) { 23033 deletePackageIfUnusedLPr(removedFromList.get(i)); 23034 } 23035 } 23036 } 23037 } 23038 23039 @Override 23040 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23041 synchronized (mPackages) { 23042 // If we do not support permission review, done. 23043 if (!mPermissionReviewRequired) { 23044 return false; 23045 } 23046 23047 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23048 if (packageSetting == null) { 23049 return false; 23050 } 23051 23052 // Permission review applies only to apps not supporting the new permission model. 23053 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23054 return false; 23055 } 23056 23057 // Legacy apps have the permission and get user consent on launch. 23058 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23059 return permissionsState.isPermissionReviewRequired(userId); 23060 } 23061 } 23062 23063 @Override 23064 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23065 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23066 } 23067 23068 @Override 23069 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23070 int userId) { 23071 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23072 } 23073 23074 @Override 23075 public void setDeviceAndProfileOwnerPackages( 23076 int deviceOwnerUserId, String deviceOwnerPackage, 23077 SparseArray<String> profileOwnerPackages) { 23078 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23079 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23080 } 23081 23082 @Override 23083 public boolean isPackageDataProtected(int userId, String packageName) { 23084 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23085 } 23086 23087 @Override 23088 public boolean isPackageEphemeral(int userId, String packageName) { 23089 synchronized (mPackages) { 23090 final PackageSetting ps = mSettings.mPackages.get(packageName); 23091 return ps != null ? ps.getInstantApp(userId) : false; 23092 } 23093 } 23094 23095 @Override 23096 public boolean wasPackageEverLaunched(String packageName, int userId) { 23097 synchronized (mPackages) { 23098 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23099 } 23100 } 23101 23102 @Override 23103 public void grantRuntimePermission(String packageName, String name, int userId, 23104 boolean overridePolicy) { 23105 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23106 overridePolicy); 23107 } 23108 23109 @Override 23110 public void revokeRuntimePermission(String packageName, String name, int userId, 23111 boolean overridePolicy) { 23112 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23113 overridePolicy); 23114 } 23115 23116 @Override 23117 public String getNameForUid(int uid) { 23118 return PackageManagerService.this.getNameForUid(uid); 23119 } 23120 23121 @Override 23122 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23123 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23124 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23125 responseObj, origIntent, resolvedType, callingPackage, userId); 23126 } 23127 23128 @Override 23129 public void grantEphemeralAccess(int userId, Intent intent, 23130 int targetAppId, int ephemeralAppId) { 23131 synchronized (mPackages) { 23132 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23133 targetAppId, ephemeralAppId); 23134 } 23135 } 23136 23137 @Override 23138 public void pruneInstantApps() { 23139 synchronized (mPackages) { 23140 mInstantAppRegistry.pruneInstantAppsLPw(); 23141 } 23142 } 23143 23144 @Override 23145 public String getSetupWizardPackageName() { 23146 return mSetupWizardPackage; 23147 } 23148 23149 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23150 if (policy != null) { 23151 mExternalSourcesPolicy = policy; 23152 } 23153 } 23154 23155 @Override 23156 public boolean isPackagePersistent(String packageName) { 23157 synchronized (mPackages) { 23158 PackageParser.Package pkg = mPackages.get(packageName); 23159 return pkg != null 23160 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23161 | ApplicationInfo.FLAG_PERSISTENT)) == 23162 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23163 : false; 23164 } 23165 } 23166 23167 @Override 23168 public List<PackageInfo> getOverlayPackages(int userId) { 23169 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23170 synchronized (mPackages) { 23171 for (PackageParser.Package p : mPackages.values()) { 23172 if (p.mOverlayTarget != null) { 23173 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23174 if (pkg != null) { 23175 overlayPackages.add(pkg); 23176 } 23177 } 23178 } 23179 } 23180 return overlayPackages; 23181 } 23182 23183 @Override 23184 public List<String> getTargetPackageNames(int userId) { 23185 List<String> targetPackages = new ArrayList<>(); 23186 synchronized (mPackages) { 23187 for (PackageParser.Package p : mPackages.values()) { 23188 if (p.mOverlayTarget == null) { 23189 targetPackages.add(p.packageName); 23190 } 23191 } 23192 } 23193 return targetPackages; 23194 } 23195 23196 @Override 23197 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23198 @Nullable List<String> overlayPackageNames) { 23199 synchronized (mPackages) { 23200 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23201 Slog.e(TAG, "failed to find package " + targetPackageName); 23202 return false; 23203 } 23204 23205 ArrayList<String> paths = null; 23206 if (overlayPackageNames != null) { 23207 final int N = overlayPackageNames.size(); 23208 paths = new ArrayList<>(N); 23209 for (int i = 0; i < N; i++) { 23210 final String packageName = overlayPackageNames.get(i); 23211 final PackageParser.Package pkg = mPackages.get(packageName); 23212 if (pkg == null) { 23213 Slog.e(TAG, "failed to find package " + packageName); 23214 return false; 23215 } 23216 paths.add(pkg.baseCodePath); 23217 } 23218 } 23219 23220 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23221 mEnabledOverlayPaths.get(userId); 23222 if (userSpecificOverlays == null) { 23223 userSpecificOverlays = new ArrayMap<>(); 23224 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23225 } 23226 23227 if (paths != null && paths.size() > 0) { 23228 userSpecificOverlays.put(targetPackageName, paths); 23229 } else { 23230 userSpecificOverlays.remove(targetPackageName); 23231 } 23232 return true; 23233 } 23234 } 23235 23236 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23237 int flags, int userId) { 23238 return resolveIntentInternal( 23239 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23240 } 23241 } 23242 23243 @Override 23244 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23245 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23246 synchronized (mPackages) { 23247 final long identity = Binder.clearCallingIdentity(); 23248 try { 23249 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23250 packageNames, userId); 23251 } finally { 23252 Binder.restoreCallingIdentity(identity); 23253 } 23254 } 23255 } 23256 23257 @Override 23258 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23259 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23260 synchronized (mPackages) { 23261 final long identity = Binder.clearCallingIdentity(); 23262 try { 23263 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23264 packageNames, userId); 23265 } finally { 23266 Binder.restoreCallingIdentity(identity); 23267 } 23268 } 23269 } 23270 23271 private static void enforceSystemOrPhoneCaller(String tag) { 23272 int callingUid = Binder.getCallingUid(); 23273 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23274 throw new SecurityException( 23275 "Cannot call " + tag + " from UID " + callingUid); 23276 } 23277 } 23278 23279 boolean isHistoricalPackageUsageAvailable() { 23280 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23281 } 23282 23283 /** 23284 * Return a <b>copy</b> of the collection of packages known to the package manager. 23285 * @return A copy of the values of mPackages. 23286 */ 23287 Collection<PackageParser.Package> getPackages() { 23288 synchronized (mPackages) { 23289 return new ArrayList<>(mPackages.values()); 23290 } 23291 } 23292 23293 /** 23294 * Logs process start information (including base APK hash) to the security log. 23295 * @hide 23296 */ 23297 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23298 String apkFile, int pid) { 23299 if (!SecurityLog.isLoggingEnabled()) { 23300 return; 23301 } 23302 Bundle data = new Bundle(); 23303 data.putLong("startTimestamp", System.currentTimeMillis()); 23304 data.putString("processName", processName); 23305 data.putInt("uid", uid); 23306 data.putString("seinfo", seinfo); 23307 data.putString("apkFile", apkFile); 23308 data.putInt("pid", pid); 23309 Message msg = mProcessLoggingHandler.obtainMessage( 23310 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23311 msg.setData(data); 23312 mProcessLoggingHandler.sendMessage(msg); 23313 } 23314 23315 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23316 return mCompilerStats.getPackageStats(pkgName); 23317 } 23318 23319 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23320 return getOrCreateCompilerPackageStats(pkg.packageName); 23321 } 23322 23323 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23324 return mCompilerStats.getOrCreatePackageStats(pkgName); 23325 } 23326 23327 public void deleteCompilerPackageStats(String pkgName) { 23328 mCompilerStats.deletePackageStats(pkgName); 23329 } 23330 23331 @Override 23332 public int getInstallReason(String packageName, int userId) { 23333 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23334 true /* requireFullPermission */, false /* checkShell */, 23335 "get install reason"); 23336 synchronized (mPackages) { 23337 final PackageSetting ps = mSettings.mPackages.get(packageName); 23338 if (ps != null) { 23339 return ps.getInstallReason(userId); 23340 } 23341 } 23342 return PackageManager.INSTALL_REASON_UNKNOWN; 23343 } 23344 23345 @Override 23346 public boolean canRequestPackageInstalls(String packageName, int userId) { 23347 int callingUid = Binder.getCallingUid(); 23348 int uid = getPackageUid(packageName, 0, userId); 23349 if (callingUid != uid && callingUid != Process.ROOT_UID 23350 && callingUid != Process.SYSTEM_UID) { 23351 throw new SecurityException( 23352 "Caller uid " + callingUid + " does not own package " + packageName); 23353 } 23354 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23355 if (info == null) { 23356 return false; 23357 } 23358 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23359 throw new UnsupportedOperationException( 23360 "Operation only supported on apps targeting Android O or higher"); 23361 } 23362 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23363 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23364 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23365 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23366 } 23367 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23368 return false; 23369 } 23370 if (mExternalSourcesPolicy != null) { 23371 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23372 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23373 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23374 } 23375 } 23376 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23377 } 23378} 23379