PackageManagerService.java revision 829ea130bf9c3bdea6143f2c46f8145a1549d294
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.INSTALL_PACKAGES; 21import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 22import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 23import static android.Manifest.permission.REQUEST_INSTALL_PACKAGES; 24import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 25import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 27import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 31import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 39import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 40import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 41import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 42import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 49import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 51import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 56import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 57import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 58import static android.content.pm.PackageManager.INSTALL_INTERNAL; 59import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 65import static android.content.pm.PackageManager.MATCH_ALL; 66import static android.content.pm.PackageManager.MATCH_ANY_USER; 67import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 68import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 70import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 71import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 72import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 73import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 74import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 75import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 76import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 77import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 78import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 79import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 80import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 81import static android.content.pm.PackageManager.PERMISSION_DENIED; 82import static android.content.pm.PackageManager.PERMISSION_GRANTED; 83import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 84import static android.content.pm.PackageParser.isApkFile; 85import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 86import static android.system.OsConstants.O_CREAT; 87import static android.system.OsConstants.O_RDWR; 88import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 89import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 90import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 91import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 92import static com.android.internal.util.ArrayUtils.appendInt; 93import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 94import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 95import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 96import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 97import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 98import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 99import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 100import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 102import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 103import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 104import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 105 106import android.Manifest; 107import android.annotation.NonNull; 108import android.annotation.Nullable; 109import android.app.ActivityManager; 110import android.app.AppOpsManager; 111import android.app.IActivityManager; 112import android.app.ResourcesManager; 113import android.app.admin.IDevicePolicyManager; 114import android.app.admin.SecurityLog; 115import android.app.backup.IBackupManager; 116import android.content.BroadcastReceiver; 117import android.content.ComponentName; 118import android.content.ContentResolver; 119import android.content.Context; 120import android.content.IIntentReceiver; 121import android.content.Intent; 122import android.content.IntentFilter; 123import android.content.IntentSender; 124import android.content.IntentSender.SendIntentException; 125import android.content.ServiceConnection; 126import android.content.pm.ActivityInfo; 127import android.content.pm.ApplicationInfo; 128import android.content.pm.AppsQueryHelper; 129import android.content.pm.ChangedPackages; 130import android.content.pm.ComponentInfo; 131import android.content.pm.InstantAppRequest; 132import android.content.pm.AuxiliaryResolveInfo; 133import android.content.pm.FallbackCategoryProvider; 134import android.content.pm.FeatureInfo; 135import android.content.pm.IOnPermissionsChangeListener; 136import android.content.pm.IPackageDataObserver; 137import android.content.pm.IPackageDeleteObserver; 138import android.content.pm.IPackageDeleteObserver2; 139import android.content.pm.IPackageInstallObserver2; 140import android.content.pm.IPackageInstaller; 141import android.content.pm.IPackageManager; 142import android.content.pm.IPackageMoveObserver; 143import android.content.pm.IPackageStatsObserver; 144import android.content.pm.InstantAppInfo; 145import android.content.pm.InstantAppResolveInfo; 146import android.content.pm.InstrumentationInfo; 147import android.content.pm.IntentFilterVerificationInfo; 148import android.content.pm.KeySet; 149import android.content.pm.PackageCleanItem; 150import android.content.pm.PackageInfo; 151import android.content.pm.PackageInfoLite; 152import android.content.pm.PackageInstaller; 153import android.content.pm.PackageManager; 154import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 155import android.content.pm.PackageManagerInternal; 156import android.content.pm.PackageParser; 157import android.content.pm.PackageParser.ActivityIntentInfo; 158import android.content.pm.PackageParser.PackageLite; 159import android.content.pm.PackageParser.PackageParserException; 160import android.content.pm.PackageStats; 161import android.content.pm.PackageUserState; 162import android.content.pm.ParceledListSlice; 163import android.content.pm.PermissionGroupInfo; 164import android.content.pm.PermissionInfo; 165import android.content.pm.ProviderInfo; 166import android.content.pm.ResolveInfo; 167import android.content.pm.SELinuxUtil; 168import android.content.pm.ServiceInfo; 169import android.content.pm.SharedLibraryInfo; 170import android.content.pm.Signature; 171import android.content.pm.UserInfo; 172import android.content.pm.VerifierDeviceIdentity; 173import android.content.pm.VerifierInfo; 174import android.content.pm.VersionedPackage; 175import android.content.res.Resources; 176import android.graphics.Bitmap; 177import android.hardware.display.DisplayManager; 178import android.net.Uri; 179import android.os.Binder; 180import android.os.Build; 181import android.os.Bundle; 182import android.os.Debug; 183import android.os.Environment; 184import android.os.Environment.UserEnvironment; 185import android.os.FileUtils; 186import android.os.Handler; 187import android.os.IBinder; 188import android.os.Looper; 189import android.os.Message; 190import android.os.Parcel; 191import android.os.ParcelFileDescriptor; 192import android.os.PatternMatcher; 193import android.os.Process; 194import android.os.RemoteCallbackList; 195import android.os.RemoteException; 196import android.os.ResultReceiver; 197import android.os.SELinux; 198import android.os.ServiceManager; 199import android.os.ShellCallback; 200import android.os.SystemClock; 201import android.os.SystemProperties; 202import android.os.Trace; 203import android.os.UserHandle; 204import android.os.UserManager; 205import android.os.UserManagerInternal; 206import android.os.storage.IStorageManager; 207import android.os.storage.StorageEventListener; 208import android.os.storage.StorageManager; 209import android.os.storage.StorageManagerInternal; 210import android.os.storage.VolumeInfo; 211import android.os.storage.VolumeRecord; 212import android.provider.Settings.Global; 213import android.provider.Settings.Secure; 214import android.security.KeyStore; 215import android.security.SystemKeyStore; 216import android.service.pm.PackageServiceDumpProto; 217import android.system.ErrnoException; 218import android.system.Os; 219import android.text.TextUtils; 220import android.text.format.DateUtils; 221import android.util.ArrayMap; 222import android.util.ArraySet; 223import android.util.Base64; 224import android.util.DisplayMetrics; 225import android.util.EventLog; 226import android.util.ExceptionUtils; 227import android.util.Log; 228import android.util.LogPrinter; 229import android.util.MathUtils; 230import android.util.PackageUtils; 231import android.util.Pair; 232import android.util.PrintStreamPrinter; 233import android.util.Slog; 234import android.util.SparseArray; 235import android.util.SparseBooleanArray; 236import android.util.SparseIntArray; 237import android.util.Xml; 238import android.util.jar.StrictJarFile; 239import android.util.proto.ProtoOutputStream; 240import android.view.Display; 241 242import com.android.internal.R; 243import com.android.internal.annotations.GuardedBy; 244import com.android.internal.app.IMediaContainerService; 245import com.android.internal.app.ResolverActivity; 246import com.android.internal.content.NativeLibraryHelper; 247import com.android.internal.content.PackageHelper; 248import com.android.internal.logging.MetricsLogger; 249import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 250import com.android.internal.os.IParcelFileDescriptorFactory; 251import com.android.internal.os.RoSystemProperties; 252import com.android.internal.os.SomeArgs; 253import com.android.internal.os.Zygote; 254import com.android.internal.telephony.CarrierAppUtils; 255import com.android.internal.util.ArrayUtils; 256import com.android.internal.util.ConcurrentUtils; 257import com.android.internal.util.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.DeviceIdleController; 264import com.android.server.EventLogTags; 265import com.android.server.FgThread; 266import com.android.server.IntentResolver; 267import com.android.server.LocalServices; 268import com.android.server.LockGuard; 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.BackgroundDexOptService; 275import com.android.server.pm.Installer.InstallerException; 276import com.android.server.pm.PermissionsState.PermissionState; 277import com.android.server.pm.Settings.DatabaseVersion; 278import com.android.server.pm.Settings.VersionInfo; 279import com.android.server.pm.dex.DexManager; 280import com.android.server.storage.DeviceStorageMonitorInternal; 281 282import dalvik.system.CloseGuard; 283import dalvik.system.DexFile; 284import dalvik.system.VMRuntime; 285 286import libcore.io.IoUtils; 287import libcore.util.EmptyArray; 288 289import org.xmlpull.v1.XmlPullParser; 290import org.xmlpull.v1.XmlPullParserException; 291import org.xmlpull.v1.XmlSerializer; 292 293import java.io.BufferedOutputStream; 294import java.io.BufferedReader; 295import java.io.ByteArrayInputStream; 296import java.io.ByteArrayOutputStream; 297import java.io.File; 298import java.io.FileDescriptor; 299import java.io.FileInputStream; 300import java.io.FileNotFoundException; 301import java.io.FileOutputStream; 302import java.io.FileReader; 303import java.io.FilenameFilter; 304import java.io.IOException; 305import java.io.PrintWriter; 306import java.nio.charset.StandardCharsets; 307import java.security.DigestInputStream; 308import java.security.MessageDigest; 309import java.security.NoSuchAlgorithmException; 310import java.security.PublicKey; 311import java.security.SecureRandom; 312import java.security.cert.Certificate; 313import java.security.cert.CertificateEncodingException; 314import java.security.cert.CertificateException; 315import java.text.SimpleDateFormat; 316import java.util.ArrayList; 317import java.util.Arrays; 318import java.util.Collection; 319import java.util.Collections; 320import java.util.Comparator; 321import java.util.Date; 322import java.util.HashMap; 323import java.util.HashSet; 324import java.util.Iterator; 325import java.util.List; 326import java.util.Map; 327import java.util.Objects; 328import java.util.Set; 329import java.util.concurrent.CountDownLatch; 330import java.util.concurrent.Future; 331import java.util.concurrent.TimeUnit; 332import java.util.concurrent.atomic.AtomicBoolean; 333import java.util.concurrent.atomic.AtomicInteger; 334 335/** 336 * Keep track of all those APKs everywhere. 337 * <p> 338 * Internally there are two important locks: 339 * <ul> 340 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 341 * and other related state. It is a fine-grained lock that should only be held 342 * momentarily, as it's one of the most contended locks in the system. 343 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 344 * operations typically involve heavy lifting of application data on disk. Since 345 * {@code installd} is single-threaded, and it's operations can often be slow, 346 * this lock should never be acquired while already holding {@link #mPackages}. 347 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 348 * holding {@link #mInstallLock}. 349 * </ul> 350 * Many internal methods rely on the caller to hold the appropriate locks, and 351 * this contract is expressed through method name suffixes: 352 * <ul> 353 * <li>fooLI(): the caller must hold {@link #mInstallLock} 354 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 355 * being modified must be frozen 356 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 357 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 358 * </ul> 359 * <p> 360 * Because this class is very central to the platform's security; please run all 361 * CTS and unit tests whenever making modifications: 362 * 363 * <pre> 364 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 365 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 366 * </pre> 367 */ 368public class PackageManagerService extends IPackageManager.Stub { 369 static final String TAG = "PackageManager"; 370 static final boolean DEBUG_SETTINGS = false; 371 static final boolean DEBUG_PREFERRED = false; 372 static final boolean DEBUG_UPGRADE = false; 373 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 374 private static final boolean DEBUG_BACKUP = false; 375 private static final boolean DEBUG_INSTALL = false; 376 private static final boolean DEBUG_REMOVE = false; 377 private static final boolean DEBUG_BROADCASTS = false; 378 private static final boolean DEBUG_SHOW_INFO = false; 379 private static final boolean DEBUG_PACKAGE_INFO = false; 380 private static final boolean DEBUG_INTENT_MATCHING = false; 381 private static final boolean DEBUG_PACKAGE_SCANNING = false; 382 private static final boolean DEBUG_VERIFY = false; 383 private static final boolean DEBUG_FILTERS = false; 384 385 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 386 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 387 // user, but by default initialize to this. 388 public static final boolean DEBUG_DEXOPT = false; 389 390 private static final boolean DEBUG_ABI_SELECTION = false; 391 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 392 private static final boolean DEBUG_TRIAGED_MISSING = false; 393 private static final boolean DEBUG_APP_DATA = false; 394 395 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 396 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 397 398 private static final boolean DISABLE_EPHEMERAL_APPS = false; 399 private static final boolean HIDE_EPHEMERAL_APIS = false; 400 401 private static final boolean ENABLE_FREE_CACHE_V2 = 402 SystemProperties.getBoolean("fw.free_cache_v2", true); 403 404 private static final int RADIO_UID = Process.PHONE_UID; 405 private static final int LOG_UID = Process.LOG_UID; 406 private static final int NFC_UID = Process.NFC_UID; 407 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 408 private static final int SHELL_UID = Process.SHELL_UID; 409 410 // Cap the size of permission trees that 3rd party apps can define 411 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 412 413 // Suffix used during package installation when copying/moving 414 // package apks to install directory. 415 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 416 417 static final int SCAN_NO_DEX = 1<<1; 418 static final int SCAN_FORCE_DEX = 1<<2; 419 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 420 static final int SCAN_NEW_INSTALL = 1<<4; 421 static final int SCAN_UPDATE_TIME = 1<<5; 422 static final int SCAN_BOOTING = 1<<6; 423 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 424 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 425 static final int SCAN_REPLACING = 1<<9; 426 static final int SCAN_REQUIRE_KNOWN = 1<<10; 427 static final int SCAN_MOVE = 1<<11; 428 static final int SCAN_INITIAL = 1<<12; 429 static final int SCAN_CHECK_ONLY = 1<<13; 430 static final int SCAN_DONT_KILL_APP = 1<<14; 431 static final int SCAN_IGNORE_FROZEN = 1<<15; 432 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 433 static final int SCAN_AS_INSTANT_APP = 1<<17; 434 static final int SCAN_AS_FULL_APP = 1<<18; 435 /** Should not be with the scan flags */ 436 static final int FLAGS_REMOVE_CHATTY = 1<<31; 437 438 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 439 440 private static final int[] EMPTY_INT_ARRAY = new int[0]; 441 442 /** 443 * Timeout (in milliseconds) after which the watchdog should declare that 444 * our handler thread is wedged. The usual default for such things is one 445 * minute but we sometimes do very lengthy I/O operations on this thread, 446 * such as installing multi-gigabyte applications, so ours needs to be longer. 447 */ 448 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 449 450 /** 451 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 452 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 453 * settings entry if available, otherwise we use the hardcoded default. If it's been 454 * more than this long since the last fstrim, we force one during the boot sequence. 455 * 456 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 457 * one gets run at the next available charging+idle time. This final mandatory 458 * no-fstrim check kicks in only of the other scheduling criteria is never met. 459 */ 460 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 461 462 /** 463 * Whether verification is enabled by default. 464 */ 465 private static final boolean DEFAULT_VERIFY_ENABLE = true; 466 467 /** 468 * The default maximum time to wait for the verification agent to return in 469 * milliseconds. 470 */ 471 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 472 473 /** 474 * The default response for package verification timeout. 475 * 476 * This can be either PackageManager.VERIFICATION_ALLOW or 477 * PackageManager.VERIFICATION_REJECT. 478 */ 479 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 480 481 static final String PLATFORM_PACKAGE_NAME = "android"; 482 483 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 484 485 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 486 DEFAULT_CONTAINER_PACKAGE, 487 "com.android.defcontainer.DefaultContainerService"); 488 489 private static final String KILL_APP_REASON_GIDS_CHANGED = 490 "permission grant or revoke changed gids"; 491 492 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 493 "permissions revoked"; 494 495 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 496 497 private static final String PACKAGE_SCHEME = "package"; 498 499 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 500 501 /** Permission grant: not grant the permission. */ 502 private static final int GRANT_DENIED = 1; 503 504 /** Permission grant: grant the permission as an install permission. */ 505 private static final int GRANT_INSTALL = 2; 506 507 /** Permission grant: grant the permission as a runtime one. */ 508 private static final int GRANT_RUNTIME = 3; 509 510 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 511 private static final int GRANT_UPGRADE = 4; 512 513 /** Canonical intent used to identify what counts as a "web browser" app */ 514 private static final Intent sBrowserIntent; 515 static { 516 sBrowserIntent = new Intent(); 517 sBrowserIntent.setAction(Intent.ACTION_VIEW); 518 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 519 sBrowserIntent.setData(Uri.parse("http:")); 520 } 521 522 /** 523 * The set of all protected actions [i.e. those actions for which a high priority 524 * intent filter is disallowed]. 525 */ 526 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 527 static { 528 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 529 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 531 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 532 } 533 534 // Compilation reasons. 535 public static final int REASON_FIRST_BOOT = 0; 536 public static final int REASON_BOOT = 1; 537 public static final int REASON_INSTALL = 2; 538 public static final int REASON_BACKGROUND_DEXOPT = 3; 539 public static final int REASON_AB_OTA = 4; 540 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 541 public static final int REASON_SHARED_APK = 6; 542 public static final int REASON_FORCED_DEXOPT = 7; 543 public static final int REASON_CORE_APP = 8; 544 545 public static final int REASON_LAST = REASON_CORE_APP; 546 547 /** All dangerous permission names in the same order as the events in MetricsEvent */ 548 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 549 Manifest.permission.READ_CALENDAR, 550 Manifest.permission.WRITE_CALENDAR, 551 Manifest.permission.CAMERA, 552 Manifest.permission.READ_CONTACTS, 553 Manifest.permission.WRITE_CONTACTS, 554 Manifest.permission.GET_ACCOUNTS, 555 Manifest.permission.ACCESS_FINE_LOCATION, 556 Manifest.permission.ACCESS_COARSE_LOCATION, 557 Manifest.permission.RECORD_AUDIO, 558 Manifest.permission.READ_PHONE_STATE, 559 Manifest.permission.CALL_PHONE, 560 Manifest.permission.READ_CALL_LOG, 561 Manifest.permission.WRITE_CALL_LOG, 562 Manifest.permission.ADD_VOICEMAIL, 563 Manifest.permission.USE_SIP, 564 Manifest.permission.PROCESS_OUTGOING_CALLS, 565 Manifest.permission.READ_CELL_BROADCASTS, 566 Manifest.permission.BODY_SENSORS, 567 Manifest.permission.SEND_SMS, 568 Manifest.permission.RECEIVE_SMS, 569 Manifest.permission.READ_SMS, 570 Manifest.permission.RECEIVE_WAP_PUSH, 571 Manifest.permission.RECEIVE_MMS, 572 Manifest.permission.READ_EXTERNAL_STORAGE, 573 Manifest.permission.WRITE_EXTERNAL_STORAGE, 574 Manifest.permission.READ_PHONE_NUMBER, 575 Manifest.permission.ANSWER_PHONE_CALLS); 576 577 578 /** 579 * Version number for the package parser cache. Increment this whenever the format or 580 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 581 */ 582 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 583 584 /** 585 * Whether the package parser cache is enabled. 586 */ 587 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 588 589 final ServiceThread mHandlerThread; 590 591 final PackageHandler mHandler; 592 593 private final ProcessLoggingHandler mProcessLoggingHandler; 594 595 /** 596 * Messages for {@link #mHandler} that need to wait for system ready before 597 * being dispatched. 598 */ 599 private ArrayList<Message> mPostSystemReadyMessages; 600 601 final int mSdkVersion = Build.VERSION.SDK_INT; 602 603 final Context mContext; 604 final boolean mFactoryTest; 605 final boolean mOnlyCore; 606 final DisplayMetrics mMetrics; 607 final int mDefParseFlags; 608 final String[] mSeparateProcesses; 609 final boolean mIsUpgrade; 610 final boolean mIsPreNUpgrade; 611 final boolean mIsPreNMR1Upgrade; 612 613 @GuardedBy("mPackages") 614 private boolean mDexOptDialogShown; 615 616 /** The location for ASEC container files on internal storage. */ 617 final String mAsecInternalPath; 618 619 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 620 // LOCK HELD. Can be called with mInstallLock held. 621 @GuardedBy("mInstallLock") 622 final Installer mInstaller; 623 624 /** Directory where installed third-party apps stored */ 625 final File mAppInstallDir; 626 627 /** 628 * Directory to which applications installed internally have their 629 * 32 bit native libraries copied. 630 */ 631 private File mAppLib32InstallDir; 632 633 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 634 // apps. 635 final File mDrmAppPrivateInstallDir; 636 637 // ---------------------------------------------------------------- 638 639 // Lock for state used when installing and doing other long running 640 // operations. Methods that must be called with this lock held have 641 // the suffix "LI". 642 final Object mInstallLock = new Object(); 643 644 // ---------------------------------------------------------------- 645 646 // Keys are String (package name), values are Package. This also serves 647 // as the lock for the global state. Methods that must be called with 648 // this lock held have the prefix "LP". 649 @GuardedBy("mPackages") 650 final ArrayMap<String, PackageParser.Package> mPackages = 651 new ArrayMap<String, PackageParser.Package>(); 652 653 final ArrayMap<String, Set<String>> mKnownCodebase = 654 new ArrayMap<String, Set<String>>(); 655 656 // List of APK paths to load for each user and package. This data is never 657 // persisted by the package manager. Instead, the overlay manager will 658 // ensure the data is up-to-date in runtime. 659 @GuardedBy("mPackages") 660 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 661 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 662 663 /** 664 * Tracks new system packages [received in an OTA] that we expect to 665 * find updated user-installed versions. Keys are package name, values 666 * are package location. 667 */ 668 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 669 /** 670 * Tracks high priority intent filters for protected actions. During boot, certain 671 * filter actions are protected and should never be allowed to have a high priority 672 * intent filter for them. However, there is one, and only one exception -- the 673 * setup wizard. It must be able to define a high priority intent filter for these 674 * actions to ensure there are no escapes from the wizard. We need to delay processing 675 * of these during boot as we need to look at all of the system packages in order 676 * to know which component is the setup wizard. 677 */ 678 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 679 /** 680 * Whether or not processing protected filters should be deferred. 681 */ 682 private boolean mDeferProtectedFilters = true; 683 684 /** 685 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 686 */ 687 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 688 /** 689 * Whether or not system app permissions should be promoted from install to runtime. 690 */ 691 boolean mPromoteSystemApps; 692 693 @GuardedBy("mPackages") 694 final Settings mSettings; 695 696 /** 697 * Set of package names that are currently "frozen", which means active 698 * surgery is being done on the code/data for that package. The platform 699 * will refuse to launch frozen packages to avoid race conditions. 700 * 701 * @see PackageFreezer 702 */ 703 @GuardedBy("mPackages") 704 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 705 706 final ProtectedPackages mProtectedPackages; 707 708 boolean mFirstBoot; 709 710 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 711 712 // System configuration read by SystemConfig. 713 final int[] mGlobalGids; 714 final SparseArray<ArraySet<String>> mSystemPermissions; 715 @GuardedBy("mAvailableFeatures") 716 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 717 718 // If mac_permissions.xml was found for seinfo labeling. 719 boolean mFoundPolicyFile; 720 721 private final InstantAppRegistry mInstantAppRegistry; 722 723 @GuardedBy("mPackages") 724 int mChangedPackagesSequenceNumber; 725 /** 726 * List of changed [installed, removed or updated] packages. 727 * mapping from user id -> sequence number -> package name 728 */ 729 @GuardedBy("mPackages") 730 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 731 /** 732 * The sequence number of the last change to a package. 733 * mapping from user id -> package name -> sequence number 734 */ 735 @GuardedBy("mPackages") 736 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 737 738 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 739 @Override public boolean hasFeature(String feature) { 740 return PackageManagerService.this.hasSystemFeature(feature, 0); 741 } 742 }; 743 744 public static final class SharedLibraryEntry { 745 public final String path; 746 public final String apk; 747 public final SharedLibraryInfo info; 748 749 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 750 String declaringPackageName, int declaringPackageVersionCode) { 751 path = _path; 752 apk = _apk; 753 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 754 declaringPackageName, declaringPackageVersionCode), null); 755 } 756 } 757 758 // Currently known shared libraries. 759 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 760 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 761 new ArrayMap<>(); 762 763 // All available activities, for your resolving pleasure. 764 final ActivityIntentResolver mActivities = 765 new ActivityIntentResolver(); 766 767 // All available receivers, for your resolving pleasure. 768 final ActivityIntentResolver mReceivers = 769 new ActivityIntentResolver(); 770 771 // All available services, for your resolving pleasure. 772 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 773 774 // All available providers, for your resolving pleasure. 775 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 776 777 // Mapping from provider base names (first directory in content URI codePath) 778 // to the provider information. 779 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 780 new ArrayMap<String, PackageParser.Provider>(); 781 782 // Mapping from instrumentation class names to info about them. 783 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 784 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 785 786 // Mapping from permission names to info about them. 787 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 788 new ArrayMap<String, PackageParser.PermissionGroup>(); 789 790 // Packages whose data we have transfered into another package, thus 791 // should no longer exist. 792 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 793 794 // Broadcast actions that are only available to the system. 795 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 796 797 /** List of packages waiting for verification. */ 798 final SparseArray<PackageVerificationState> mPendingVerification 799 = new SparseArray<PackageVerificationState>(); 800 801 /** Set of packages associated with each app op permission. */ 802 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 803 804 final PackageInstallerService mInstallerService; 805 806 private final PackageDexOptimizer mPackageDexOptimizer; 807 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 808 // is used by other apps). 809 private final DexManager mDexManager; 810 811 private AtomicInteger mNextMoveId = new AtomicInteger(); 812 private final MoveCallbacks mMoveCallbacks; 813 814 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 815 816 // Cache of users who need badging. 817 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 818 819 /** Token for keys in mPendingVerification. */ 820 private int mPendingVerificationToken = 0; 821 822 volatile boolean mSystemReady; 823 volatile boolean mSafeMode; 824 volatile boolean mHasSystemUidErrors; 825 826 ApplicationInfo mAndroidApplication; 827 final ActivityInfo mResolveActivity = new ActivityInfo(); 828 final ResolveInfo mResolveInfo = new ResolveInfo(); 829 ComponentName mResolveComponentName; 830 PackageParser.Package mPlatformPackage; 831 ComponentName mCustomResolverComponentName; 832 833 boolean mResolverReplaced = false; 834 835 private final @Nullable ComponentName mIntentFilterVerifierComponent; 836 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 837 838 private int mIntentFilterVerificationToken = 0; 839 840 /** The service connection to the ephemeral resolver */ 841 final EphemeralResolverConnection mInstantAppResolverConnection; 842 843 /** Component used to install ephemeral applications */ 844 ComponentName mInstantAppInstallerComponent; 845 final ActivityInfo mInstantAppInstallerActivity = new ActivityInfo(); 846 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 847 848 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 849 = new SparseArray<IntentFilterVerificationState>(); 850 851 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 852 853 // List of packages names to keep cached, even if they are uninstalled for all users 854 private List<String> mKeepUninstalledPackages; 855 856 private UserManagerInternal mUserManagerInternal; 857 858 private DeviceIdleController.LocalService mDeviceIdleController; 859 860 private File mCacheDir; 861 862 private ArraySet<String> mPrivappPermissionsViolations; 863 864 private Future<?> mPrepareAppDataFuture; 865 866 private static class IFVerificationParams { 867 PackageParser.Package pkg; 868 boolean replacing; 869 int userId; 870 int verifierUid; 871 872 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 873 int _userId, int _verifierUid) { 874 pkg = _pkg; 875 replacing = _replacing; 876 userId = _userId; 877 replacing = _replacing; 878 verifierUid = _verifierUid; 879 } 880 } 881 882 private interface IntentFilterVerifier<T extends IntentFilter> { 883 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 884 T filter, String packageName); 885 void startVerifications(int userId); 886 void receiveVerificationResponse(int verificationId); 887 } 888 889 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 890 private Context mContext; 891 private ComponentName mIntentFilterVerifierComponent; 892 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 893 894 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 895 mContext = context; 896 mIntentFilterVerifierComponent = verifierComponent; 897 } 898 899 private String getDefaultScheme() { 900 return IntentFilter.SCHEME_HTTPS; 901 } 902 903 @Override 904 public void startVerifications(int userId) { 905 // Launch verifications requests 906 int count = mCurrentIntentFilterVerifications.size(); 907 for (int n=0; n<count; n++) { 908 int verificationId = mCurrentIntentFilterVerifications.get(n); 909 final IntentFilterVerificationState ivs = 910 mIntentFilterVerificationStates.get(verificationId); 911 912 String packageName = ivs.getPackageName(); 913 914 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 915 final int filterCount = filters.size(); 916 ArraySet<String> domainsSet = new ArraySet<>(); 917 for (int m=0; m<filterCount; m++) { 918 PackageParser.ActivityIntentInfo filter = filters.get(m); 919 domainsSet.addAll(filter.getHostsList()); 920 } 921 synchronized (mPackages) { 922 if (mSettings.createIntentFilterVerificationIfNeededLPw( 923 packageName, domainsSet) != null) { 924 scheduleWriteSettingsLocked(); 925 } 926 } 927 sendVerificationRequest(userId, verificationId, ivs); 928 } 929 mCurrentIntentFilterVerifications.clear(); 930 } 931 932 private void sendVerificationRequest(int userId, int verificationId, 933 IntentFilterVerificationState ivs) { 934 935 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 936 verificationIntent.putExtra( 937 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 938 verificationId); 939 verificationIntent.putExtra( 940 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 941 getDefaultScheme()); 942 verificationIntent.putExtra( 943 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 944 ivs.getHostsString()); 945 verificationIntent.putExtra( 946 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 947 ivs.getPackageName()); 948 verificationIntent.setComponent(mIntentFilterVerifierComponent); 949 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 950 951 UserHandle user = new UserHandle(userId); 952 mContext.sendBroadcastAsUser(verificationIntent, user); 953 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 954 "Sending IntentFilter verification broadcast"); 955 } 956 957 public void receiveVerificationResponse(int verificationId) { 958 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 959 960 final boolean verified = ivs.isVerified(); 961 962 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 963 final int count = filters.size(); 964 if (DEBUG_DOMAIN_VERIFICATION) { 965 Slog.i(TAG, "Received verification response " + verificationId 966 + " for " + count + " filters, verified=" + verified); 967 } 968 for (int n=0; n<count; n++) { 969 PackageParser.ActivityIntentInfo filter = filters.get(n); 970 filter.setVerified(verified); 971 972 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 973 + " verified with result:" + verified + " and hosts:" 974 + ivs.getHostsString()); 975 } 976 977 mIntentFilterVerificationStates.remove(verificationId); 978 979 final String packageName = ivs.getPackageName(); 980 IntentFilterVerificationInfo ivi = null; 981 982 synchronized (mPackages) { 983 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 984 } 985 if (ivi == null) { 986 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 987 + verificationId + " packageName:" + packageName); 988 return; 989 } 990 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 991 "Updating IntentFilterVerificationInfo for package " + packageName 992 +" verificationId:" + verificationId); 993 994 synchronized (mPackages) { 995 if (verified) { 996 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 997 } else { 998 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 999 } 1000 scheduleWriteSettingsLocked(); 1001 1002 final int userId = ivs.getUserId(); 1003 if (userId != UserHandle.USER_ALL) { 1004 final int userStatus = 1005 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1006 1007 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1008 boolean needUpdate = false; 1009 1010 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1011 // already been set by the User thru the Disambiguation dialog 1012 switch (userStatus) { 1013 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1014 if (verified) { 1015 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1016 } else { 1017 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1018 } 1019 needUpdate = true; 1020 break; 1021 1022 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1023 if (verified) { 1024 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1025 needUpdate = true; 1026 } 1027 break; 1028 1029 default: 1030 // Nothing to do 1031 } 1032 1033 if (needUpdate) { 1034 mSettings.updateIntentFilterVerificationStatusLPw( 1035 packageName, updatedStatus, userId); 1036 scheduleWritePackageRestrictionsLocked(userId); 1037 } 1038 } 1039 } 1040 } 1041 1042 @Override 1043 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1044 ActivityIntentInfo filter, String packageName) { 1045 if (!hasValidDomains(filter)) { 1046 return false; 1047 } 1048 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1049 if (ivs == null) { 1050 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1051 packageName); 1052 } 1053 if (DEBUG_DOMAIN_VERIFICATION) { 1054 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1055 } 1056 ivs.addFilter(filter); 1057 return true; 1058 } 1059 1060 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1061 int userId, int verificationId, String packageName) { 1062 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1063 verifierUid, userId, packageName); 1064 ivs.setPendingState(); 1065 synchronized (mPackages) { 1066 mIntentFilterVerificationStates.append(verificationId, ivs); 1067 mCurrentIntentFilterVerifications.add(verificationId); 1068 } 1069 return ivs; 1070 } 1071 } 1072 1073 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1074 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1075 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1076 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1077 } 1078 1079 // Set of pending broadcasts for aggregating enable/disable of components. 1080 static class PendingPackageBroadcasts { 1081 // for each user id, a map of <package name -> components within that package> 1082 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1083 1084 public PendingPackageBroadcasts() { 1085 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1086 } 1087 1088 public ArrayList<String> get(int userId, String packageName) { 1089 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1090 return packages.get(packageName); 1091 } 1092 1093 public void put(int userId, String packageName, ArrayList<String> components) { 1094 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1095 packages.put(packageName, components); 1096 } 1097 1098 public void remove(int userId, String packageName) { 1099 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1100 if (packages != null) { 1101 packages.remove(packageName); 1102 } 1103 } 1104 1105 public void remove(int userId) { 1106 mUidMap.remove(userId); 1107 } 1108 1109 public int userIdCount() { 1110 return mUidMap.size(); 1111 } 1112 1113 public int userIdAt(int n) { 1114 return mUidMap.keyAt(n); 1115 } 1116 1117 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1118 return mUidMap.get(userId); 1119 } 1120 1121 public int size() { 1122 // total number of pending broadcast entries across all userIds 1123 int num = 0; 1124 for (int i = 0; i< mUidMap.size(); i++) { 1125 num += mUidMap.valueAt(i).size(); 1126 } 1127 return num; 1128 } 1129 1130 public void clear() { 1131 mUidMap.clear(); 1132 } 1133 1134 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1135 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1136 if (map == null) { 1137 map = new ArrayMap<String, ArrayList<String>>(); 1138 mUidMap.put(userId, map); 1139 } 1140 return map; 1141 } 1142 } 1143 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1144 1145 // Service Connection to remote media container service to copy 1146 // package uri's from external media onto secure containers 1147 // or internal storage. 1148 private IMediaContainerService mContainerService = null; 1149 1150 static final int SEND_PENDING_BROADCAST = 1; 1151 static final int MCS_BOUND = 3; 1152 static final int END_COPY = 4; 1153 static final int INIT_COPY = 5; 1154 static final int MCS_UNBIND = 6; 1155 static final int START_CLEANING_PACKAGE = 7; 1156 static final int FIND_INSTALL_LOC = 8; 1157 static final int POST_INSTALL = 9; 1158 static final int MCS_RECONNECT = 10; 1159 static final int MCS_GIVE_UP = 11; 1160 static final int UPDATED_MEDIA_STATUS = 12; 1161 static final int WRITE_SETTINGS = 13; 1162 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1163 static final int PACKAGE_VERIFIED = 15; 1164 static final int CHECK_PENDING_VERIFICATION = 16; 1165 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1166 static final int INTENT_FILTER_VERIFIED = 18; 1167 static final int WRITE_PACKAGE_LIST = 19; 1168 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1169 1170 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1171 1172 // Delay time in millisecs 1173 static final int BROADCAST_DELAY = 10 * 1000; 1174 1175 static UserManagerService sUserManager; 1176 1177 // Stores a list of users whose package restrictions file needs to be updated 1178 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1179 1180 final private DefaultContainerConnection mDefContainerConn = 1181 new DefaultContainerConnection(); 1182 class DefaultContainerConnection implements ServiceConnection { 1183 public void onServiceConnected(ComponentName name, IBinder service) { 1184 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1185 final IMediaContainerService imcs = IMediaContainerService.Stub 1186 .asInterface(Binder.allowBlocking(service)); 1187 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1188 } 1189 1190 public void onServiceDisconnected(ComponentName name) { 1191 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1192 } 1193 } 1194 1195 // Recordkeeping of restore-after-install operations that are currently in flight 1196 // between the Package Manager and the Backup Manager 1197 static class PostInstallData { 1198 public InstallArgs args; 1199 public PackageInstalledInfo res; 1200 1201 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1202 args = _a; 1203 res = _r; 1204 } 1205 } 1206 1207 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1208 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1209 1210 // XML tags for backup/restore of various bits of state 1211 private static final String TAG_PREFERRED_BACKUP = "pa"; 1212 private static final String TAG_DEFAULT_APPS = "da"; 1213 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1214 1215 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1216 private static final String TAG_ALL_GRANTS = "rt-grants"; 1217 private static final String TAG_GRANT = "grant"; 1218 private static final String ATTR_PACKAGE_NAME = "pkg"; 1219 1220 private static final String TAG_PERMISSION = "perm"; 1221 private static final String ATTR_PERMISSION_NAME = "name"; 1222 private static final String ATTR_IS_GRANTED = "g"; 1223 private static final String ATTR_USER_SET = "set"; 1224 private static final String ATTR_USER_FIXED = "fixed"; 1225 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1226 1227 // System/policy permission grants are not backed up 1228 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1229 FLAG_PERMISSION_POLICY_FIXED 1230 | FLAG_PERMISSION_SYSTEM_FIXED 1231 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1232 1233 // And we back up these user-adjusted states 1234 private static final int USER_RUNTIME_GRANT_MASK = 1235 FLAG_PERMISSION_USER_SET 1236 | FLAG_PERMISSION_USER_FIXED 1237 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1238 1239 final @Nullable String mRequiredVerifierPackage; 1240 final @NonNull String mRequiredInstallerPackage; 1241 final @NonNull String mRequiredUninstallerPackage; 1242 final @Nullable String mSetupWizardPackage; 1243 final @Nullable String mStorageManagerPackage; 1244 final @NonNull String mServicesSystemSharedLibraryPackageName; 1245 final @NonNull String mSharedSystemSharedLibraryPackageName; 1246 1247 final boolean mPermissionReviewRequired; 1248 1249 private final PackageUsage mPackageUsage = new PackageUsage(); 1250 private final CompilerStats mCompilerStats = new CompilerStats(); 1251 1252 class PackageHandler extends Handler { 1253 private boolean mBound = false; 1254 final ArrayList<HandlerParams> mPendingInstalls = 1255 new ArrayList<HandlerParams>(); 1256 1257 private boolean connectToService() { 1258 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1259 " DefaultContainerService"); 1260 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1261 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1262 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1263 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1264 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1265 mBound = true; 1266 return true; 1267 } 1268 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1269 return false; 1270 } 1271 1272 private void disconnectService() { 1273 mContainerService = null; 1274 mBound = false; 1275 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1276 mContext.unbindService(mDefContainerConn); 1277 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1278 } 1279 1280 PackageHandler(Looper looper) { 1281 super(looper); 1282 } 1283 1284 public void handleMessage(Message msg) { 1285 try { 1286 doHandleMessage(msg); 1287 } finally { 1288 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1289 } 1290 } 1291 1292 void doHandleMessage(Message msg) { 1293 switch (msg.what) { 1294 case INIT_COPY: { 1295 HandlerParams params = (HandlerParams) msg.obj; 1296 int idx = mPendingInstalls.size(); 1297 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1298 // If a bind was already initiated we dont really 1299 // need to do anything. The pending install 1300 // will be processed later on. 1301 if (!mBound) { 1302 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1303 System.identityHashCode(mHandler)); 1304 // If this is the only one pending we might 1305 // have to bind to the service again. 1306 if (!connectToService()) { 1307 Slog.e(TAG, "Failed to bind to media container service"); 1308 params.serviceError(); 1309 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1310 System.identityHashCode(mHandler)); 1311 if (params.traceMethod != null) { 1312 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1313 params.traceCookie); 1314 } 1315 return; 1316 } else { 1317 // Once we bind to the service, the first 1318 // pending request will be processed. 1319 mPendingInstalls.add(idx, params); 1320 } 1321 } else { 1322 mPendingInstalls.add(idx, params); 1323 // Already bound to the service. Just make 1324 // sure we trigger off processing the first request. 1325 if (idx == 0) { 1326 mHandler.sendEmptyMessage(MCS_BOUND); 1327 } 1328 } 1329 break; 1330 } 1331 case MCS_BOUND: { 1332 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1333 if (msg.obj != null) { 1334 mContainerService = (IMediaContainerService) msg.obj; 1335 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1336 System.identityHashCode(mHandler)); 1337 } 1338 if (mContainerService == null) { 1339 if (!mBound) { 1340 // Something seriously wrong since we are not bound and we are not 1341 // waiting for connection. Bail out. 1342 Slog.e(TAG, "Cannot bind to media container service"); 1343 for (HandlerParams params : mPendingInstalls) { 1344 // Indicate service bind error 1345 params.serviceError(); 1346 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1347 System.identityHashCode(params)); 1348 if (params.traceMethod != null) { 1349 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1350 params.traceMethod, params.traceCookie); 1351 } 1352 return; 1353 } 1354 mPendingInstalls.clear(); 1355 } else { 1356 Slog.w(TAG, "Waiting to connect to media container service"); 1357 } 1358 } else if (mPendingInstalls.size() > 0) { 1359 HandlerParams params = mPendingInstalls.get(0); 1360 if (params != null) { 1361 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1362 System.identityHashCode(params)); 1363 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1364 if (params.startCopy()) { 1365 // We are done... look for more work or to 1366 // go idle. 1367 if (DEBUG_SD_INSTALL) Log.i(TAG, 1368 "Checking for more work or unbind..."); 1369 // Delete pending install 1370 if (mPendingInstalls.size() > 0) { 1371 mPendingInstalls.remove(0); 1372 } 1373 if (mPendingInstalls.size() == 0) { 1374 if (mBound) { 1375 if (DEBUG_SD_INSTALL) Log.i(TAG, 1376 "Posting delayed MCS_UNBIND"); 1377 removeMessages(MCS_UNBIND); 1378 Message ubmsg = obtainMessage(MCS_UNBIND); 1379 // Unbind after a little delay, to avoid 1380 // continual thrashing. 1381 sendMessageDelayed(ubmsg, 10000); 1382 } 1383 } else { 1384 // There are more pending requests in queue. 1385 // Just post MCS_BOUND message to trigger processing 1386 // of next pending install. 1387 if (DEBUG_SD_INSTALL) Log.i(TAG, 1388 "Posting MCS_BOUND for next work"); 1389 mHandler.sendEmptyMessage(MCS_BOUND); 1390 } 1391 } 1392 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1393 } 1394 } else { 1395 // Should never happen ideally. 1396 Slog.w(TAG, "Empty queue"); 1397 } 1398 break; 1399 } 1400 case MCS_RECONNECT: { 1401 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1402 if (mPendingInstalls.size() > 0) { 1403 if (mBound) { 1404 disconnectService(); 1405 } 1406 if (!connectToService()) { 1407 Slog.e(TAG, "Failed to bind to media container service"); 1408 for (HandlerParams params : mPendingInstalls) { 1409 // Indicate service bind error 1410 params.serviceError(); 1411 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1412 System.identityHashCode(params)); 1413 } 1414 mPendingInstalls.clear(); 1415 } 1416 } 1417 break; 1418 } 1419 case MCS_UNBIND: { 1420 // If there is no actual work left, then time to unbind. 1421 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1422 1423 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1424 if (mBound) { 1425 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1426 1427 disconnectService(); 1428 } 1429 } else if (mPendingInstalls.size() > 0) { 1430 // There are more pending requests in queue. 1431 // Just post MCS_BOUND message to trigger processing 1432 // of next pending install. 1433 mHandler.sendEmptyMessage(MCS_BOUND); 1434 } 1435 1436 break; 1437 } 1438 case MCS_GIVE_UP: { 1439 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1440 HandlerParams params = mPendingInstalls.remove(0); 1441 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1442 System.identityHashCode(params)); 1443 break; 1444 } 1445 case SEND_PENDING_BROADCAST: { 1446 String packages[]; 1447 ArrayList<String> components[]; 1448 int size = 0; 1449 int uids[]; 1450 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1451 synchronized (mPackages) { 1452 if (mPendingBroadcasts == null) { 1453 return; 1454 } 1455 size = mPendingBroadcasts.size(); 1456 if (size <= 0) { 1457 // Nothing to be done. Just return 1458 return; 1459 } 1460 packages = new String[size]; 1461 components = new ArrayList[size]; 1462 uids = new int[size]; 1463 int i = 0; // filling out the above arrays 1464 1465 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1466 int packageUserId = mPendingBroadcasts.userIdAt(n); 1467 Iterator<Map.Entry<String, ArrayList<String>>> it 1468 = mPendingBroadcasts.packagesForUserId(packageUserId) 1469 .entrySet().iterator(); 1470 while (it.hasNext() && i < size) { 1471 Map.Entry<String, ArrayList<String>> ent = it.next(); 1472 packages[i] = ent.getKey(); 1473 components[i] = ent.getValue(); 1474 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1475 uids[i] = (ps != null) 1476 ? UserHandle.getUid(packageUserId, ps.appId) 1477 : -1; 1478 i++; 1479 } 1480 } 1481 size = i; 1482 mPendingBroadcasts.clear(); 1483 } 1484 // Send broadcasts 1485 for (int i = 0; i < size; i++) { 1486 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1487 } 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1489 break; 1490 } 1491 case START_CLEANING_PACKAGE: { 1492 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1493 final String packageName = (String)msg.obj; 1494 final int userId = msg.arg1; 1495 final boolean andCode = msg.arg2 != 0; 1496 synchronized (mPackages) { 1497 if (userId == UserHandle.USER_ALL) { 1498 int[] users = sUserManager.getUserIds(); 1499 for (int user : users) { 1500 mSettings.addPackageToCleanLPw( 1501 new PackageCleanItem(user, packageName, andCode)); 1502 } 1503 } else { 1504 mSettings.addPackageToCleanLPw( 1505 new PackageCleanItem(userId, packageName, andCode)); 1506 } 1507 } 1508 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1509 startCleaningPackages(); 1510 } break; 1511 case POST_INSTALL: { 1512 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1513 1514 PostInstallData data = mRunningInstalls.get(msg.arg1); 1515 final boolean didRestore = (msg.arg2 != 0); 1516 mRunningInstalls.delete(msg.arg1); 1517 1518 if (data != null) { 1519 InstallArgs args = data.args; 1520 PackageInstalledInfo parentRes = data.res; 1521 1522 final boolean grantPermissions = (args.installFlags 1523 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1524 final boolean killApp = (args.installFlags 1525 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1526 final String[] grantedPermissions = args.installGrantPermissions; 1527 1528 // Handle the parent package 1529 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1530 grantedPermissions, didRestore, args.installerPackageName, 1531 args.observer); 1532 1533 // Handle the child packages 1534 final int childCount = (parentRes.addedChildPackages != null) 1535 ? parentRes.addedChildPackages.size() : 0; 1536 for (int i = 0; i < childCount; i++) { 1537 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1538 handlePackagePostInstall(childRes, grantPermissions, killApp, 1539 grantedPermissions, false, args.installerPackageName, 1540 args.observer); 1541 } 1542 1543 // Log tracing if needed 1544 if (args.traceMethod != null) { 1545 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1546 args.traceCookie); 1547 } 1548 } else { 1549 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1550 } 1551 1552 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1553 } break; 1554 case UPDATED_MEDIA_STATUS: { 1555 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1556 boolean reportStatus = msg.arg1 == 1; 1557 boolean doGc = msg.arg2 == 1; 1558 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1559 if (doGc) { 1560 // Force a gc to clear up stale containers. 1561 Runtime.getRuntime().gc(); 1562 } 1563 if (msg.obj != null) { 1564 @SuppressWarnings("unchecked") 1565 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1566 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1567 // Unload containers 1568 unloadAllContainers(args); 1569 } 1570 if (reportStatus) { 1571 try { 1572 if (DEBUG_SD_INSTALL) Log.i(TAG, 1573 "Invoking StorageManagerService call back"); 1574 PackageHelper.getStorageManager().finishMediaUpdate(); 1575 } catch (RemoteException e) { 1576 Log.e(TAG, "StorageManagerService not running?"); 1577 } 1578 } 1579 } break; 1580 case WRITE_SETTINGS: { 1581 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1582 synchronized (mPackages) { 1583 removeMessages(WRITE_SETTINGS); 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 mSettings.writeLPr(); 1586 mDirtyUsers.clear(); 1587 } 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1589 } break; 1590 case WRITE_PACKAGE_RESTRICTIONS: { 1591 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1592 synchronized (mPackages) { 1593 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1594 for (int userId : mDirtyUsers) { 1595 mSettings.writePackageRestrictionsLPr(userId); 1596 } 1597 mDirtyUsers.clear(); 1598 } 1599 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1600 } break; 1601 case WRITE_PACKAGE_LIST: { 1602 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1603 synchronized (mPackages) { 1604 removeMessages(WRITE_PACKAGE_LIST); 1605 mSettings.writePackageListLPr(msg.arg1); 1606 } 1607 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1608 } break; 1609 case CHECK_PENDING_VERIFICATION: { 1610 final int verificationId = msg.arg1; 1611 final PackageVerificationState state = mPendingVerification.get(verificationId); 1612 1613 if ((state != null) && !state.timeoutExtended()) { 1614 final InstallArgs args = state.getInstallArgs(); 1615 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1616 1617 Slog.i(TAG, "Verification timed out for " + originUri); 1618 mPendingVerification.remove(verificationId); 1619 1620 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1621 1622 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1623 Slog.i(TAG, "Continuing with installation of " + originUri); 1624 state.setVerifierResponse(Binder.getCallingUid(), 1625 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1626 broadcastPackageVerified(verificationId, originUri, 1627 PackageManager.VERIFICATION_ALLOW, 1628 state.getInstallArgs().getUser()); 1629 try { 1630 ret = args.copyApk(mContainerService, true); 1631 } catch (RemoteException e) { 1632 Slog.e(TAG, "Could not contact the ContainerService"); 1633 } 1634 } else { 1635 broadcastPackageVerified(verificationId, originUri, 1636 PackageManager.VERIFICATION_REJECT, 1637 state.getInstallArgs().getUser()); 1638 } 1639 1640 Trace.asyncTraceEnd( 1641 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1642 1643 processPendingInstall(args, ret); 1644 mHandler.sendEmptyMessage(MCS_UNBIND); 1645 } 1646 break; 1647 } 1648 case PACKAGE_VERIFIED: { 1649 final int verificationId = msg.arg1; 1650 1651 final PackageVerificationState state = mPendingVerification.get(verificationId); 1652 if (state == null) { 1653 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1654 break; 1655 } 1656 1657 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1658 1659 state.setVerifierResponse(response.callerUid, response.code); 1660 1661 if (state.isVerificationComplete()) { 1662 mPendingVerification.remove(verificationId); 1663 1664 final InstallArgs args = state.getInstallArgs(); 1665 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1666 1667 int ret; 1668 if (state.isInstallAllowed()) { 1669 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1670 broadcastPackageVerified(verificationId, originUri, 1671 response.code, state.getInstallArgs().getUser()); 1672 try { 1673 ret = args.copyApk(mContainerService, true); 1674 } catch (RemoteException e) { 1675 Slog.e(TAG, "Could not contact the ContainerService"); 1676 } 1677 } else { 1678 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1679 } 1680 1681 Trace.asyncTraceEnd( 1682 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1683 1684 processPendingInstall(args, ret); 1685 mHandler.sendEmptyMessage(MCS_UNBIND); 1686 } 1687 1688 break; 1689 } 1690 case START_INTENT_FILTER_VERIFICATIONS: { 1691 IFVerificationParams params = (IFVerificationParams) msg.obj; 1692 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1693 params.replacing, params.pkg); 1694 break; 1695 } 1696 case INTENT_FILTER_VERIFIED: { 1697 final int verificationId = msg.arg1; 1698 1699 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1700 verificationId); 1701 if (state == null) { 1702 Slog.w(TAG, "Invalid IntentFilter verification token " 1703 + verificationId + " received"); 1704 break; 1705 } 1706 1707 final int userId = state.getUserId(); 1708 1709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1710 "Processing IntentFilter verification with token:" 1711 + verificationId + " and userId:" + userId); 1712 1713 final IntentFilterVerificationResponse response = 1714 (IntentFilterVerificationResponse) msg.obj; 1715 1716 state.setVerifierResponse(response.callerUid, response.code); 1717 1718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1719 "IntentFilter verification with token:" + verificationId 1720 + " and userId:" + userId 1721 + " is settings verifier response with response code:" 1722 + response.code); 1723 1724 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1725 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1726 + response.getFailedDomainsString()); 1727 } 1728 1729 if (state.isVerificationComplete()) { 1730 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1731 } else { 1732 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1733 "IntentFilter verification with token:" + verificationId 1734 + " was not said to be complete"); 1735 } 1736 1737 break; 1738 } 1739 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1740 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1741 mInstantAppResolverConnection, 1742 (InstantAppRequest) msg.obj, 1743 mInstantAppInstallerActivity, 1744 mHandler); 1745 } 1746 } 1747 } 1748 } 1749 1750 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1751 boolean killApp, String[] grantedPermissions, 1752 boolean launchedForRestore, String installerPackage, 1753 IPackageInstallObserver2 installObserver) { 1754 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1755 // Send the removed broadcasts 1756 if (res.removedInfo != null) { 1757 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1758 } 1759 1760 // Now that we successfully installed the package, grant runtime 1761 // permissions if requested before broadcasting the install. Also 1762 // for legacy apps in permission review mode we clear the permission 1763 // review flag which is used to emulate runtime permissions for 1764 // legacy apps. 1765 if (grantPermissions) { 1766 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1767 } 1768 1769 final boolean update = res.removedInfo != null 1770 && res.removedInfo.removedPackage != null; 1771 1772 // If this is the first time we have child packages for a disabled privileged 1773 // app that had no children, we grant requested runtime permissions to the new 1774 // children if the parent on the system image had them already granted. 1775 if (res.pkg.parentPackage != null) { 1776 synchronized (mPackages) { 1777 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1778 } 1779 } 1780 1781 synchronized (mPackages) { 1782 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1783 } 1784 1785 final String packageName = res.pkg.applicationInfo.packageName; 1786 1787 // Determine the set of users who are adding this package for 1788 // the first time vs. those who are seeing an update. 1789 int[] firstUsers = EMPTY_INT_ARRAY; 1790 int[] updateUsers = EMPTY_INT_ARRAY; 1791 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1792 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1793 for (int newUser : res.newUsers) { 1794 if (ps.getInstantApp(newUser)) { 1795 continue; 1796 } 1797 if (allNewUsers) { 1798 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1799 continue; 1800 } 1801 boolean isNew = true; 1802 for (int origUser : res.origUsers) { 1803 if (origUser == newUser) { 1804 isNew = false; 1805 break; 1806 } 1807 } 1808 if (isNew) { 1809 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1810 } else { 1811 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1812 } 1813 } 1814 1815 // Send installed broadcasts if the package is not a static shared lib. 1816 if (res.pkg.staticSharedLibName == null) { 1817 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1818 1819 // Send added for users that see the package for the first time 1820 // sendPackageAddedForNewUsers also deals with system apps 1821 int appId = UserHandle.getAppId(res.uid); 1822 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1823 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1824 1825 // Send added for users that don't see the package for the first time 1826 Bundle extras = new Bundle(1); 1827 extras.putInt(Intent.EXTRA_UID, res.uid); 1828 if (update) { 1829 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1830 } 1831 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1832 extras, 0 /*flags*/, null /*targetPackage*/, 1833 null /*finishedReceiver*/, updateUsers); 1834 1835 // Send replaced for users that don't see the package for the first time 1836 if (update) { 1837 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1838 packageName, extras, 0 /*flags*/, 1839 null /*targetPackage*/, null /*finishedReceiver*/, 1840 updateUsers); 1841 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1842 null /*package*/, null /*extras*/, 0 /*flags*/, 1843 packageName /*targetPackage*/, 1844 null /*finishedReceiver*/, updateUsers); 1845 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1846 // First-install and we did a restore, so we're responsible for the 1847 // first-launch broadcast. 1848 if (DEBUG_BACKUP) { 1849 Slog.i(TAG, "Post-restore of " + packageName 1850 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1851 } 1852 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1853 } 1854 1855 // Send broadcast package appeared if forward locked/external for all users 1856 // treat asec-hosted packages like removable media on upgrade 1857 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1858 if (DEBUG_INSTALL) { 1859 Slog.i(TAG, "upgrading pkg " + res.pkg 1860 + " is ASEC-hosted -> AVAILABLE"); 1861 } 1862 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1863 ArrayList<String> pkgList = new ArrayList<>(1); 1864 pkgList.add(packageName); 1865 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1866 } 1867 } 1868 1869 // Work that needs to happen on first install within each user 1870 if (firstUsers != null && firstUsers.length > 0) { 1871 synchronized (mPackages) { 1872 for (int userId : firstUsers) { 1873 // If this app is a browser and it's newly-installed for some 1874 // users, clear any default-browser state in those users. The 1875 // app's nature doesn't depend on the user, so we can just check 1876 // its browser nature in any user and generalize. 1877 if (packageIsBrowser(packageName, userId)) { 1878 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1879 } 1880 1881 // We may also need to apply pending (restored) runtime 1882 // permission grants within these users. 1883 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1884 } 1885 } 1886 } 1887 1888 // Log current value of "unknown sources" setting 1889 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1890 getUnknownSourcesSettings()); 1891 1892 // Force a gc to clear up things 1893 Runtime.getRuntime().gc(); 1894 1895 // Remove the replaced package's older resources safely now 1896 // We delete after a gc for applications on sdcard. 1897 if (res.removedInfo != null && res.removedInfo.args != null) { 1898 synchronized (mInstallLock) { 1899 res.removedInfo.args.doPostDeleteLI(true); 1900 } 1901 } 1902 1903 // Notify DexManager that the package was installed for new users. 1904 // The updated users should already be indexed and the package code paths 1905 // should not change. 1906 // Don't notify the manager for ephemeral apps as they are not expected to 1907 // survive long enough to benefit of background optimizations. 1908 for (int userId : firstUsers) { 1909 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1910 mDexManager.notifyPackageInstalled(info, userId); 1911 } 1912 } 1913 1914 // If someone is watching installs - notify them 1915 if (installObserver != null) { 1916 try { 1917 Bundle extras = extrasForInstallResult(res); 1918 installObserver.onPackageInstalled(res.name, res.returnCode, 1919 res.returnMsg, extras); 1920 } catch (RemoteException e) { 1921 Slog.i(TAG, "Observer no longer exists."); 1922 } 1923 } 1924 } 1925 1926 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1927 PackageParser.Package pkg) { 1928 if (pkg.parentPackage == null) { 1929 return; 1930 } 1931 if (pkg.requestedPermissions == null) { 1932 return; 1933 } 1934 final PackageSetting disabledSysParentPs = mSettings 1935 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1936 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1937 || !disabledSysParentPs.isPrivileged() 1938 || (disabledSysParentPs.childPackageNames != null 1939 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1940 return; 1941 } 1942 final int[] allUserIds = sUserManager.getUserIds(); 1943 final int permCount = pkg.requestedPermissions.size(); 1944 for (int i = 0; i < permCount; i++) { 1945 String permission = pkg.requestedPermissions.get(i); 1946 BasePermission bp = mSettings.mPermissions.get(permission); 1947 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1948 continue; 1949 } 1950 for (int userId : allUserIds) { 1951 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1952 permission, userId)) { 1953 grantRuntimePermission(pkg.packageName, permission, userId); 1954 } 1955 } 1956 } 1957 } 1958 1959 private StorageEventListener mStorageListener = new StorageEventListener() { 1960 @Override 1961 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1962 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1963 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1964 final String volumeUuid = vol.getFsUuid(); 1965 1966 // Clean up any users or apps that were removed or recreated 1967 // while this volume was missing 1968 sUserManager.reconcileUsers(volumeUuid); 1969 reconcileApps(volumeUuid); 1970 1971 // Clean up any install sessions that expired or were 1972 // cancelled while this volume was missing 1973 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1974 1975 loadPrivatePackages(vol); 1976 1977 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1978 unloadPrivatePackages(vol); 1979 } 1980 } 1981 1982 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1983 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1984 updateExternalMediaStatus(true, false); 1985 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1986 updateExternalMediaStatus(false, false); 1987 } 1988 } 1989 } 1990 1991 @Override 1992 public void onVolumeForgotten(String fsUuid) { 1993 if (TextUtils.isEmpty(fsUuid)) { 1994 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1995 return; 1996 } 1997 1998 // Remove any apps installed on the forgotten volume 1999 synchronized (mPackages) { 2000 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2001 for (PackageSetting ps : packages) { 2002 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2003 deletePackageVersioned(new VersionedPackage(ps.name, 2004 PackageManager.VERSION_CODE_HIGHEST), 2005 new LegacyPackageDeleteObserver(null).getBinder(), 2006 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2007 // Try very hard to release any references to this package 2008 // so we don't risk the system server being killed due to 2009 // open FDs 2010 AttributeCache.instance().removePackage(ps.name); 2011 } 2012 2013 mSettings.onVolumeForgotten(fsUuid); 2014 mSettings.writeLPr(); 2015 } 2016 } 2017 }; 2018 2019 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2020 String[] grantedPermissions) { 2021 for (int userId : userIds) { 2022 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2023 } 2024 } 2025 2026 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2027 String[] grantedPermissions) { 2028 SettingBase sb = (SettingBase) pkg.mExtras; 2029 if (sb == null) { 2030 return; 2031 } 2032 2033 PermissionsState permissionsState = sb.getPermissionsState(); 2034 2035 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2036 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2037 2038 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2039 >= Build.VERSION_CODES.M; 2040 2041 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2042 2043 for (String permission : pkg.requestedPermissions) { 2044 final BasePermission bp; 2045 synchronized (mPackages) { 2046 bp = mSettings.mPermissions.get(permission); 2047 } 2048 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2049 && (!instantApp || bp.isInstant()) 2050 && (grantedPermissions == null 2051 || ArrayUtils.contains(grantedPermissions, permission))) { 2052 final int flags = permissionsState.getPermissionFlags(permission, userId); 2053 if (supportsRuntimePermissions) { 2054 // Installer cannot change immutable permissions. 2055 if ((flags & immutableFlags) == 0) { 2056 grantRuntimePermission(pkg.packageName, permission, userId); 2057 } 2058 } else if (mPermissionReviewRequired) { 2059 // In permission review mode we clear the review flag when we 2060 // are asked to install the app with all permissions granted. 2061 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2062 updatePermissionFlags(permission, pkg.packageName, 2063 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2064 } 2065 } 2066 } 2067 } 2068 } 2069 2070 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2071 Bundle extras = null; 2072 switch (res.returnCode) { 2073 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2074 extras = new Bundle(); 2075 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2076 res.origPermission); 2077 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2078 res.origPackage); 2079 break; 2080 } 2081 case PackageManager.INSTALL_SUCCEEDED: { 2082 extras = new Bundle(); 2083 extras.putBoolean(Intent.EXTRA_REPLACING, 2084 res.removedInfo != null && res.removedInfo.removedPackage != null); 2085 break; 2086 } 2087 } 2088 return extras; 2089 } 2090 2091 void scheduleWriteSettingsLocked() { 2092 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2093 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2094 } 2095 } 2096 2097 void scheduleWritePackageListLocked(int userId) { 2098 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2099 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2100 msg.arg1 = userId; 2101 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2102 } 2103 } 2104 2105 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2106 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2107 scheduleWritePackageRestrictionsLocked(userId); 2108 } 2109 2110 void scheduleWritePackageRestrictionsLocked(int userId) { 2111 final int[] userIds = (userId == UserHandle.USER_ALL) 2112 ? sUserManager.getUserIds() : new int[]{userId}; 2113 for (int nextUserId : userIds) { 2114 if (!sUserManager.exists(nextUserId)) return; 2115 mDirtyUsers.add(nextUserId); 2116 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2117 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2118 } 2119 } 2120 } 2121 2122 public static PackageManagerService main(Context context, Installer installer, 2123 boolean factoryTest, boolean onlyCore) { 2124 // Self-check for initial settings. 2125 PackageManagerServiceCompilerMapping.checkProperties(); 2126 2127 PackageManagerService m = new PackageManagerService(context, installer, 2128 factoryTest, onlyCore); 2129 m.enableSystemUserPackages(); 2130 ServiceManager.addService("package", m); 2131 return m; 2132 } 2133 2134 private void enableSystemUserPackages() { 2135 if (!UserManager.isSplitSystemUser()) { 2136 return; 2137 } 2138 // For system user, enable apps based on the following conditions: 2139 // - app is whitelisted or belong to one of these groups: 2140 // -- system app which has no launcher icons 2141 // -- system app which has INTERACT_ACROSS_USERS permission 2142 // -- system IME app 2143 // - app is not in the blacklist 2144 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2145 Set<String> enableApps = new ArraySet<>(); 2146 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2147 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2148 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2149 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2150 enableApps.addAll(wlApps); 2151 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2152 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2153 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2154 enableApps.removeAll(blApps); 2155 Log.i(TAG, "Applications installed for system user: " + enableApps); 2156 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2157 UserHandle.SYSTEM); 2158 final int allAppsSize = allAps.size(); 2159 synchronized (mPackages) { 2160 for (int i = 0; i < allAppsSize; i++) { 2161 String pName = allAps.get(i); 2162 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2163 // Should not happen, but we shouldn't be failing if it does 2164 if (pkgSetting == null) { 2165 continue; 2166 } 2167 boolean install = enableApps.contains(pName); 2168 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2169 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2170 + " for system user"); 2171 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2172 } 2173 } 2174 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2175 } 2176 } 2177 2178 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2179 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2180 Context.DISPLAY_SERVICE); 2181 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2182 } 2183 2184 /** 2185 * Requests that files preopted on a secondary system partition be copied to the data partition 2186 * if possible. Note that the actual copying of the files is accomplished by init for security 2187 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2188 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2189 */ 2190 private static void requestCopyPreoptedFiles() { 2191 final int WAIT_TIME_MS = 100; 2192 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2193 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2194 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2195 // We will wait for up to 100 seconds. 2196 final long timeStart = SystemClock.uptimeMillis(); 2197 final long timeEnd = timeStart + 100 * 1000; 2198 long timeNow = timeStart; 2199 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2200 try { 2201 Thread.sleep(WAIT_TIME_MS); 2202 } catch (InterruptedException e) { 2203 // Do nothing 2204 } 2205 timeNow = SystemClock.uptimeMillis(); 2206 if (timeNow > timeEnd) { 2207 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2208 Slog.wtf(TAG, "cppreopt did not finish!"); 2209 break; 2210 } 2211 } 2212 2213 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2214 } 2215 } 2216 2217 public PackageManagerService(Context context, Installer installer, 2218 boolean factoryTest, boolean onlyCore) { 2219 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2221 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2222 SystemClock.uptimeMillis()); 2223 2224 if (mSdkVersion <= 0) { 2225 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2226 } 2227 2228 mContext = context; 2229 2230 mPermissionReviewRequired = context.getResources().getBoolean( 2231 R.bool.config_permissionReviewRequired); 2232 2233 mFactoryTest = factoryTest; 2234 mOnlyCore = onlyCore; 2235 mMetrics = new DisplayMetrics(); 2236 mSettings = new Settings(mPackages); 2237 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2238 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2239 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2240 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2241 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2242 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2243 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2244 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2245 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2246 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2247 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2248 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2249 2250 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2251 if (separateProcesses != null && separateProcesses.length() > 0) { 2252 if ("*".equals(separateProcesses)) { 2253 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2254 mSeparateProcesses = null; 2255 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2256 } else { 2257 mDefParseFlags = 0; 2258 mSeparateProcesses = separateProcesses.split(","); 2259 Slog.w(TAG, "Running with debug.separate_processes: " 2260 + separateProcesses); 2261 } 2262 } else { 2263 mDefParseFlags = 0; 2264 mSeparateProcesses = null; 2265 } 2266 2267 mInstaller = installer; 2268 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2269 "*dexopt*"); 2270 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2271 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2272 2273 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2274 FgThread.get().getLooper()); 2275 2276 getDefaultDisplayMetrics(context, mMetrics); 2277 2278 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2279 SystemConfig systemConfig = SystemConfig.getInstance(); 2280 mGlobalGids = systemConfig.getGlobalGids(); 2281 mSystemPermissions = systemConfig.getSystemPermissions(); 2282 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2283 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2284 2285 mProtectedPackages = new ProtectedPackages(mContext); 2286 2287 synchronized (mInstallLock) { 2288 // writer 2289 synchronized (mPackages) { 2290 mHandlerThread = new ServiceThread(TAG, 2291 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2292 mHandlerThread.start(); 2293 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2294 mProcessLoggingHandler = new ProcessLoggingHandler(); 2295 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2296 2297 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2298 mInstantAppRegistry = new InstantAppRegistry(this); 2299 2300 File dataDir = Environment.getDataDirectory(); 2301 mAppInstallDir = new File(dataDir, "app"); 2302 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2303 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2304 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2305 sUserManager = new UserManagerService(context, this, 2306 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2307 2308 // Propagate permission configuration in to package manager. 2309 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2310 = systemConfig.getPermissions(); 2311 for (int i=0; i<permConfig.size(); i++) { 2312 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2313 BasePermission bp = mSettings.mPermissions.get(perm.name); 2314 if (bp == null) { 2315 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2316 mSettings.mPermissions.put(perm.name, bp); 2317 } 2318 if (perm.gids != null) { 2319 bp.setGids(perm.gids, perm.perUser); 2320 } 2321 } 2322 2323 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2324 final int builtInLibCount = libConfig.size(); 2325 for (int i = 0; i < builtInLibCount; i++) { 2326 String name = libConfig.keyAt(i); 2327 String path = libConfig.valueAt(i); 2328 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2329 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2330 } 2331 2332 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2333 2334 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2335 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2336 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2337 2338 // Clean up orphaned packages for which the code path doesn't exist 2339 // and they are an update to a system app - caused by bug/32321269 2340 final int packageSettingCount = mSettings.mPackages.size(); 2341 for (int i = packageSettingCount - 1; i >= 0; i--) { 2342 PackageSetting ps = mSettings.mPackages.valueAt(i); 2343 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2344 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2345 mSettings.mPackages.removeAt(i); 2346 mSettings.enableSystemPackageLPw(ps.name); 2347 } 2348 } 2349 2350 if (mFirstBoot) { 2351 requestCopyPreoptedFiles(); 2352 } 2353 2354 String customResolverActivity = Resources.getSystem().getString( 2355 R.string.config_customResolverActivity); 2356 if (TextUtils.isEmpty(customResolverActivity)) { 2357 customResolverActivity = null; 2358 } else { 2359 mCustomResolverComponentName = ComponentName.unflattenFromString( 2360 customResolverActivity); 2361 } 2362 2363 long startTime = SystemClock.uptimeMillis(); 2364 2365 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2366 startTime); 2367 2368 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2369 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2370 2371 if (bootClassPath == null) { 2372 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2373 } 2374 2375 if (systemServerClassPath == null) { 2376 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2377 } 2378 2379 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2380 final String[] dexCodeInstructionSets = 2381 getDexCodeInstructionSets( 2382 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2383 2384 /** 2385 * Ensure all external libraries have had dexopt run on them. 2386 */ 2387 if (mSharedLibraries.size() > 0) { 2388 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2389 // NOTE: For now, we're compiling these system "shared libraries" 2390 // (and framework jars) into all available architectures. It's possible 2391 // to compile them only when we come across an app that uses them (there's 2392 // already logic for that in scanPackageLI) but that adds some complexity. 2393 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2394 final int libCount = mSharedLibraries.size(); 2395 for (int i = 0; i < libCount; i++) { 2396 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 2397 final int versionCount = versionedLib.size(); 2398 for (int j = 0; j < versionCount; j++) { 2399 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 2400 final String libPath = libEntry.path != null 2401 ? libEntry.path : libEntry.apk; 2402 if (libPath == null) { 2403 continue; 2404 } 2405 try { 2406 // Shared libraries do not have profiles so we perform a full 2407 // AOT compilation (if needed). 2408 int dexoptNeeded = DexFile.getDexOptNeeded( 2409 libPath, dexCodeInstructionSet, 2410 getCompilerFilterForReason(REASON_SHARED_APK), 2411 false /* newProfile */); 2412 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2413 mInstaller.dexopt(libPath, Process.SYSTEM_UID, "*", 2414 dexCodeInstructionSet, dexoptNeeded, null, 2415 DEXOPT_PUBLIC, 2416 getCompilerFilterForReason(REASON_SHARED_APK), 2417 StorageManager.UUID_PRIVATE_INTERNAL, 2418 PackageDexOptimizer.SKIP_SHARED_LIBRARY_CHECK); 2419 } 2420 } catch (FileNotFoundException e) { 2421 Slog.w(TAG, "Library not found: " + libPath); 2422 } catch (IOException | InstallerException e) { 2423 Slog.w(TAG, "Cannot dexopt " + libPath + "; is it an APK or JAR? " 2424 + e.getMessage()); 2425 } 2426 } 2427 } 2428 } 2429 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2430 } 2431 2432 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2433 2434 final VersionInfo ver = mSettings.getInternalVersion(); 2435 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2436 2437 // when upgrading from pre-M, promote system app permissions from install to runtime 2438 mPromoteSystemApps = 2439 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2440 2441 // When upgrading from pre-N, we need to handle package extraction like first boot, 2442 // as there is no profiling data available. 2443 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2444 2445 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2446 2447 // save off the names of pre-existing system packages prior to scanning; we don't 2448 // want to automatically grant runtime permissions for new system apps 2449 if (mPromoteSystemApps) { 2450 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2451 while (pkgSettingIter.hasNext()) { 2452 PackageSetting ps = pkgSettingIter.next(); 2453 if (isSystemApp(ps)) { 2454 mExistingSystemPackages.add(ps.name); 2455 } 2456 } 2457 } 2458 2459 mCacheDir = preparePackageParserCache(mIsUpgrade); 2460 2461 // Set flag to monitor and not change apk file paths when 2462 // scanning install directories. 2463 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2464 2465 if (mIsUpgrade || mFirstBoot) { 2466 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2467 } 2468 2469 // Collect vendor overlay packages. (Do this before scanning any apps.) 2470 // For security and version matching reason, only consider 2471 // overlay packages if they reside in the right directory. 2472 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2473 | PackageParser.PARSE_IS_SYSTEM 2474 | PackageParser.PARSE_IS_SYSTEM_DIR 2475 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2476 2477 // Find base frameworks (resource packages without code). 2478 scanDirTracedLI(frameworkDir, mDefParseFlags 2479 | PackageParser.PARSE_IS_SYSTEM 2480 | PackageParser.PARSE_IS_SYSTEM_DIR 2481 | PackageParser.PARSE_IS_PRIVILEGED, 2482 scanFlags | SCAN_NO_DEX, 0); 2483 2484 // Collected privileged system packages. 2485 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2486 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2487 | PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR 2489 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2490 2491 // Collect ordinary system packages. 2492 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2493 scanDirTracedLI(systemAppDir, mDefParseFlags 2494 | PackageParser.PARSE_IS_SYSTEM 2495 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2496 2497 // Collect all vendor packages. 2498 File vendorAppDir = new File("/vendor/app"); 2499 try { 2500 vendorAppDir = vendorAppDir.getCanonicalFile(); 2501 } catch (IOException e) { 2502 // failed to look up canonical path, continue with original one 2503 } 2504 scanDirTracedLI(vendorAppDir, mDefParseFlags 2505 | PackageParser.PARSE_IS_SYSTEM 2506 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2507 2508 // Collect all OEM packages. 2509 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2510 scanDirTracedLI(oemAppDir, mDefParseFlags 2511 | PackageParser.PARSE_IS_SYSTEM 2512 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2513 2514 // Prune any system packages that no longer exist. 2515 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2516 if (!mOnlyCore) { 2517 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2518 while (psit.hasNext()) { 2519 PackageSetting ps = psit.next(); 2520 2521 /* 2522 * If this is not a system app, it can't be a 2523 * disable system app. 2524 */ 2525 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2526 continue; 2527 } 2528 2529 /* 2530 * If the package is scanned, it's not erased. 2531 */ 2532 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2533 if (scannedPkg != null) { 2534 /* 2535 * If the system app is both scanned and in the 2536 * disabled packages list, then it must have been 2537 * added via OTA. Remove it from the currently 2538 * scanned package so the previously user-installed 2539 * application can be scanned. 2540 */ 2541 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2542 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2543 + ps.name + "; removing system app. Last known codePath=" 2544 + ps.codePathString + ", installStatus=" + ps.installStatus 2545 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2546 + scannedPkg.mVersionCode); 2547 removePackageLI(scannedPkg, true); 2548 mExpectingBetter.put(ps.name, ps.codePath); 2549 } 2550 2551 continue; 2552 } 2553 2554 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2555 psit.remove(); 2556 logCriticalInfo(Log.WARN, "System package " + ps.name 2557 + " no longer exists; it's data will be wiped"); 2558 // Actual deletion of code and data will be handled by later 2559 // reconciliation step 2560 } else { 2561 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2562 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2563 possiblyDeletedUpdatedSystemApps.add(ps.name); 2564 } 2565 } 2566 } 2567 } 2568 2569 //look for any incomplete package installations 2570 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2571 for (int i = 0; i < deletePkgsList.size(); i++) { 2572 // Actual deletion of code and data will be handled by later 2573 // reconciliation step 2574 final String packageName = deletePkgsList.get(i).name; 2575 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2576 synchronized (mPackages) { 2577 mSettings.removePackageLPw(packageName); 2578 } 2579 } 2580 2581 //delete tmp files 2582 deleteTempPackageFiles(); 2583 2584 // Remove any shared userIDs that have no associated packages 2585 mSettings.pruneSharedUsersLPw(); 2586 2587 if (!mOnlyCore) { 2588 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2589 SystemClock.uptimeMillis()); 2590 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2591 2592 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2593 | PackageParser.PARSE_FORWARD_LOCK, 2594 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2595 2596 /** 2597 * Remove disable package settings for any updated system 2598 * apps that were removed via an OTA. If they're not a 2599 * previously-updated app, remove them completely. 2600 * Otherwise, just revoke their system-level permissions. 2601 */ 2602 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2603 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2604 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2605 2606 String msg; 2607 if (deletedPkg == null) { 2608 msg = "Updated system package " + deletedAppName 2609 + " no longer exists; it's data will be wiped"; 2610 // Actual deletion of code and data will be handled by later 2611 // reconciliation step 2612 } else { 2613 msg = "Updated system app + " + deletedAppName 2614 + " no longer present; removing system privileges for " 2615 + deletedAppName; 2616 2617 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2618 2619 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2620 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2621 } 2622 logCriticalInfo(Log.WARN, msg); 2623 } 2624 2625 /** 2626 * Make sure all system apps that we expected to appear on 2627 * the userdata partition actually showed up. If they never 2628 * appeared, crawl back and revive the system version. 2629 */ 2630 for (int i = 0; i < mExpectingBetter.size(); i++) { 2631 final String packageName = mExpectingBetter.keyAt(i); 2632 if (!mPackages.containsKey(packageName)) { 2633 final File scanFile = mExpectingBetter.valueAt(i); 2634 2635 logCriticalInfo(Log.WARN, "Expected better " + packageName 2636 + " but never showed up; reverting to system"); 2637 2638 int reparseFlags = mDefParseFlags; 2639 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2640 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2641 | PackageParser.PARSE_IS_SYSTEM_DIR 2642 | PackageParser.PARSE_IS_PRIVILEGED; 2643 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2644 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2645 | PackageParser.PARSE_IS_SYSTEM_DIR; 2646 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2647 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2648 | PackageParser.PARSE_IS_SYSTEM_DIR; 2649 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2650 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2651 | PackageParser.PARSE_IS_SYSTEM_DIR; 2652 } else { 2653 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2654 continue; 2655 } 2656 2657 mSettings.enableSystemPackageLPw(packageName); 2658 2659 try { 2660 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2661 } catch (PackageManagerException e) { 2662 Slog.e(TAG, "Failed to parse original system package: " 2663 + e.getMessage()); 2664 } 2665 } 2666 } 2667 } 2668 mExpectingBetter.clear(); 2669 2670 // Resolve the storage manager. 2671 mStorageManagerPackage = getStorageManagerPackageName(); 2672 2673 // Resolve protected action filters. Only the setup wizard is allowed to 2674 // have a high priority filter for these actions. 2675 mSetupWizardPackage = getSetupWizardPackageName(); 2676 if (mProtectedFilters.size() > 0) { 2677 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2678 Slog.i(TAG, "No setup wizard;" 2679 + " All protected intents capped to priority 0"); 2680 } 2681 for (ActivityIntentInfo filter : mProtectedFilters) { 2682 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2683 if (DEBUG_FILTERS) { 2684 Slog.i(TAG, "Found setup wizard;" 2685 + " allow priority " + filter.getPriority() + ";" 2686 + " package: " + filter.activity.info.packageName 2687 + " activity: " + filter.activity.className 2688 + " priority: " + filter.getPriority()); 2689 } 2690 // skip setup wizard; allow it to keep the high priority filter 2691 continue; 2692 } 2693 Slog.w(TAG, "Protected action; cap priority to 0;" 2694 + " package: " + filter.activity.info.packageName 2695 + " activity: " + filter.activity.className 2696 + " origPrio: " + filter.getPriority()); 2697 filter.setPriority(0); 2698 } 2699 } 2700 mDeferProtectedFilters = false; 2701 mProtectedFilters.clear(); 2702 2703 // Now that we know all of the shared libraries, update all clients to have 2704 // the correct library paths. 2705 updateAllSharedLibrariesLPw(null); 2706 2707 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2708 // NOTE: We ignore potential failures here during a system scan (like 2709 // the rest of the commands above) because there's precious little we 2710 // can do about it. A settings error is reported, though. 2711 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2712 } 2713 2714 // Now that we know all the packages we are keeping, 2715 // read and update their last usage times. 2716 mPackageUsage.read(mPackages); 2717 mCompilerStats.read(); 2718 2719 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2720 SystemClock.uptimeMillis()); 2721 Slog.i(TAG, "Time to scan packages: " 2722 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2723 + " seconds"); 2724 2725 // If the platform SDK has changed since the last time we booted, 2726 // we need to re-grant app permission to catch any new ones that 2727 // appear. This is really a hack, and means that apps can in some 2728 // cases get permissions that the user didn't initially explicitly 2729 // allow... it would be nice to have some better way to handle 2730 // this situation. 2731 int updateFlags = UPDATE_PERMISSIONS_ALL; 2732 if (ver.sdkVersion != mSdkVersion) { 2733 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2734 + mSdkVersion + "; regranting permissions for internal storage"); 2735 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2736 } 2737 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2738 ver.sdkVersion = mSdkVersion; 2739 2740 // If this is the first boot or an update from pre-M, and it is a normal 2741 // boot, then we need to initialize the default preferred apps across 2742 // all defined users. 2743 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2744 for (UserInfo user : sUserManager.getUsers(true)) { 2745 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2746 applyFactoryDefaultBrowserLPw(user.id); 2747 primeDomainVerificationsLPw(user.id); 2748 } 2749 } 2750 2751 // Prepare storage for system user really early during boot, 2752 // since core system apps like SettingsProvider and SystemUI 2753 // can't wait for user to start 2754 final int storageFlags; 2755 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2756 storageFlags = StorageManager.FLAG_STORAGE_DE; 2757 } else { 2758 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2759 } 2760 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2761 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2762 true /* onlyCoreApps */); 2763 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2764 if (deferPackages == null || deferPackages.isEmpty()) { 2765 return; 2766 } 2767 int count = 0; 2768 for (String pkgName : deferPackages) { 2769 PackageParser.Package pkg = null; 2770 synchronized (mPackages) { 2771 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2772 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2773 pkg = ps.pkg; 2774 } 2775 } 2776 if (pkg != null) { 2777 synchronized (mInstallLock) { 2778 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2779 true /* maybeMigrateAppData */); 2780 } 2781 count++; 2782 } 2783 } 2784 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2785 }, "prepareAppData"); 2786 2787 // If this is first boot after an OTA, and a normal boot, then 2788 // we need to clear code cache directories. 2789 // Note that we do *not* clear the application profiles. These remain valid 2790 // across OTAs and are used to drive profile verification (post OTA) and 2791 // profile compilation (without waiting to collect a fresh set of profiles). 2792 if (mIsUpgrade && !onlyCore) { 2793 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2794 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2795 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2796 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2797 // No apps are running this early, so no need to freeze 2798 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2799 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2800 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2801 } 2802 } 2803 ver.fingerprint = Build.FINGERPRINT; 2804 } 2805 2806 checkDefaultBrowser(); 2807 2808 // clear only after permissions and other defaults have been updated 2809 mExistingSystemPackages.clear(); 2810 mPromoteSystemApps = false; 2811 2812 // All the changes are done during package scanning. 2813 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2814 2815 // can downgrade to reader 2816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2817 mSettings.writeLPr(); 2818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2819 2820 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2821 // early on (before the package manager declares itself as early) because other 2822 // components in the system server might ask for package contexts for these apps. 2823 // 2824 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2825 // (i.e, that the data partition is unavailable). 2826 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2827 long start = System.nanoTime(); 2828 List<PackageParser.Package> coreApps = new ArrayList<>(); 2829 for (PackageParser.Package pkg : mPackages.values()) { 2830 if (pkg.coreApp) { 2831 coreApps.add(pkg); 2832 } 2833 } 2834 2835 int[] stats = performDexOptUpgrade(coreApps, false, 2836 getCompilerFilterForReason(REASON_CORE_APP)); 2837 2838 final int elapsedTimeSeconds = 2839 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2840 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2841 2842 if (DEBUG_DEXOPT) { 2843 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2844 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2845 } 2846 2847 2848 // TODO: Should we log these stats to tron too ? 2849 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2850 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2851 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2852 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2853 } 2854 2855 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2856 SystemClock.uptimeMillis()); 2857 2858 if (!mOnlyCore) { 2859 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2860 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2861 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2862 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2863 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2864 mIntentFilterVerifierComponent); 2865 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2866 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2867 SharedLibraryInfo.VERSION_UNDEFINED); 2868 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2869 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2870 SharedLibraryInfo.VERSION_UNDEFINED); 2871 } else { 2872 mRequiredVerifierPackage = null; 2873 mRequiredInstallerPackage = null; 2874 mRequiredUninstallerPackage = null; 2875 mIntentFilterVerifierComponent = null; 2876 mIntentFilterVerifier = null; 2877 mServicesSystemSharedLibraryPackageName = null; 2878 mSharedSystemSharedLibraryPackageName = null; 2879 } 2880 2881 mInstallerService = new PackageInstallerService(context, this); 2882 2883 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2884 if (ephemeralResolverComponent != null) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2887 } 2888 mInstantAppResolverConnection = 2889 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2890 } else { 2891 mInstantAppResolverConnection = null; 2892 } 2893 mInstantAppInstallerComponent = getEphemeralInstallerLPr(); 2894 if (mInstantAppInstallerComponent != null) { 2895 if (DEBUG_EPHEMERAL) { 2896 Slog.i(TAG, "Ephemeral installer: " + mInstantAppInstallerComponent); 2897 } 2898 setUpInstantAppInstallerActivityLP(mInstantAppInstallerComponent); 2899 } 2900 2901 // Read and update the usage of dex files. 2902 // Do this at the end of PM init so that all the packages have their 2903 // data directory reconciled. 2904 // At this point we know the code paths of the packages, so we can validate 2905 // the disk file and build the internal cache. 2906 // The usage file is expected to be small so loading and verifying it 2907 // should take a fairly small time compare to the other activities (e.g. package 2908 // scanning). 2909 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2910 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2911 for (int userId : currentUserIds) { 2912 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2913 } 2914 mDexManager.load(userPackages); 2915 } // synchronized (mPackages) 2916 } // synchronized (mInstallLock) 2917 2918 // Now after opening every single application zip, make sure they 2919 // are all flushed. Not really needed, but keeps things nice and 2920 // tidy. 2921 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2922 Runtime.getRuntime().gc(); 2923 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2924 2925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2926 FallbackCategoryProvider.loadFallbacks(); 2927 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2928 2929 // The initial scanning above does many calls into installd while 2930 // holding the mPackages lock, but we're mostly interested in yelling 2931 // once we have a booted system. 2932 mInstaller.setWarnIfHeld(mPackages); 2933 2934 // Expose private service for system components to use. 2935 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2936 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2937 } 2938 2939 private static File preparePackageParserCache(boolean isUpgrade) { 2940 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2941 return null; 2942 } 2943 2944 // Disable package parsing on eng builds to allow for faster incremental development. 2945 if ("eng".equals(Build.TYPE)) { 2946 return null; 2947 } 2948 2949 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2950 Slog.i(TAG, "Disabling package parser cache due to system property."); 2951 return null; 2952 } 2953 2954 // The base directory for the package parser cache lives under /data/system/. 2955 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2956 "package_cache"); 2957 if (cacheBaseDir == null) { 2958 return null; 2959 } 2960 2961 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2962 // This also serves to "GC" unused entries when the package cache version changes (which 2963 // can only happen during upgrades). 2964 if (isUpgrade) { 2965 FileUtils.deleteContents(cacheBaseDir); 2966 } 2967 2968 2969 // Return the versioned package cache directory. This is something like 2970 // "/data/system/package_cache/1" 2971 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2972 2973 // The following is a workaround to aid development on non-numbered userdebug 2974 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2975 // the system partition is newer. 2976 // 2977 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2978 // that starts with "eng." to signify that this is an engineering build and not 2979 // destined for release. 2980 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2981 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2982 2983 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2984 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2985 // in general and should not be used for production changes. In this specific case, 2986 // we know that they will work. 2987 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2988 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2989 FileUtils.deleteContents(cacheBaseDir); 2990 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2991 } 2992 } 2993 2994 return cacheDir; 2995 } 2996 2997 @Override 2998 public boolean isFirstBoot() { 2999 return mFirstBoot; 3000 } 3001 3002 @Override 3003 public boolean isOnlyCoreApps() { 3004 return mOnlyCore; 3005 } 3006 3007 @Override 3008 public boolean isUpgrade() { 3009 return mIsUpgrade; 3010 } 3011 3012 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3013 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3014 3015 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3016 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3017 UserHandle.USER_SYSTEM); 3018 if (matches.size() == 1) { 3019 return matches.get(0).getComponentInfo().packageName; 3020 } else if (matches.size() == 0) { 3021 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3022 return null; 3023 } 3024 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3025 } 3026 3027 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3028 synchronized (mPackages) { 3029 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3030 if (libraryEntry == null) { 3031 throw new IllegalStateException("Missing required shared library:" + name); 3032 } 3033 return libraryEntry.apk; 3034 } 3035 } 3036 3037 private @NonNull String getRequiredInstallerLPr() { 3038 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3039 intent.addCategory(Intent.CATEGORY_DEFAULT); 3040 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3041 3042 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3043 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3044 UserHandle.USER_SYSTEM); 3045 if (matches.size() == 1) { 3046 ResolveInfo resolveInfo = matches.get(0); 3047 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3048 throw new RuntimeException("The installer must be a privileged app"); 3049 } 3050 return matches.get(0).getComponentInfo().packageName; 3051 } else { 3052 throw new RuntimeException("There must be exactly one installer; found " + matches); 3053 } 3054 } 3055 3056 private @NonNull String getRequiredUninstallerLPr() { 3057 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3058 intent.addCategory(Intent.CATEGORY_DEFAULT); 3059 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3060 3061 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3062 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3063 UserHandle.USER_SYSTEM); 3064 if (resolveInfo == null || 3065 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3066 throw new RuntimeException("There must be exactly one uninstaller; found " 3067 + resolveInfo); 3068 } 3069 return resolveInfo.getComponentInfo().packageName; 3070 } 3071 3072 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3073 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3074 3075 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3076 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3077 UserHandle.USER_SYSTEM); 3078 ResolveInfo best = null; 3079 final int N = matches.size(); 3080 for (int i = 0; i < N; i++) { 3081 final ResolveInfo cur = matches.get(i); 3082 final String packageName = cur.getComponentInfo().packageName; 3083 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3084 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3085 continue; 3086 } 3087 3088 if (best == null || cur.priority > best.priority) { 3089 best = cur; 3090 } 3091 } 3092 3093 if (best != null) { 3094 return best.getComponentInfo().getComponentName(); 3095 } else { 3096 throw new RuntimeException("There must be at least one intent filter verifier"); 3097 } 3098 } 3099 3100 private @Nullable ComponentName getEphemeralResolverLPr() { 3101 final String[] packageArray = 3102 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3103 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3104 if (DEBUG_EPHEMERAL) { 3105 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3106 } 3107 return null; 3108 } 3109 3110 final int resolveFlags = 3111 MATCH_DIRECT_BOOT_AWARE 3112 | MATCH_DIRECT_BOOT_UNAWARE 3113 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3114 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 3115 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3116 resolveFlags, UserHandle.USER_SYSTEM); 3117 3118 final int N = resolvers.size(); 3119 if (N == 0) { 3120 if (DEBUG_EPHEMERAL) { 3121 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3122 } 3123 return null; 3124 } 3125 3126 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3127 for (int i = 0; i < N; i++) { 3128 final ResolveInfo info = resolvers.get(i); 3129 3130 if (info.serviceInfo == null) { 3131 continue; 3132 } 3133 3134 final String packageName = info.serviceInfo.packageName; 3135 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3136 if (DEBUG_EPHEMERAL) { 3137 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3138 + " pkg: " + packageName + ", info:" + info); 3139 } 3140 continue; 3141 } 3142 3143 if (DEBUG_EPHEMERAL) { 3144 Slog.v(TAG, "Ephemeral resolver found;" 3145 + " pkg: " + packageName + ", info:" + info); 3146 } 3147 return new ComponentName(packageName, info.serviceInfo.name); 3148 } 3149 if (DEBUG_EPHEMERAL) { 3150 Slog.v(TAG, "Ephemeral resolver NOT found"); 3151 } 3152 return null; 3153 } 3154 3155 private @Nullable ComponentName getEphemeralInstallerLPr() { 3156 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3157 intent.addCategory(Intent.CATEGORY_DEFAULT); 3158 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3159 3160 final int resolveFlags = 3161 MATCH_DIRECT_BOOT_AWARE 3162 | MATCH_DIRECT_BOOT_UNAWARE 3163 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3164 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3165 resolveFlags, UserHandle.USER_SYSTEM); 3166 Iterator<ResolveInfo> iter = matches.iterator(); 3167 while (iter.hasNext()) { 3168 final ResolveInfo rInfo = iter.next(); 3169 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3170 if (ps != null) { 3171 final PermissionsState permissionsState = ps.getPermissionsState(); 3172 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3173 continue; 3174 } 3175 } 3176 iter.remove(); 3177 } 3178 if (matches.size() == 0) { 3179 return null; 3180 } else if (matches.size() == 1) { 3181 return matches.get(0).getComponentInfo().getComponentName(); 3182 } else { 3183 throw new RuntimeException( 3184 "There must be at most one ephemeral installer; found " + matches); 3185 } 3186 } 3187 3188 private void primeDomainVerificationsLPw(int userId) { 3189 if (DEBUG_DOMAIN_VERIFICATION) { 3190 Slog.d(TAG, "Priming domain verifications in user " + userId); 3191 } 3192 3193 SystemConfig systemConfig = SystemConfig.getInstance(); 3194 ArraySet<String> packages = systemConfig.getLinkedApps(); 3195 3196 for (String packageName : packages) { 3197 PackageParser.Package pkg = mPackages.get(packageName); 3198 if (pkg != null) { 3199 if (!pkg.isSystemApp()) { 3200 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3201 continue; 3202 } 3203 3204 ArraySet<String> domains = null; 3205 for (PackageParser.Activity a : pkg.activities) { 3206 for (ActivityIntentInfo filter : a.intents) { 3207 if (hasValidDomains(filter)) { 3208 if (domains == null) { 3209 domains = new ArraySet<String>(); 3210 } 3211 domains.addAll(filter.getHostsList()); 3212 } 3213 } 3214 } 3215 3216 if (domains != null && domains.size() > 0) { 3217 if (DEBUG_DOMAIN_VERIFICATION) { 3218 Slog.v(TAG, " + " + packageName); 3219 } 3220 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3221 // state w.r.t. the formal app-linkage "no verification attempted" state; 3222 // and then 'always' in the per-user state actually used for intent resolution. 3223 final IntentFilterVerificationInfo ivi; 3224 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3225 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3226 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3227 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3228 } else { 3229 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3230 + "' does not handle web links"); 3231 } 3232 } else { 3233 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3234 } 3235 } 3236 3237 scheduleWritePackageRestrictionsLocked(userId); 3238 scheduleWriteSettingsLocked(); 3239 } 3240 3241 private void applyFactoryDefaultBrowserLPw(int userId) { 3242 // The default browser app's package name is stored in a string resource, 3243 // with a product-specific overlay used for vendor customization. 3244 String browserPkg = mContext.getResources().getString( 3245 com.android.internal.R.string.default_browser); 3246 if (!TextUtils.isEmpty(browserPkg)) { 3247 // non-empty string => required to be a known package 3248 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3249 if (ps == null) { 3250 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3251 browserPkg = null; 3252 } else { 3253 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3254 } 3255 } 3256 3257 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3258 // default. If there's more than one, just leave everything alone. 3259 if (browserPkg == null) { 3260 calculateDefaultBrowserLPw(userId); 3261 } 3262 } 3263 3264 private void calculateDefaultBrowserLPw(int userId) { 3265 List<String> allBrowsers = resolveAllBrowserApps(userId); 3266 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3267 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3268 } 3269 3270 private List<String> resolveAllBrowserApps(int userId) { 3271 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3272 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3273 PackageManager.MATCH_ALL, userId); 3274 3275 final int count = list.size(); 3276 List<String> result = new ArrayList<String>(count); 3277 for (int i=0; i<count; i++) { 3278 ResolveInfo info = list.get(i); 3279 if (info.activityInfo == null 3280 || !info.handleAllWebDataURI 3281 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3282 || result.contains(info.activityInfo.packageName)) { 3283 continue; 3284 } 3285 result.add(info.activityInfo.packageName); 3286 } 3287 3288 return result; 3289 } 3290 3291 private boolean packageIsBrowser(String packageName, int userId) { 3292 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3293 PackageManager.MATCH_ALL, userId); 3294 final int N = list.size(); 3295 for (int i = 0; i < N; i++) { 3296 ResolveInfo info = list.get(i); 3297 if (packageName.equals(info.activityInfo.packageName)) { 3298 return true; 3299 } 3300 } 3301 return false; 3302 } 3303 3304 private void checkDefaultBrowser() { 3305 final int myUserId = UserHandle.myUserId(); 3306 final String packageName = getDefaultBrowserPackageName(myUserId); 3307 if (packageName != null) { 3308 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3309 if (info == null) { 3310 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3311 synchronized (mPackages) { 3312 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3313 } 3314 } 3315 } 3316 } 3317 3318 @Override 3319 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3320 throws RemoteException { 3321 try { 3322 return super.onTransact(code, data, reply, flags); 3323 } catch (RuntimeException e) { 3324 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3325 Slog.wtf(TAG, "Package Manager Crash", e); 3326 } 3327 throw e; 3328 } 3329 } 3330 3331 static int[] appendInts(int[] cur, int[] add) { 3332 if (add == null) return cur; 3333 if (cur == null) return add; 3334 final int N = add.length; 3335 for (int i=0; i<N; i++) { 3336 cur = appendInt(cur, add[i]); 3337 } 3338 return cur; 3339 } 3340 3341 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3342 if (!sUserManager.exists(userId)) return null; 3343 if (ps == null) { 3344 return null; 3345 } 3346 final PackageParser.Package p = ps.pkg; 3347 if (p == null) { 3348 return null; 3349 } 3350 // Filter out ephemeral app metadata: 3351 // * The system/shell/root can see metadata for any app 3352 // * An installed app can see metadata for 1) other installed apps 3353 // and 2) ephemeral apps that have explicitly interacted with it 3354 // * Ephemeral apps can only see their own data and exposed installed apps 3355 // * Holding a signature permission allows seeing instant apps 3356 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3357 if (callingAppId != Process.SYSTEM_UID 3358 && callingAppId != Process.SHELL_UID 3359 && callingAppId != Process.ROOT_UID 3360 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3361 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3362 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3363 if (instantAppPackageName != null) { 3364 // ephemeral apps can only get information on themselves or 3365 // installed apps that are exposed. 3366 if (!instantAppPackageName.equals(p.packageName) 3367 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3368 return null; 3369 } 3370 } else { 3371 if (ps.getInstantApp(userId)) { 3372 // only get access to the ephemeral app if we've been granted access 3373 if (!mInstantAppRegistry.isInstantAccessGranted( 3374 userId, callingAppId, ps.appId)) { 3375 return null; 3376 } 3377 } 3378 } 3379 } 3380 3381 final PermissionsState permissionsState = ps.getPermissionsState(); 3382 3383 // Compute GIDs only if requested 3384 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3385 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3386 // Compute granted permissions only if package has requested permissions 3387 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3388 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3389 final PackageUserState state = ps.readUserState(userId); 3390 3391 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3392 && ps.isSystem()) { 3393 flags |= MATCH_ANY_USER; 3394 } 3395 3396 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3397 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3398 3399 if (packageInfo == null) { 3400 return null; 3401 } 3402 3403 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3404 3405 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3406 resolveExternalPackageNameLPr(p); 3407 3408 return packageInfo; 3409 } 3410 3411 @Override 3412 public void checkPackageStartable(String packageName, int userId) { 3413 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3414 3415 synchronized (mPackages) { 3416 final PackageSetting ps = mSettings.mPackages.get(packageName); 3417 if (ps == null) { 3418 throw new SecurityException("Package " + packageName + " was not found!"); 3419 } 3420 3421 if (!ps.getInstalled(userId)) { 3422 throw new SecurityException( 3423 "Package " + packageName + " was not installed for user " + userId + "!"); 3424 } 3425 3426 if (mSafeMode && !ps.isSystem()) { 3427 throw new SecurityException("Package " + packageName + " not a system app!"); 3428 } 3429 3430 if (mFrozenPackages.contains(packageName)) { 3431 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3432 } 3433 3434 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3435 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3436 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3437 } 3438 } 3439 } 3440 3441 @Override 3442 public boolean isPackageAvailable(String packageName, int userId) { 3443 if (!sUserManager.exists(userId)) return false; 3444 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3445 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3446 synchronized (mPackages) { 3447 PackageParser.Package p = mPackages.get(packageName); 3448 if (p != null) { 3449 final PackageSetting ps = (PackageSetting) p.mExtras; 3450 if (ps != null) { 3451 final PackageUserState state = ps.readUserState(userId); 3452 if (state != null) { 3453 return PackageParser.isAvailable(state); 3454 } 3455 } 3456 } 3457 } 3458 return false; 3459 } 3460 3461 @Override 3462 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3463 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3464 flags, userId); 3465 } 3466 3467 @Override 3468 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3469 int flags, int userId) { 3470 return getPackageInfoInternal(versionedPackage.getPackageName(), 3471 // TODO: We will change version code to long, so in the new API it is long 3472 (int) versionedPackage.getVersionCode(), flags, userId); 3473 } 3474 3475 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3476 int flags, int userId) { 3477 if (!sUserManager.exists(userId)) return null; 3478 flags = updateFlagsForPackage(flags, userId, packageName); 3479 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3480 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3481 3482 // reader 3483 synchronized (mPackages) { 3484 // Normalize package name to handle renamed packages and static libs 3485 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3486 3487 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3488 if (matchFactoryOnly) { 3489 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3490 if (ps != null) { 3491 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3492 return null; 3493 } 3494 return generatePackageInfo(ps, flags, userId); 3495 } 3496 } 3497 3498 PackageParser.Package p = mPackages.get(packageName); 3499 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3500 return null; 3501 } 3502 if (DEBUG_PACKAGE_INFO) 3503 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3504 if (p != null) { 3505 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3506 Binder.getCallingUid(), userId)) { 3507 return null; 3508 } 3509 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3510 } 3511 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3512 final PackageSetting ps = mSettings.mPackages.get(packageName); 3513 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3514 return null; 3515 } 3516 return generatePackageInfo(ps, flags, userId); 3517 } 3518 } 3519 return null; 3520 } 3521 3522 3523 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3524 // System/shell/root get to see all static libs 3525 final int appId = UserHandle.getAppId(uid); 3526 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3527 || appId == Process.ROOT_UID) { 3528 return false; 3529 } 3530 3531 // No package means no static lib as it is always on internal storage 3532 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3533 return false; 3534 } 3535 3536 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3537 ps.pkg.staticSharedLibVersion); 3538 if (libEntry == null) { 3539 return false; 3540 } 3541 3542 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3543 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3544 if (uidPackageNames == null) { 3545 return true; 3546 } 3547 3548 for (String uidPackageName : uidPackageNames) { 3549 if (ps.name.equals(uidPackageName)) { 3550 return false; 3551 } 3552 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3553 if (uidPs != null) { 3554 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3555 libEntry.info.getName()); 3556 if (index < 0) { 3557 continue; 3558 } 3559 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3560 return false; 3561 } 3562 } 3563 } 3564 return true; 3565 } 3566 3567 @Override 3568 public String[] currentToCanonicalPackageNames(String[] names) { 3569 String[] out = new String[names.length]; 3570 // reader 3571 synchronized (mPackages) { 3572 for (int i=names.length-1; i>=0; i--) { 3573 PackageSetting ps = mSettings.mPackages.get(names[i]); 3574 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3575 } 3576 } 3577 return out; 3578 } 3579 3580 @Override 3581 public String[] canonicalToCurrentPackageNames(String[] names) { 3582 String[] out = new String[names.length]; 3583 // reader 3584 synchronized (mPackages) { 3585 for (int i=names.length-1; i>=0; i--) { 3586 String cur = mSettings.getRenamedPackageLPr(names[i]); 3587 out[i] = cur != null ? cur : names[i]; 3588 } 3589 } 3590 return out; 3591 } 3592 3593 @Override 3594 public int getPackageUid(String packageName, int flags, int userId) { 3595 if (!sUserManager.exists(userId)) return -1; 3596 flags = updateFlagsForPackage(flags, userId, packageName); 3597 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3598 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3599 3600 // reader 3601 synchronized (mPackages) { 3602 final PackageParser.Package p = mPackages.get(packageName); 3603 if (p != null && p.isMatch(flags)) { 3604 return UserHandle.getUid(userId, p.applicationInfo.uid); 3605 } 3606 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3607 final PackageSetting ps = mSettings.mPackages.get(packageName); 3608 if (ps != null && ps.isMatch(flags)) { 3609 return UserHandle.getUid(userId, ps.appId); 3610 } 3611 } 3612 } 3613 3614 return -1; 3615 } 3616 3617 @Override 3618 public int[] getPackageGids(String packageName, int flags, int userId) { 3619 if (!sUserManager.exists(userId)) return null; 3620 flags = updateFlagsForPackage(flags, userId, packageName); 3621 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3622 false /* requireFullPermission */, false /* checkShell */, 3623 "getPackageGids"); 3624 3625 // reader 3626 synchronized (mPackages) { 3627 final PackageParser.Package p = mPackages.get(packageName); 3628 if (p != null && p.isMatch(flags)) { 3629 PackageSetting ps = (PackageSetting) p.mExtras; 3630 // TODO: Shouldn't this be checking for package installed state for userId and 3631 // return null? 3632 return ps.getPermissionsState().computeGids(userId); 3633 } 3634 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3635 final PackageSetting ps = mSettings.mPackages.get(packageName); 3636 if (ps != null && ps.isMatch(flags)) { 3637 return ps.getPermissionsState().computeGids(userId); 3638 } 3639 } 3640 } 3641 3642 return null; 3643 } 3644 3645 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3646 if (bp.perm != null) { 3647 return PackageParser.generatePermissionInfo(bp.perm, flags); 3648 } 3649 PermissionInfo pi = new PermissionInfo(); 3650 pi.name = bp.name; 3651 pi.packageName = bp.sourcePackage; 3652 pi.nonLocalizedLabel = bp.name; 3653 pi.protectionLevel = bp.protectionLevel; 3654 return pi; 3655 } 3656 3657 @Override 3658 public PermissionInfo getPermissionInfo(String name, int flags) { 3659 // reader 3660 synchronized (mPackages) { 3661 final BasePermission p = mSettings.mPermissions.get(name); 3662 if (p != null) { 3663 return generatePermissionInfo(p, flags); 3664 } 3665 return null; 3666 } 3667 } 3668 3669 @Override 3670 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3671 int flags) { 3672 // reader 3673 synchronized (mPackages) { 3674 if (group != null && !mPermissionGroups.containsKey(group)) { 3675 // This is thrown as NameNotFoundException 3676 return null; 3677 } 3678 3679 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3680 for (BasePermission p : mSettings.mPermissions.values()) { 3681 if (group == null) { 3682 if (p.perm == null || p.perm.info.group == null) { 3683 out.add(generatePermissionInfo(p, flags)); 3684 } 3685 } else { 3686 if (p.perm != null && group.equals(p.perm.info.group)) { 3687 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3688 } 3689 } 3690 } 3691 return new ParceledListSlice<>(out); 3692 } 3693 } 3694 3695 @Override 3696 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3697 // reader 3698 synchronized (mPackages) { 3699 return PackageParser.generatePermissionGroupInfo( 3700 mPermissionGroups.get(name), flags); 3701 } 3702 } 3703 3704 @Override 3705 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3706 // reader 3707 synchronized (mPackages) { 3708 final int N = mPermissionGroups.size(); 3709 ArrayList<PermissionGroupInfo> out 3710 = new ArrayList<PermissionGroupInfo>(N); 3711 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3712 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3713 } 3714 return new ParceledListSlice<>(out); 3715 } 3716 } 3717 3718 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3719 int uid, int userId) { 3720 if (!sUserManager.exists(userId)) return null; 3721 PackageSetting ps = mSettings.mPackages.get(packageName); 3722 if (ps != null) { 3723 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3724 return null; 3725 } 3726 if (ps.pkg == null) { 3727 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3728 if (pInfo != null) { 3729 return pInfo.applicationInfo; 3730 } 3731 return null; 3732 } 3733 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3734 ps.readUserState(userId), userId); 3735 if (ai != null) { 3736 rebaseEnabledOverlays(ai, userId); 3737 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3738 } 3739 return ai; 3740 } 3741 return null; 3742 } 3743 3744 @Override 3745 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3746 if (!sUserManager.exists(userId)) return null; 3747 flags = updateFlagsForApplication(flags, userId, packageName); 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3749 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3750 3751 // writer 3752 synchronized (mPackages) { 3753 // Normalize package name to handle renamed packages and static libs 3754 packageName = resolveInternalPackageNameLPr(packageName, 3755 PackageManager.VERSION_CODE_HIGHEST); 3756 3757 PackageParser.Package p = mPackages.get(packageName); 3758 if (DEBUG_PACKAGE_INFO) Log.v( 3759 TAG, "getApplicationInfo " + packageName 3760 + ": " + p); 3761 if (p != null) { 3762 PackageSetting ps = mSettings.mPackages.get(packageName); 3763 if (ps == null) return null; 3764 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3765 return null; 3766 } 3767 // Note: isEnabledLP() does not apply here - always return info 3768 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3769 p, flags, ps.readUserState(userId), userId); 3770 if (ai != null) { 3771 rebaseEnabledOverlays(ai, userId); 3772 ai.packageName = resolveExternalPackageNameLPr(p); 3773 } 3774 return ai; 3775 } 3776 if ("android".equals(packageName)||"system".equals(packageName)) { 3777 return mAndroidApplication; 3778 } 3779 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3780 // Already generates the external package name 3781 return generateApplicationInfoFromSettingsLPw(packageName, 3782 Binder.getCallingUid(), flags, userId); 3783 } 3784 } 3785 return null; 3786 } 3787 3788 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3789 List<String> paths = new ArrayList<>(); 3790 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3791 mEnabledOverlayPaths.get(userId); 3792 if (userSpecificOverlays != null) { 3793 if (!"android".equals(ai.packageName)) { 3794 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3795 if (frameworkOverlays != null) { 3796 paths.addAll(frameworkOverlays); 3797 } 3798 } 3799 3800 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3801 if (appOverlays != null) { 3802 paths.addAll(appOverlays); 3803 } 3804 } 3805 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3806 } 3807 3808 private String normalizePackageNameLPr(String packageName) { 3809 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3810 return normalizedPackageName != null ? normalizedPackageName : packageName; 3811 } 3812 3813 @Override 3814 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3815 final IPackageDataObserver observer) { 3816 mContext.enforceCallingOrSelfPermission( 3817 android.Manifest.permission.CLEAR_APP_CACHE, null); 3818 mHandler.post(() -> { 3819 boolean success = false; 3820 try { 3821 freeStorage(volumeUuid, freeStorageSize, 0); 3822 success = true; 3823 } catch (IOException e) { 3824 Slog.w(TAG, e); 3825 } 3826 if (observer != null) { 3827 try { 3828 observer.onRemoveCompleted(null, success); 3829 } catch (RemoteException e) { 3830 Slog.w(TAG, e); 3831 } 3832 } 3833 }); 3834 } 3835 3836 @Override 3837 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3838 final IntentSender pi) { 3839 mContext.enforceCallingOrSelfPermission( 3840 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3841 mHandler.post(() -> { 3842 boolean success = false; 3843 try { 3844 freeStorage(volumeUuid, freeStorageSize, 0); 3845 success = true; 3846 } catch (IOException e) { 3847 Slog.w(TAG, e); 3848 } 3849 if (pi != null) { 3850 try { 3851 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3852 } catch (SendIntentException e) { 3853 Slog.w(TAG, e); 3854 } 3855 } 3856 }); 3857 } 3858 3859 /** 3860 * Blocking call to clear various types of cached data across the system 3861 * until the requested bytes are available. 3862 */ 3863 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3864 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3865 final File file = storage.findPathForUuid(volumeUuid); 3866 3867 if (ENABLE_FREE_CACHE_V2) { 3868 final boolean aggressive = (storageFlags 3869 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3870 3871 // 1. Pre-flight to determine if we have any chance to succeed 3872 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 3873 3874 // 3. Consider parsed APK data (aggressive only) 3875 if (aggressive) { 3876 FileUtils.deleteContents(mCacheDir); 3877 } 3878 if (file.getUsableSpace() >= bytes) return; 3879 3880 // 4. Consider cached app data (above quotas) 3881 try { 3882 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3883 } catch (InstallerException ignored) { 3884 } 3885 if (file.getUsableSpace() >= bytes) return; 3886 3887 // 5. Consider shared libraries with refcount=0 and age>2h 3888 // 6. Consider dexopt output (aggressive only) 3889 // 7. Consider ephemeral apps not used in last week 3890 3891 // 8. Consider cached app data (below quotas) 3892 try { 3893 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3894 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3895 } catch (InstallerException ignored) { 3896 } 3897 if (file.getUsableSpace() >= bytes) return; 3898 3899 // 9. Consider DropBox entries 3900 // 10. Consider ephemeral cookies 3901 3902 } else { 3903 try { 3904 mInstaller.freeCache(volumeUuid, bytes, 0); 3905 } catch (InstallerException ignored) { 3906 } 3907 if (file.getUsableSpace() >= bytes) return; 3908 } 3909 3910 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3911 } 3912 3913 /** 3914 * Update given flags based on encryption status of current user. 3915 */ 3916 private int updateFlags(int flags, int userId) { 3917 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3918 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3919 // Caller expressed an explicit opinion about what encryption 3920 // aware/unaware components they want to see, so fall through and 3921 // give them what they want 3922 } else { 3923 // Caller expressed no opinion, so match based on user state 3924 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3925 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3926 } else { 3927 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3928 } 3929 } 3930 return flags; 3931 } 3932 3933 private UserManagerInternal getUserManagerInternal() { 3934 if (mUserManagerInternal == null) { 3935 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3936 } 3937 return mUserManagerInternal; 3938 } 3939 3940 private DeviceIdleController.LocalService getDeviceIdleController() { 3941 if (mDeviceIdleController == null) { 3942 mDeviceIdleController = 3943 LocalServices.getService(DeviceIdleController.LocalService.class); 3944 } 3945 return mDeviceIdleController; 3946 } 3947 3948 /** 3949 * Update given flags when being used to request {@link PackageInfo}. 3950 */ 3951 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3952 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3953 boolean triaged = true; 3954 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3955 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3956 // Caller is asking for component details, so they'd better be 3957 // asking for specific encryption matching behavior, or be triaged 3958 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3959 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3960 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3961 triaged = false; 3962 } 3963 } 3964 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3965 | PackageManager.MATCH_SYSTEM_ONLY 3966 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3967 triaged = false; 3968 } 3969 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3970 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3971 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3972 + Debug.getCallers(5)); 3973 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3974 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3975 // If the caller wants all packages and has a restricted profile associated with it, 3976 // then match all users. This is to make sure that launchers that need to access work 3977 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3978 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3979 flags |= PackageManager.MATCH_ANY_USER; 3980 } 3981 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3982 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3983 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3984 } 3985 return updateFlags(flags, userId); 3986 } 3987 3988 /** 3989 * Update given flags when being used to request {@link ApplicationInfo}. 3990 */ 3991 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3992 return updateFlagsForPackage(flags, userId, cookie); 3993 } 3994 3995 /** 3996 * Update given flags when being used to request {@link ComponentInfo}. 3997 */ 3998 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3999 if (cookie instanceof Intent) { 4000 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4001 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4002 } 4003 } 4004 4005 boolean triaged = true; 4006 // Caller is asking for component details, so they'd better be 4007 // asking for specific encryption matching behavior, or be triaged 4008 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4009 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4010 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4011 triaged = false; 4012 } 4013 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4014 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4015 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4016 } 4017 4018 return updateFlags(flags, userId); 4019 } 4020 4021 /** 4022 * Update given intent when being used to request {@link ResolveInfo}. 4023 */ 4024 private Intent updateIntentForResolve(Intent intent) { 4025 if (intent.getSelector() != null) { 4026 intent = intent.getSelector(); 4027 } 4028 if (DEBUG_PREFERRED) { 4029 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4030 } 4031 return intent; 4032 } 4033 4034 /** 4035 * Update given flags when being used to request {@link ResolveInfo}. 4036 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4037 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4038 * flag set. However, this flag is only honoured in three circumstances: 4039 * <ul> 4040 * <li>when called from a system process</li> 4041 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4042 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4043 * action and a {@code android.intent.category.BROWSABLE} category</li> 4044 * </ul> 4045 */ 4046 int updateFlagsForResolve(int flags, int userId, Intent intent, boolean includeInstantApp) { 4047 // Safe mode means we shouldn't match any third-party components 4048 if (mSafeMode) { 4049 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4050 } 4051 final int callingUid = Binder.getCallingUid(); 4052 if (getInstantAppPackageName(callingUid) != null) { 4053 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4054 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4055 flags |= PackageManager.MATCH_INSTANT; 4056 } else { 4057 // Otherwise, prevent leaking ephemeral components 4058 final boolean isSpecialProcess = 4059 callingUid == Process.SYSTEM_UID 4060 || callingUid == Process.SHELL_UID 4061 || callingUid == 0; 4062 final boolean allowMatchInstant = 4063 (includeInstantApp 4064 && Intent.ACTION_VIEW.equals(intent.getAction()) 4065 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4066 && hasWebURI(intent)) 4067 || isSpecialProcess 4068 || mContext.checkCallingOrSelfPermission( 4069 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4070 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4071 if (!allowMatchInstant) { 4072 flags &= ~PackageManager.MATCH_INSTANT; 4073 } 4074 } 4075 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4076 } 4077 4078 @Override 4079 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4080 if (!sUserManager.exists(userId)) return null; 4081 flags = updateFlagsForComponent(flags, userId, component); 4082 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4083 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4084 synchronized (mPackages) { 4085 PackageParser.Activity a = mActivities.mActivities.get(component); 4086 4087 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4088 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4089 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4090 if (ps == null) return null; 4091 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4092 userId); 4093 } 4094 if (mResolveComponentName.equals(component)) { 4095 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4096 new PackageUserState(), userId); 4097 } 4098 } 4099 return null; 4100 } 4101 4102 @Override 4103 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4104 String resolvedType) { 4105 synchronized (mPackages) { 4106 if (component.equals(mResolveComponentName)) { 4107 // The resolver supports EVERYTHING! 4108 return true; 4109 } 4110 PackageParser.Activity a = mActivities.mActivities.get(component); 4111 if (a == null) { 4112 return false; 4113 } 4114 for (int i=0; i<a.intents.size(); i++) { 4115 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4116 intent.getData(), intent.getCategories(), TAG) >= 0) { 4117 return true; 4118 } 4119 } 4120 return false; 4121 } 4122 } 4123 4124 @Override 4125 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4126 if (!sUserManager.exists(userId)) return null; 4127 flags = updateFlagsForComponent(flags, userId, component); 4128 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4129 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4130 synchronized (mPackages) { 4131 PackageParser.Activity a = mReceivers.mActivities.get(component); 4132 if (DEBUG_PACKAGE_INFO) Log.v( 4133 TAG, "getReceiverInfo " + component + ": " + a); 4134 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4135 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4136 if (ps == null) return null; 4137 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4138 ps.readUserState(userId), userId); 4139 if (ri != null) { 4140 rebaseEnabledOverlays(ri.applicationInfo, userId); 4141 } 4142 return ri; 4143 } 4144 } 4145 return null; 4146 } 4147 4148 @Override 4149 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4150 if (!sUserManager.exists(userId)) return null; 4151 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4152 4153 flags = updateFlagsForPackage(flags, userId, null); 4154 4155 final boolean canSeeStaticLibraries = 4156 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4157 == PERMISSION_GRANTED 4158 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4159 == PERMISSION_GRANTED 4160 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4161 == PERMISSION_GRANTED 4162 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4163 == PERMISSION_GRANTED; 4164 4165 synchronized (mPackages) { 4166 List<SharedLibraryInfo> result = null; 4167 4168 final int libCount = mSharedLibraries.size(); 4169 for (int i = 0; i < libCount; i++) { 4170 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4171 if (versionedLib == null) { 4172 continue; 4173 } 4174 4175 final int versionCount = versionedLib.size(); 4176 for (int j = 0; j < versionCount; j++) { 4177 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4178 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4179 break; 4180 } 4181 final long identity = Binder.clearCallingIdentity(); 4182 try { 4183 // TODO: We will change version code to long, so in the new API it is long 4184 PackageInfo packageInfo = getPackageInfoVersioned( 4185 libInfo.getDeclaringPackage(), flags, userId); 4186 if (packageInfo == null) { 4187 continue; 4188 } 4189 } finally { 4190 Binder.restoreCallingIdentity(identity); 4191 } 4192 4193 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4194 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4195 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4196 4197 if (result == null) { 4198 result = new ArrayList<>(); 4199 } 4200 result.add(resLibInfo); 4201 } 4202 } 4203 4204 return result != null ? new ParceledListSlice<>(result) : null; 4205 } 4206 } 4207 4208 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4209 SharedLibraryInfo libInfo, int flags, int userId) { 4210 List<VersionedPackage> versionedPackages = null; 4211 final int packageCount = mSettings.mPackages.size(); 4212 for (int i = 0; i < packageCount; i++) { 4213 PackageSetting ps = mSettings.mPackages.valueAt(i); 4214 4215 if (ps == null) { 4216 continue; 4217 } 4218 4219 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4220 continue; 4221 } 4222 4223 final String libName = libInfo.getName(); 4224 if (libInfo.isStatic()) { 4225 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4226 if (libIdx < 0) { 4227 continue; 4228 } 4229 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4230 continue; 4231 } 4232 if (versionedPackages == null) { 4233 versionedPackages = new ArrayList<>(); 4234 } 4235 // If the dependent is a static shared lib, use the public package name 4236 String dependentPackageName = ps.name; 4237 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4238 dependentPackageName = ps.pkg.manifestPackageName; 4239 } 4240 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4241 } else if (ps.pkg != null) { 4242 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4243 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4244 if (versionedPackages == null) { 4245 versionedPackages = new ArrayList<>(); 4246 } 4247 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4248 } 4249 } 4250 } 4251 4252 return versionedPackages; 4253 } 4254 4255 @Override 4256 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4257 if (!sUserManager.exists(userId)) return null; 4258 flags = updateFlagsForComponent(flags, userId, component); 4259 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4260 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4261 synchronized (mPackages) { 4262 PackageParser.Service s = mServices.mServices.get(component); 4263 if (DEBUG_PACKAGE_INFO) Log.v( 4264 TAG, "getServiceInfo " + component + ": " + s); 4265 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4266 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4267 if (ps == null) return null; 4268 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4269 ps.readUserState(userId), userId); 4270 if (si != null) { 4271 rebaseEnabledOverlays(si.applicationInfo, userId); 4272 } 4273 return si; 4274 } 4275 } 4276 return null; 4277 } 4278 4279 @Override 4280 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4281 if (!sUserManager.exists(userId)) return null; 4282 flags = updateFlagsForComponent(flags, userId, component); 4283 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4284 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4285 synchronized (mPackages) { 4286 PackageParser.Provider p = mProviders.mProviders.get(component); 4287 if (DEBUG_PACKAGE_INFO) Log.v( 4288 TAG, "getProviderInfo " + component + ": " + p); 4289 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4290 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4291 if (ps == null) return null; 4292 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4293 ps.readUserState(userId), userId); 4294 if (pi != null) { 4295 rebaseEnabledOverlays(pi.applicationInfo, userId); 4296 } 4297 return pi; 4298 } 4299 } 4300 return null; 4301 } 4302 4303 @Override 4304 public String[] getSystemSharedLibraryNames() { 4305 synchronized (mPackages) { 4306 Set<String> libs = null; 4307 final int libCount = mSharedLibraries.size(); 4308 for (int i = 0; i < libCount; i++) { 4309 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4310 if (versionedLib == null) { 4311 continue; 4312 } 4313 final int versionCount = versionedLib.size(); 4314 for (int j = 0; j < versionCount; j++) { 4315 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4316 if (!libEntry.info.isStatic()) { 4317 if (libs == null) { 4318 libs = new ArraySet<>(); 4319 } 4320 libs.add(libEntry.info.getName()); 4321 break; 4322 } 4323 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4324 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4325 UserHandle.getUserId(Binder.getCallingUid()))) { 4326 if (libs == null) { 4327 libs = new ArraySet<>(); 4328 } 4329 libs.add(libEntry.info.getName()); 4330 break; 4331 } 4332 } 4333 } 4334 4335 if (libs != null) { 4336 String[] libsArray = new String[libs.size()]; 4337 libs.toArray(libsArray); 4338 return libsArray; 4339 } 4340 4341 return null; 4342 } 4343 } 4344 4345 @Override 4346 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4347 synchronized (mPackages) { 4348 return mServicesSystemSharedLibraryPackageName; 4349 } 4350 } 4351 4352 @Override 4353 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4354 synchronized (mPackages) { 4355 return mSharedSystemSharedLibraryPackageName; 4356 } 4357 } 4358 4359 private void updateSequenceNumberLP(String packageName, int[] userList) { 4360 for (int i = userList.length - 1; i >= 0; --i) { 4361 final int userId = userList[i]; 4362 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4363 if (changedPackages == null) { 4364 changedPackages = new SparseArray<>(); 4365 mChangedPackages.put(userId, changedPackages); 4366 } 4367 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4368 if (sequenceNumbers == null) { 4369 sequenceNumbers = new HashMap<>(); 4370 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4371 } 4372 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4373 if (sequenceNumber != null) { 4374 changedPackages.remove(sequenceNumber); 4375 } 4376 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4377 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4378 } 4379 mChangedPackagesSequenceNumber++; 4380 } 4381 4382 @Override 4383 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4384 synchronized (mPackages) { 4385 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4386 return null; 4387 } 4388 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4389 if (changedPackages == null) { 4390 return null; 4391 } 4392 final List<String> packageNames = 4393 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4394 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4395 final String packageName = changedPackages.get(i); 4396 if (packageName != null) { 4397 packageNames.add(packageName); 4398 } 4399 } 4400 return packageNames.isEmpty() 4401 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4402 } 4403 } 4404 4405 @Override 4406 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4407 ArrayList<FeatureInfo> res; 4408 synchronized (mAvailableFeatures) { 4409 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4410 res.addAll(mAvailableFeatures.values()); 4411 } 4412 final FeatureInfo fi = new FeatureInfo(); 4413 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4414 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4415 res.add(fi); 4416 4417 return new ParceledListSlice<>(res); 4418 } 4419 4420 @Override 4421 public boolean hasSystemFeature(String name, int version) { 4422 synchronized (mAvailableFeatures) { 4423 final FeatureInfo feat = mAvailableFeatures.get(name); 4424 if (feat == null) { 4425 return false; 4426 } else { 4427 return feat.version >= version; 4428 } 4429 } 4430 } 4431 4432 @Override 4433 public int checkPermission(String permName, String pkgName, int userId) { 4434 if (!sUserManager.exists(userId)) { 4435 return PackageManager.PERMISSION_DENIED; 4436 } 4437 4438 synchronized (mPackages) { 4439 final PackageParser.Package p = mPackages.get(pkgName); 4440 if (p != null && p.mExtras != null) { 4441 final PackageSetting ps = (PackageSetting) p.mExtras; 4442 final PermissionsState permissionsState = ps.getPermissionsState(); 4443 if (permissionsState.hasPermission(permName, userId)) { 4444 return PackageManager.PERMISSION_GRANTED; 4445 } 4446 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4447 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4448 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4449 return PackageManager.PERMISSION_GRANTED; 4450 } 4451 } 4452 } 4453 4454 return PackageManager.PERMISSION_DENIED; 4455 } 4456 4457 @Override 4458 public int checkUidPermission(String permName, int uid) { 4459 final int userId = UserHandle.getUserId(uid); 4460 4461 if (!sUserManager.exists(userId)) { 4462 return PackageManager.PERMISSION_DENIED; 4463 } 4464 4465 synchronized (mPackages) { 4466 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4467 if (obj != null) { 4468 final SettingBase ps = (SettingBase) obj; 4469 final PermissionsState permissionsState = ps.getPermissionsState(); 4470 if (permissionsState.hasPermission(permName, userId)) { 4471 return PackageManager.PERMISSION_GRANTED; 4472 } 4473 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4474 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4475 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4476 return PackageManager.PERMISSION_GRANTED; 4477 } 4478 } else { 4479 ArraySet<String> perms = mSystemPermissions.get(uid); 4480 if (perms != null) { 4481 if (perms.contains(permName)) { 4482 return PackageManager.PERMISSION_GRANTED; 4483 } 4484 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4485 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4486 return PackageManager.PERMISSION_GRANTED; 4487 } 4488 } 4489 } 4490 } 4491 4492 return PackageManager.PERMISSION_DENIED; 4493 } 4494 4495 @Override 4496 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4497 if (UserHandle.getCallingUserId() != userId) { 4498 mContext.enforceCallingPermission( 4499 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4500 "isPermissionRevokedByPolicy for user " + userId); 4501 } 4502 4503 if (checkPermission(permission, packageName, userId) 4504 == PackageManager.PERMISSION_GRANTED) { 4505 return false; 4506 } 4507 4508 final long identity = Binder.clearCallingIdentity(); 4509 try { 4510 final int flags = getPermissionFlags(permission, packageName, userId); 4511 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4512 } finally { 4513 Binder.restoreCallingIdentity(identity); 4514 } 4515 } 4516 4517 @Override 4518 public String getPermissionControllerPackageName() { 4519 synchronized (mPackages) { 4520 return mRequiredInstallerPackage; 4521 } 4522 } 4523 4524 /** 4525 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4526 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4527 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4528 * @param message the message to log on security exception 4529 */ 4530 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4531 boolean checkShell, String message) { 4532 if (userId < 0) { 4533 throw new IllegalArgumentException("Invalid userId " + userId); 4534 } 4535 if (checkShell) { 4536 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4537 } 4538 if (userId == UserHandle.getUserId(callingUid)) return; 4539 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4540 if (requireFullPermission) { 4541 mContext.enforceCallingOrSelfPermission( 4542 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4543 } else { 4544 try { 4545 mContext.enforceCallingOrSelfPermission( 4546 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4547 } catch (SecurityException se) { 4548 mContext.enforceCallingOrSelfPermission( 4549 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4550 } 4551 } 4552 } 4553 } 4554 4555 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4556 if (callingUid == Process.SHELL_UID) { 4557 if (userHandle >= 0 4558 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4559 throw new SecurityException("Shell does not have permission to access user " 4560 + userHandle); 4561 } else if (userHandle < 0) { 4562 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4563 + Debug.getCallers(3)); 4564 } 4565 } 4566 } 4567 4568 private BasePermission findPermissionTreeLP(String permName) { 4569 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4570 if (permName.startsWith(bp.name) && 4571 permName.length() > bp.name.length() && 4572 permName.charAt(bp.name.length()) == '.') { 4573 return bp; 4574 } 4575 } 4576 return null; 4577 } 4578 4579 private BasePermission checkPermissionTreeLP(String permName) { 4580 if (permName != null) { 4581 BasePermission bp = findPermissionTreeLP(permName); 4582 if (bp != null) { 4583 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4584 return bp; 4585 } 4586 throw new SecurityException("Calling uid " 4587 + Binder.getCallingUid() 4588 + " is not allowed to add to permission tree " 4589 + bp.name + " owned by uid " + bp.uid); 4590 } 4591 } 4592 throw new SecurityException("No permission tree found for " + permName); 4593 } 4594 4595 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4596 if (s1 == null) { 4597 return s2 == null; 4598 } 4599 if (s2 == null) { 4600 return false; 4601 } 4602 if (s1.getClass() != s2.getClass()) { 4603 return false; 4604 } 4605 return s1.equals(s2); 4606 } 4607 4608 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4609 if (pi1.icon != pi2.icon) return false; 4610 if (pi1.logo != pi2.logo) return false; 4611 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4612 if (!compareStrings(pi1.name, pi2.name)) return false; 4613 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4614 // We'll take care of setting this one. 4615 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4616 // These are not currently stored in settings. 4617 //if (!compareStrings(pi1.group, pi2.group)) return false; 4618 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4619 //if (pi1.labelRes != pi2.labelRes) return false; 4620 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4621 return true; 4622 } 4623 4624 int permissionInfoFootprint(PermissionInfo info) { 4625 int size = info.name.length(); 4626 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4627 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4628 return size; 4629 } 4630 4631 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4632 int size = 0; 4633 for (BasePermission perm : mSettings.mPermissions.values()) { 4634 if (perm.uid == tree.uid) { 4635 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4636 } 4637 } 4638 return size; 4639 } 4640 4641 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4642 // We calculate the max size of permissions defined by this uid and throw 4643 // if that plus the size of 'info' would exceed our stated maximum. 4644 if (tree.uid != Process.SYSTEM_UID) { 4645 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4646 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4647 throw new SecurityException("Permission tree size cap exceeded"); 4648 } 4649 } 4650 } 4651 4652 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4653 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4654 throw new SecurityException("Label must be specified in permission"); 4655 } 4656 BasePermission tree = checkPermissionTreeLP(info.name); 4657 BasePermission bp = mSettings.mPermissions.get(info.name); 4658 boolean added = bp == null; 4659 boolean changed = true; 4660 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4661 if (added) { 4662 enforcePermissionCapLocked(info, tree); 4663 bp = new BasePermission(info.name, tree.sourcePackage, 4664 BasePermission.TYPE_DYNAMIC); 4665 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4666 throw new SecurityException( 4667 "Not allowed to modify non-dynamic permission " 4668 + info.name); 4669 } else { 4670 if (bp.protectionLevel == fixedLevel 4671 && bp.perm.owner.equals(tree.perm.owner) 4672 && bp.uid == tree.uid 4673 && comparePermissionInfos(bp.perm.info, info)) { 4674 changed = false; 4675 } 4676 } 4677 bp.protectionLevel = fixedLevel; 4678 info = new PermissionInfo(info); 4679 info.protectionLevel = fixedLevel; 4680 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4681 bp.perm.info.packageName = tree.perm.info.packageName; 4682 bp.uid = tree.uid; 4683 if (added) { 4684 mSettings.mPermissions.put(info.name, bp); 4685 } 4686 if (changed) { 4687 if (!async) { 4688 mSettings.writeLPr(); 4689 } else { 4690 scheduleWriteSettingsLocked(); 4691 } 4692 } 4693 return added; 4694 } 4695 4696 @Override 4697 public boolean addPermission(PermissionInfo info) { 4698 synchronized (mPackages) { 4699 return addPermissionLocked(info, false); 4700 } 4701 } 4702 4703 @Override 4704 public boolean addPermissionAsync(PermissionInfo info) { 4705 synchronized (mPackages) { 4706 return addPermissionLocked(info, true); 4707 } 4708 } 4709 4710 @Override 4711 public void removePermission(String name) { 4712 synchronized (mPackages) { 4713 checkPermissionTreeLP(name); 4714 BasePermission bp = mSettings.mPermissions.get(name); 4715 if (bp != null) { 4716 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4717 throw new SecurityException( 4718 "Not allowed to modify non-dynamic permission " 4719 + name); 4720 } 4721 mSettings.mPermissions.remove(name); 4722 mSettings.writeLPr(); 4723 } 4724 } 4725 } 4726 4727 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4728 BasePermission bp) { 4729 int index = pkg.requestedPermissions.indexOf(bp.name); 4730 if (index == -1) { 4731 throw new SecurityException("Package " + pkg.packageName 4732 + " has not requested permission " + bp.name); 4733 } 4734 if (!bp.isRuntime() && !bp.isDevelopment()) { 4735 throw new SecurityException("Permission " + bp.name 4736 + " is not a changeable permission type"); 4737 } 4738 } 4739 4740 @Override 4741 public void grantRuntimePermission(String packageName, String name, final int userId) { 4742 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4743 } 4744 4745 private void grantRuntimePermission(String packageName, String name, final int userId, 4746 boolean overridePolicy) { 4747 if (!sUserManager.exists(userId)) { 4748 Log.e(TAG, "No such user:" + userId); 4749 return; 4750 } 4751 4752 mContext.enforceCallingOrSelfPermission( 4753 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4754 "grantRuntimePermission"); 4755 4756 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4757 true /* requireFullPermission */, true /* checkShell */, 4758 "grantRuntimePermission"); 4759 4760 final int uid; 4761 final SettingBase sb; 4762 4763 synchronized (mPackages) { 4764 final PackageParser.Package pkg = mPackages.get(packageName); 4765 if (pkg == null) { 4766 throw new IllegalArgumentException("Unknown package: " + packageName); 4767 } 4768 4769 final BasePermission bp = mSettings.mPermissions.get(name); 4770 if (bp == null) { 4771 throw new IllegalArgumentException("Unknown permission: " + name); 4772 } 4773 4774 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4775 4776 // If a permission review is required for legacy apps we represent 4777 // their permissions as always granted runtime ones since we need 4778 // to keep the review required permission flag per user while an 4779 // install permission's state is shared across all users. 4780 if (mPermissionReviewRequired 4781 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4782 && bp.isRuntime()) { 4783 return; 4784 } 4785 4786 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4787 sb = (SettingBase) pkg.mExtras; 4788 if (sb == null) { 4789 throw new IllegalArgumentException("Unknown package: " + packageName); 4790 } 4791 4792 final PermissionsState permissionsState = sb.getPermissionsState(); 4793 4794 final int flags = permissionsState.getPermissionFlags(name, userId); 4795 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4796 throw new SecurityException("Cannot grant system fixed permission " 4797 + name + " for package " + packageName); 4798 } 4799 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4800 throw new SecurityException("Cannot grant policy fixed permission " 4801 + name + " for package " + packageName); 4802 } 4803 4804 if (bp.isDevelopment()) { 4805 // Development permissions must be handled specially, since they are not 4806 // normal runtime permissions. For now they apply to all users. 4807 if (permissionsState.grantInstallPermission(bp) != 4808 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4809 scheduleWriteSettingsLocked(); 4810 } 4811 return; 4812 } 4813 4814 final PackageSetting ps = mSettings.mPackages.get(packageName); 4815 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4816 throw new SecurityException("Cannot grant non-ephemeral permission" 4817 + name + " for package " + packageName); 4818 } 4819 4820 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4821 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4822 return; 4823 } 4824 4825 final int result = permissionsState.grantRuntimePermission(bp, userId); 4826 switch (result) { 4827 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4828 return; 4829 } 4830 4831 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4832 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4833 mHandler.post(new Runnable() { 4834 @Override 4835 public void run() { 4836 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4837 } 4838 }); 4839 } 4840 break; 4841 } 4842 4843 if (bp.isRuntime()) { 4844 logPermissionGranted(mContext, name, packageName); 4845 } 4846 4847 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4848 4849 // Not critical if that is lost - app has to request again. 4850 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4851 } 4852 4853 // Only need to do this if user is initialized. Otherwise it's a new user 4854 // and there are no processes running as the user yet and there's no need 4855 // to make an expensive call to remount processes for the changed permissions. 4856 if (READ_EXTERNAL_STORAGE.equals(name) 4857 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4858 final long token = Binder.clearCallingIdentity(); 4859 try { 4860 if (sUserManager.isInitialized(userId)) { 4861 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4862 StorageManagerInternal.class); 4863 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4864 } 4865 } finally { 4866 Binder.restoreCallingIdentity(token); 4867 } 4868 } 4869 } 4870 4871 @Override 4872 public void revokeRuntimePermission(String packageName, String name, int userId) { 4873 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4874 } 4875 4876 private void revokeRuntimePermission(String packageName, String name, int userId, 4877 boolean overridePolicy) { 4878 if (!sUserManager.exists(userId)) { 4879 Log.e(TAG, "No such user:" + userId); 4880 return; 4881 } 4882 4883 mContext.enforceCallingOrSelfPermission( 4884 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4885 "revokeRuntimePermission"); 4886 4887 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4888 true /* requireFullPermission */, true /* checkShell */, 4889 "revokeRuntimePermission"); 4890 4891 final int appId; 4892 4893 synchronized (mPackages) { 4894 final PackageParser.Package pkg = mPackages.get(packageName); 4895 if (pkg == null) { 4896 throw new IllegalArgumentException("Unknown package: " + packageName); 4897 } 4898 4899 final BasePermission bp = mSettings.mPermissions.get(name); 4900 if (bp == null) { 4901 throw new IllegalArgumentException("Unknown permission: " + name); 4902 } 4903 4904 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4905 4906 // If a permission review is required for legacy apps we represent 4907 // their permissions as always granted runtime ones since we need 4908 // to keep the review required permission flag per user while an 4909 // install permission's state is shared across all users. 4910 if (mPermissionReviewRequired 4911 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4912 && bp.isRuntime()) { 4913 return; 4914 } 4915 4916 SettingBase sb = (SettingBase) pkg.mExtras; 4917 if (sb == null) { 4918 throw new IllegalArgumentException("Unknown package: " + packageName); 4919 } 4920 4921 final PermissionsState permissionsState = sb.getPermissionsState(); 4922 4923 final int flags = permissionsState.getPermissionFlags(name, userId); 4924 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4925 throw new SecurityException("Cannot revoke system fixed permission " 4926 + name + " for package " + packageName); 4927 } 4928 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4929 throw new SecurityException("Cannot revoke policy fixed permission " 4930 + name + " for package " + packageName); 4931 } 4932 4933 if (bp.isDevelopment()) { 4934 // Development permissions must be handled specially, since they are not 4935 // normal runtime permissions. For now they apply to all users. 4936 if (permissionsState.revokeInstallPermission(bp) != 4937 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4938 scheduleWriteSettingsLocked(); 4939 } 4940 return; 4941 } 4942 4943 if (permissionsState.revokeRuntimePermission(bp, userId) == 4944 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4945 return; 4946 } 4947 4948 if (bp.isRuntime()) { 4949 logPermissionRevoked(mContext, name, packageName); 4950 } 4951 4952 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4953 4954 // Critical, after this call app should never have the permission. 4955 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4956 4957 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4958 } 4959 4960 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4961 } 4962 4963 /** 4964 * Get the first event id for the permission. 4965 * 4966 * <p>There are four events for each permission: <ul> 4967 * <li>Request permission: first id + 0</li> 4968 * <li>Grant permission: first id + 1</li> 4969 * <li>Request for permission denied: first id + 2</li> 4970 * <li>Revoke permission: first id + 3</li> 4971 * </ul></p> 4972 * 4973 * @param name name of the permission 4974 * 4975 * @return The first event id for the permission 4976 */ 4977 private static int getBaseEventId(@NonNull String name) { 4978 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4979 4980 if (eventIdIndex == -1) { 4981 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4982 || "user".equals(Build.TYPE)) { 4983 Log.i(TAG, "Unknown permission " + name); 4984 4985 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4986 } else { 4987 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4988 // 4989 // Also update 4990 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4991 // - metrics_constants.proto 4992 throw new IllegalStateException("Unknown permission " + name); 4993 } 4994 } 4995 4996 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4997 } 4998 4999 /** 5000 * Log that a permission was revoked. 5001 * 5002 * @param context Context of the caller 5003 * @param name name of the permission 5004 * @param packageName package permission if for 5005 */ 5006 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5007 @NonNull String packageName) { 5008 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5009 } 5010 5011 /** 5012 * Log that a permission request was granted. 5013 * 5014 * @param context Context of the caller 5015 * @param name name of the permission 5016 * @param packageName package permission if for 5017 */ 5018 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5019 @NonNull String packageName) { 5020 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5021 } 5022 5023 @Override 5024 public void resetRuntimePermissions() { 5025 mContext.enforceCallingOrSelfPermission( 5026 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5027 "revokeRuntimePermission"); 5028 5029 int callingUid = Binder.getCallingUid(); 5030 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5031 mContext.enforceCallingOrSelfPermission( 5032 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5033 "resetRuntimePermissions"); 5034 } 5035 5036 synchronized (mPackages) { 5037 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5038 for (int userId : UserManagerService.getInstance().getUserIds()) { 5039 final int packageCount = mPackages.size(); 5040 for (int i = 0; i < packageCount; i++) { 5041 PackageParser.Package pkg = mPackages.valueAt(i); 5042 if (!(pkg.mExtras instanceof PackageSetting)) { 5043 continue; 5044 } 5045 PackageSetting ps = (PackageSetting) pkg.mExtras; 5046 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5047 } 5048 } 5049 } 5050 } 5051 5052 @Override 5053 public int getPermissionFlags(String name, String packageName, int userId) { 5054 if (!sUserManager.exists(userId)) { 5055 return 0; 5056 } 5057 5058 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5059 5060 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5061 true /* requireFullPermission */, false /* checkShell */, 5062 "getPermissionFlags"); 5063 5064 synchronized (mPackages) { 5065 final PackageParser.Package pkg = mPackages.get(packageName); 5066 if (pkg == null) { 5067 return 0; 5068 } 5069 5070 final BasePermission bp = mSettings.mPermissions.get(name); 5071 if (bp == null) { 5072 return 0; 5073 } 5074 5075 SettingBase sb = (SettingBase) pkg.mExtras; 5076 if (sb == null) { 5077 return 0; 5078 } 5079 5080 PermissionsState permissionsState = sb.getPermissionsState(); 5081 return permissionsState.getPermissionFlags(name, userId); 5082 } 5083 } 5084 5085 @Override 5086 public void updatePermissionFlags(String name, String packageName, int flagMask, 5087 int flagValues, int userId) { 5088 if (!sUserManager.exists(userId)) { 5089 return; 5090 } 5091 5092 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5093 5094 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5095 true /* requireFullPermission */, true /* checkShell */, 5096 "updatePermissionFlags"); 5097 5098 // Only the system can change these flags and nothing else. 5099 if (getCallingUid() != Process.SYSTEM_UID) { 5100 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5101 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5102 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5103 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5104 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5105 } 5106 5107 synchronized (mPackages) { 5108 final PackageParser.Package pkg = mPackages.get(packageName); 5109 if (pkg == null) { 5110 throw new IllegalArgumentException("Unknown package: " + packageName); 5111 } 5112 5113 final BasePermission bp = mSettings.mPermissions.get(name); 5114 if (bp == null) { 5115 throw new IllegalArgumentException("Unknown permission: " + name); 5116 } 5117 5118 SettingBase sb = (SettingBase) pkg.mExtras; 5119 if (sb == null) { 5120 throw new IllegalArgumentException("Unknown package: " + packageName); 5121 } 5122 5123 PermissionsState permissionsState = sb.getPermissionsState(); 5124 5125 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5126 5127 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5128 // Install and runtime permissions are stored in different places, 5129 // so figure out what permission changed and persist the change. 5130 if (permissionsState.getInstallPermissionState(name) != null) { 5131 scheduleWriteSettingsLocked(); 5132 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5133 || hadState) { 5134 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5135 } 5136 } 5137 } 5138 } 5139 5140 /** 5141 * Update the permission flags for all packages and runtime permissions of a user in order 5142 * to allow device or profile owner to remove POLICY_FIXED. 5143 */ 5144 @Override 5145 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5146 if (!sUserManager.exists(userId)) { 5147 return; 5148 } 5149 5150 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5151 5152 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5153 true /* requireFullPermission */, true /* checkShell */, 5154 "updatePermissionFlagsForAllApps"); 5155 5156 // Only the system can change system fixed flags. 5157 if (getCallingUid() != Process.SYSTEM_UID) { 5158 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5159 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5160 } 5161 5162 synchronized (mPackages) { 5163 boolean changed = false; 5164 final int packageCount = mPackages.size(); 5165 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5166 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5167 SettingBase sb = (SettingBase) pkg.mExtras; 5168 if (sb == null) { 5169 continue; 5170 } 5171 PermissionsState permissionsState = sb.getPermissionsState(); 5172 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5173 userId, flagMask, flagValues); 5174 } 5175 if (changed) { 5176 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5177 } 5178 } 5179 } 5180 5181 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5182 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5183 != PackageManager.PERMISSION_GRANTED 5184 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5185 != PackageManager.PERMISSION_GRANTED) { 5186 throw new SecurityException(message + " requires " 5187 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5188 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5189 } 5190 } 5191 5192 @Override 5193 public boolean shouldShowRequestPermissionRationale(String permissionName, 5194 String packageName, int userId) { 5195 if (UserHandle.getCallingUserId() != userId) { 5196 mContext.enforceCallingPermission( 5197 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5198 "canShowRequestPermissionRationale for user " + userId); 5199 } 5200 5201 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5202 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5203 return false; 5204 } 5205 5206 if (checkPermission(permissionName, packageName, userId) 5207 == PackageManager.PERMISSION_GRANTED) { 5208 return false; 5209 } 5210 5211 final int flags; 5212 5213 final long identity = Binder.clearCallingIdentity(); 5214 try { 5215 flags = getPermissionFlags(permissionName, 5216 packageName, userId); 5217 } finally { 5218 Binder.restoreCallingIdentity(identity); 5219 } 5220 5221 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5222 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5223 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5224 5225 if ((flags & fixedFlags) != 0) { 5226 return false; 5227 } 5228 5229 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5230 } 5231 5232 @Override 5233 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5234 mContext.enforceCallingOrSelfPermission( 5235 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5236 "addOnPermissionsChangeListener"); 5237 5238 synchronized (mPackages) { 5239 mOnPermissionChangeListeners.addListenerLocked(listener); 5240 } 5241 } 5242 5243 @Override 5244 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5245 synchronized (mPackages) { 5246 mOnPermissionChangeListeners.removeListenerLocked(listener); 5247 } 5248 } 5249 5250 @Override 5251 public boolean isProtectedBroadcast(String actionName) { 5252 synchronized (mPackages) { 5253 if (mProtectedBroadcasts.contains(actionName)) { 5254 return true; 5255 } else if (actionName != null) { 5256 // TODO: remove these terrible hacks 5257 if (actionName.startsWith("android.net.netmon.lingerExpired") 5258 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5259 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5260 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5261 return true; 5262 } 5263 } 5264 } 5265 return false; 5266 } 5267 5268 @Override 5269 public int checkSignatures(String pkg1, String pkg2) { 5270 synchronized (mPackages) { 5271 final PackageParser.Package p1 = mPackages.get(pkg1); 5272 final PackageParser.Package p2 = mPackages.get(pkg2); 5273 if (p1 == null || p1.mExtras == null 5274 || p2 == null || p2.mExtras == null) { 5275 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5276 } 5277 return compareSignatures(p1.mSignatures, p2.mSignatures); 5278 } 5279 } 5280 5281 @Override 5282 public int checkUidSignatures(int uid1, int uid2) { 5283 // Map to base uids. 5284 uid1 = UserHandle.getAppId(uid1); 5285 uid2 = UserHandle.getAppId(uid2); 5286 // reader 5287 synchronized (mPackages) { 5288 Signature[] s1; 5289 Signature[] s2; 5290 Object obj = mSettings.getUserIdLPr(uid1); 5291 if (obj != null) { 5292 if (obj instanceof SharedUserSetting) { 5293 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5294 } else if (obj instanceof PackageSetting) { 5295 s1 = ((PackageSetting)obj).signatures.mSignatures; 5296 } else { 5297 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5298 } 5299 } else { 5300 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5301 } 5302 obj = mSettings.getUserIdLPr(uid2); 5303 if (obj != null) { 5304 if (obj instanceof SharedUserSetting) { 5305 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5306 } else if (obj instanceof PackageSetting) { 5307 s2 = ((PackageSetting)obj).signatures.mSignatures; 5308 } else { 5309 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5310 } 5311 } else { 5312 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5313 } 5314 return compareSignatures(s1, s2); 5315 } 5316 } 5317 5318 /** 5319 * This method should typically only be used when granting or revoking 5320 * permissions, since the app may immediately restart after this call. 5321 * <p> 5322 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5323 * guard your work against the app being relaunched. 5324 */ 5325 private void killUid(int appId, int userId, String reason) { 5326 final long identity = Binder.clearCallingIdentity(); 5327 try { 5328 IActivityManager am = ActivityManager.getService(); 5329 if (am != null) { 5330 try { 5331 am.killUid(appId, userId, reason); 5332 } catch (RemoteException e) { 5333 /* ignore - same process */ 5334 } 5335 } 5336 } finally { 5337 Binder.restoreCallingIdentity(identity); 5338 } 5339 } 5340 5341 /** 5342 * Compares two sets of signatures. Returns: 5343 * <br /> 5344 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5345 * <br /> 5346 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5347 * <br /> 5348 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5349 * <br /> 5350 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5351 * <br /> 5352 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5353 */ 5354 static int compareSignatures(Signature[] s1, Signature[] s2) { 5355 if (s1 == null) { 5356 return s2 == null 5357 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5358 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5359 } 5360 5361 if (s2 == null) { 5362 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5363 } 5364 5365 if (s1.length != s2.length) { 5366 return PackageManager.SIGNATURE_NO_MATCH; 5367 } 5368 5369 // Since both signature sets are of size 1, we can compare without HashSets. 5370 if (s1.length == 1) { 5371 return s1[0].equals(s2[0]) ? 5372 PackageManager.SIGNATURE_MATCH : 5373 PackageManager.SIGNATURE_NO_MATCH; 5374 } 5375 5376 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5377 for (Signature sig : s1) { 5378 set1.add(sig); 5379 } 5380 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5381 for (Signature sig : s2) { 5382 set2.add(sig); 5383 } 5384 // Make sure s2 contains all signatures in s1. 5385 if (set1.equals(set2)) { 5386 return PackageManager.SIGNATURE_MATCH; 5387 } 5388 return PackageManager.SIGNATURE_NO_MATCH; 5389 } 5390 5391 /** 5392 * If the database version for this type of package (internal storage or 5393 * external storage) is less than the version where package signatures 5394 * were updated, return true. 5395 */ 5396 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5397 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5398 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5399 } 5400 5401 /** 5402 * Used for backward compatibility to make sure any packages with 5403 * certificate chains get upgraded to the new style. {@code existingSigs} 5404 * will be in the old format (since they were stored on disk from before the 5405 * system upgrade) and {@code scannedSigs} will be in the newer format. 5406 */ 5407 private int compareSignaturesCompat(PackageSignatures existingSigs, 5408 PackageParser.Package scannedPkg) { 5409 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5410 return PackageManager.SIGNATURE_NO_MATCH; 5411 } 5412 5413 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5414 for (Signature sig : existingSigs.mSignatures) { 5415 existingSet.add(sig); 5416 } 5417 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5418 for (Signature sig : scannedPkg.mSignatures) { 5419 try { 5420 Signature[] chainSignatures = sig.getChainSignatures(); 5421 for (Signature chainSig : chainSignatures) { 5422 scannedCompatSet.add(chainSig); 5423 } 5424 } catch (CertificateEncodingException e) { 5425 scannedCompatSet.add(sig); 5426 } 5427 } 5428 /* 5429 * Make sure the expanded scanned set contains all signatures in the 5430 * existing one. 5431 */ 5432 if (scannedCompatSet.equals(existingSet)) { 5433 // Migrate the old signatures to the new scheme. 5434 existingSigs.assignSignatures(scannedPkg.mSignatures); 5435 // The new KeySets will be re-added later in the scanning process. 5436 synchronized (mPackages) { 5437 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5438 } 5439 return PackageManager.SIGNATURE_MATCH; 5440 } 5441 return PackageManager.SIGNATURE_NO_MATCH; 5442 } 5443 5444 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5445 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5446 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5447 } 5448 5449 private int compareSignaturesRecover(PackageSignatures existingSigs, 5450 PackageParser.Package scannedPkg) { 5451 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5452 return PackageManager.SIGNATURE_NO_MATCH; 5453 } 5454 5455 String msg = null; 5456 try { 5457 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5458 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5459 + scannedPkg.packageName); 5460 return PackageManager.SIGNATURE_MATCH; 5461 } 5462 } catch (CertificateException e) { 5463 msg = e.getMessage(); 5464 } 5465 5466 logCriticalInfo(Log.INFO, 5467 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5468 return PackageManager.SIGNATURE_NO_MATCH; 5469 } 5470 5471 @Override 5472 public List<String> getAllPackages() { 5473 synchronized (mPackages) { 5474 return new ArrayList<String>(mPackages.keySet()); 5475 } 5476 } 5477 5478 @Override 5479 public String[] getPackagesForUid(int uid) { 5480 final int userId = UserHandle.getUserId(uid); 5481 uid = UserHandle.getAppId(uid); 5482 // reader 5483 synchronized (mPackages) { 5484 Object obj = mSettings.getUserIdLPr(uid); 5485 if (obj instanceof SharedUserSetting) { 5486 final SharedUserSetting sus = (SharedUserSetting) obj; 5487 final int N = sus.packages.size(); 5488 String[] res = new String[N]; 5489 final Iterator<PackageSetting> it = sus.packages.iterator(); 5490 int i = 0; 5491 while (it.hasNext()) { 5492 PackageSetting ps = it.next(); 5493 if (ps.getInstalled(userId)) { 5494 res[i++] = ps.name; 5495 } else { 5496 res = ArrayUtils.removeElement(String.class, res, res[i]); 5497 } 5498 } 5499 return res; 5500 } else if (obj instanceof PackageSetting) { 5501 final PackageSetting ps = (PackageSetting) obj; 5502 if (ps.getInstalled(userId)) { 5503 return new String[]{ps.name}; 5504 } 5505 } 5506 } 5507 return null; 5508 } 5509 5510 @Override 5511 public String getNameForUid(int uid) { 5512 // reader 5513 synchronized (mPackages) { 5514 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5515 if (obj instanceof SharedUserSetting) { 5516 final SharedUserSetting sus = (SharedUserSetting) obj; 5517 return sus.name + ":" + sus.userId; 5518 } else if (obj instanceof PackageSetting) { 5519 final PackageSetting ps = (PackageSetting) obj; 5520 return ps.name; 5521 } 5522 } 5523 return null; 5524 } 5525 5526 @Override 5527 public int getUidForSharedUser(String sharedUserName) { 5528 if(sharedUserName == null) { 5529 return -1; 5530 } 5531 // reader 5532 synchronized (mPackages) { 5533 SharedUserSetting suid; 5534 try { 5535 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5536 if (suid != null) { 5537 return suid.userId; 5538 } 5539 } catch (PackageManagerException ignore) { 5540 // can't happen, but, still need to catch it 5541 } 5542 return -1; 5543 } 5544 } 5545 5546 @Override 5547 public int getFlagsForUid(int uid) { 5548 synchronized (mPackages) { 5549 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5550 if (obj instanceof SharedUserSetting) { 5551 final SharedUserSetting sus = (SharedUserSetting) obj; 5552 return sus.pkgFlags; 5553 } else if (obj instanceof PackageSetting) { 5554 final PackageSetting ps = (PackageSetting) obj; 5555 return ps.pkgFlags; 5556 } 5557 } 5558 return 0; 5559 } 5560 5561 @Override 5562 public int getPrivateFlagsForUid(int uid) { 5563 synchronized (mPackages) { 5564 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5565 if (obj instanceof SharedUserSetting) { 5566 final SharedUserSetting sus = (SharedUserSetting) obj; 5567 return sus.pkgPrivateFlags; 5568 } else if (obj instanceof PackageSetting) { 5569 final PackageSetting ps = (PackageSetting) obj; 5570 return ps.pkgPrivateFlags; 5571 } 5572 } 5573 return 0; 5574 } 5575 5576 @Override 5577 public boolean isUidPrivileged(int uid) { 5578 uid = UserHandle.getAppId(uid); 5579 // reader 5580 synchronized (mPackages) { 5581 Object obj = mSettings.getUserIdLPr(uid); 5582 if (obj instanceof SharedUserSetting) { 5583 final SharedUserSetting sus = (SharedUserSetting) obj; 5584 final Iterator<PackageSetting> it = sus.packages.iterator(); 5585 while (it.hasNext()) { 5586 if (it.next().isPrivileged()) { 5587 return true; 5588 } 5589 } 5590 } else if (obj instanceof PackageSetting) { 5591 final PackageSetting ps = (PackageSetting) obj; 5592 return ps.isPrivileged(); 5593 } 5594 } 5595 return false; 5596 } 5597 5598 @Override 5599 public String[] getAppOpPermissionPackages(String permissionName) { 5600 synchronized (mPackages) { 5601 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5602 if (pkgs == null) { 5603 return null; 5604 } 5605 return pkgs.toArray(new String[pkgs.size()]); 5606 } 5607 } 5608 5609 @Override 5610 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5611 int flags, int userId) { 5612 return resolveIntentInternal( 5613 intent, resolvedType, flags, userId, false /*includeInstantApp*/); 5614 } 5615 5616 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5617 int flags, int userId, boolean includeInstantApp) { 5618 try { 5619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5620 5621 if (!sUserManager.exists(userId)) return null; 5622 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 5623 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5624 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5625 5626 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5627 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5628 flags, userId, includeInstantApp); 5629 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5630 5631 final ResolveInfo bestChoice = 5632 chooseBestActivity(intent, resolvedType, flags, query, userId); 5633 return bestChoice; 5634 } finally { 5635 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5636 } 5637 } 5638 5639 @Override 5640 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5641 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5642 throw new SecurityException( 5643 "findPersistentPreferredActivity can only be run by the system"); 5644 } 5645 if (!sUserManager.exists(userId)) { 5646 return null; 5647 } 5648 intent = updateIntentForResolve(intent); 5649 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5650 final int flags = updateFlagsForResolve(0, userId, intent, false); 5651 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5652 userId); 5653 synchronized (mPackages) { 5654 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5655 userId); 5656 } 5657 } 5658 5659 @Override 5660 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5661 IntentFilter filter, int match, ComponentName activity) { 5662 final int userId = UserHandle.getCallingUserId(); 5663 if (DEBUG_PREFERRED) { 5664 Log.v(TAG, "setLastChosenActivity intent=" + intent 5665 + " resolvedType=" + resolvedType 5666 + " flags=" + flags 5667 + " filter=" + filter 5668 + " match=" + match 5669 + " activity=" + activity); 5670 filter.dump(new PrintStreamPrinter(System.out), " "); 5671 } 5672 intent.setComponent(null); 5673 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5674 userId); 5675 // Find any earlier preferred or last chosen entries and nuke them 5676 findPreferredActivity(intent, resolvedType, 5677 flags, query, 0, false, true, false, userId); 5678 // Add the new activity as the last chosen for this filter 5679 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5680 "Setting last chosen"); 5681 } 5682 5683 @Override 5684 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5685 final int userId = UserHandle.getCallingUserId(); 5686 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5687 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5688 userId); 5689 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5690 false, false, false, userId); 5691 } 5692 5693 /** 5694 * Returns whether or not instant apps have been disabled remotely. 5695 * <p><em>IMPORTANT</em> This should not be called with the package manager lock 5696 * held. Otherwise we run the risk of deadlock. 5697 */ 5698 private boolean isEphemeralDisabled() { 5699 // ephemeral apps have been disabled across the board 5700 if (DISABLE_EPHEMERAL_APPS) { 5701 return true; 5702 } 5703 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5704 if (!mSystemReady) { 5705 return true; 5706 } 5707 // we can't get a content resolver until the system is ready; these checks must happen last 5708 final ContentResolver resolver = mContext.getContentResolver(); 5709 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5710 return true; 5711 } 5712 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5713 } 5714 5715 private boolean isEphemeralAllowed( 5716 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5717 boolean skipPackageCheck) { 5718 final int callingUser = UserHandle.getCallingUserId(); 5719 if (callingUser != UserHandle.USER_SYSTEM) { 5720 return false; 5721 } 5722 if (mInstantAppResolverConnection == null) { 5723 return false; 5724 } 5725 if (mInstantAppInstallerComponent == null) { 5726 return false; 5727 } 5728 if (intent.getComponent() != null) { 5729 return false; 5730 } 5731 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5732 return false; 5733 } 5734 if (!skipPackageCheck && intent.getPackage() != null) { 5735 return false; 5736 } 5737 final boolean isWebUri = hasWebURI(intent); 5738 if (!isWebUri || intent.getData().getHost() == null) { 5739 return false; 5740 } 5741 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5742 // Or if there's already an ephemeral app installed that handles the action 5743 synchronized (mPackages) { 5744 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5745 for (int n = 0; n < count; n++) { 5746 ResolveInfo info = resolvedActivities.get(n); 5747 String packageName = info.activityInfo.packageName; 5748 PackageSetting ps = mSettings.mPackages.get(packageName); 5749 if (ps != null) { 5750 // Try to get the status from User settings first 5751 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5752 int status = (int) (packedStatus >> 32); 5753 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5754 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5755 if (DEBUG_EPHEMERAL) { 5756 Slog.v(TAG, "DENY ephemeral apps;" 5757 + " pkg: " + packageName + ", status: " + status); 5758 } 5759 return false; 5760 } 5761 if (ps.getInstantApp(userId)) { 5762 return false; 5763 } 5764 } 5765 } 5766 } 5767 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5768 return true; 5769 } 5770 5771 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5772 Intent origIntent, String resolvedType, String callingPackage, 5773 int userId) { 5774 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5775 new InstantAppRequest(responseObj, origIntent, resolvedType, 5776 callingPackage, userId)); 5777 mHandler.sendMessage(msg); 5778 } 5779 5780 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5781 int flags, List<ResolveInfo> query, int userId) { 5782 if (query != null) { 5783 final int N = query.size(); 5784 if (N == 1) { 5785 return query.get(0); 5786 } else if (N > 1) { 5787 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5788 // If there is more than one activity with the same priority, 5789 // then let the user decide between them. 5790 ResolveInfo r0 = query.get(0); 5791 ResolveInfo r1 = query.get(1); 5792 if (DEBUG_INTENT_MATCHING || debug) { 5793 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5794 + r1.activityInfo.name + "=" + r1.priority); 5795 } 5796 // If the first activity has a higher priority, or a different 5797 // default, then it is always desirable to pick it. 5798 if (r0.priority != r1.priority 5799 || r0.preferredOrder != r1.preferredOrder 5800 || r0.isDefault != r1.isDefault) { 5801 return query.get(0); 5802 } 5803 // If we have saved a preference for a preferred activity for 5804 // this Intent, use that. 5805 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5806 flags, query, r0.priority, true, false, debug, userId); 5807 if (ri != null) { 5808 return ri; 5809 } 5810 // If we have an ephemeral app, use it 5811 for (int i = 0; i < N; i++) { 5812 ri = query.get(i); 5813 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5814 return ri; 5815 } 5816 } 5817 ri = new ResolveInfo(mResolveInfo); 5818 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5819 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5820 // If all of the options come from the same package, show the application's 5821 // label and icon instead of the generic resolver's. 5822 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5823 // and then throw away the ResolveInfo itself, meaning that the caller loses 5824 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5825 // a fallback for this case; we only set the target package's resources on 5826 // the ResolveInfo, not the ActivityInfo. 5827 final String intentPackage = intent.getPackage(); 5828 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5829 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5830 ri.resolvePackageName = intentPackage; 5831 if (userNeedsBadging(userId)) { 5832 ri.noResourceId = true; 5833 } else { 5834 ri.icon = appi.icon; 5835 } 5836 ri.iconResourceId = appi.icon; 5837 ri.labelRes = appi.labelRes; 5838 } 5839 ri.activityInfo.applicationInfo = new ApplicationInfo( 5840 ri.activityInfo.applicationInfo); 5841 if (userId != 0) { 5842 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5843 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5844 } 5845 // Make sure that the resolver is displayable in car mode 5846 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5847 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5848 return ri; 5849 } 5850 } 5851 return null; 5852 } 5853 5854 /** 5855 * Return true if the given list is not empty and all of its contents have 5856 * an activityInfo with the given package name. 5857 */ 5858 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5859 if (ArrayUtils.isEmpty(list)) { 5860 return false; 5861 } 5862 for (int i = 0, N = list.size(); i < N; i++) { 5863 final ResolveInfo ri = list.get(i); 5864 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5865 if (ai == null || !packageName.equals(ai.packageName)) { 5866 return false; 5867 } 5868 } 5869 return true; 5870 } 5871 5872 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5873 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5874 final int N = query.size(); 5875 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5876 .get(userId); 5877 // Get the list of persistent preferred activities that handle the intent 5878 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5879 List<PersistentPreferredActivity> pprefs = ppir != null 5880 ? ppir.queryIntent(intent, resolvedType, 5881 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5882 userId) 5883 : null; 5884 if (pprefs != null && pprefs.size() > 0) { 5885 final int M = pprefs.size(); 5886 for (int i=0; i<M; i++) { 5887 final PersistentPreferredActivity ppa = pprefs.get(i); 5888 if (DEBUG_PREFERRED || debug) { 5889 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5890 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5891 + "\n component=" + ppa.mComponent); 5892 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5893 } 5894 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5895 flags | MATCH_DISABLED_COMPONENTS, userId); 5896 if (DEBUG_PREFERRED || debug) { 5897 Slog.v(TAG, "Found persistent preferred activity:"); 5898 if (ai != null) { 5899 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5900 } else { 5901 Slog.v(TAG, " null"); 5902 } 5903 } 5904 if (ai == null) { 5905 // This previously registered persistent preferred activity 5906 // component is no longer known. Ignore it and do NOT remove it. 5907 continue; 5908 } 5909 for (int j=0; j<N; j++) { 5910 final ResolveInfo ri = query.get(j); 5911 if (!ri.activityInfo.applicationInfo.packageName 5912 .equals(ai.applicationInfo.packageName)) { 5913 continue; 5914 } 5915 if (!ri.activityInfo.name.equals(ai.name)) { 5916 continue; 5917 } 5918 // Found a persistent preference that can handle the intent. 5919 if (DEBUG_PREFERRED || debug) { 5920 Slog.v(TAG, "Returning persistent preferred activity: " + 5921 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5922 } 5923 return ri; 5924 } 5925 } 5926 } 5927 return null; 5928 } 5929 5930 // TODO: handle preferred activities missing while user has amnesia 5931 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5932 List<ResolveInfo> query, int priority, boolean always, 5933 boolean removeMatches, boolean debug, int userId) { 5934 if (!sUserManager.exists(userId)) return null; 5935 flags = updateFlagsForResolve(flags, userId, intent, false); 5936 intent = updateIntentForResolve(intent); 5937 // writer 5938 synchronized (mPackages) { 5939 // Try to find a matching persistent preferred activity. 5940 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5941 debug, userId); 5942 5943 // If a persistent preferred activity matched, use it. 5944 if (pri != null) { 5945 return pri; 5946 } 5947 5948 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5949 // Get the list of preferred activities that handle the intent 5950 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5951 List<PreferredActivity> prefs = pir != null 5952 ? pir.queryIntent(intent, resolvedType, 5953 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5954 userId) 5955 : null; 5956 if (prefs != null && prefs.size() > 0) { 5957 boolean changed = false; 5958 try { 5959 // First figure out how good the original match set is. 5960 // We will only allow preferred activities that came 5961 // from the same match quality. 5962 int match = 0; 5963 5964 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5965 5966 final int N = query.size(); 5967 for (int j=0; j<N; j++) { 5968 final ResolveInfo ri = query.get(j); 5969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5970 + ": 0x" + Integer.toHexString(match)); 5971 if (ri.match > match) { 5972 match = ri.match; 5973 } 5974 } 5975 5976 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5977 + Integer.toHexString(match)); 5978 5979 match &= IntentFilter.MATCH_CATEGORY_MASK; 5980 final int M = prefs.size(); 5981 for (int i=0; i<M; i++) { 5982 final PreferredActivity pa = prefs.get(i); 5983 if (DEBUG_PREFERRED || debug) { 5984 Slog.v(TAG, "Checking PreferredActivity ds=" 5985 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5986 + "\n component=" + pa.mPref.mComponent); 5987 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5988 } 5989 if (pa.mPref.mMatch != match) { 5990 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5991 + Integer.toHexString(pa.mPref.mMatch)); 5992 continue; 5993 } 5994 // If it's not an "always" type preferred activity and that's what we're 5995 // looking for, skip it. 5996 if (always && !pa.mPref.mAlways) { 5997 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5998 continue; 5999 } 6000 final ActivityInfo ai = getActivityInfo( 6001 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6002 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6003 userId); 6004 if (DEBUG_PREFERRED || debug) { 6005 Slog.v(TAG, "Found preferred activity:"); 6006 if (ai != null) { 6007 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6008 } else { 6009 Slog.v(TAG, " null"); 6010 } 6011 } 6012 if (ai == null) { 6013 // This previously registered preferred activity 6014 // component is no longer known. Most likely an update 6015 // to the app was installed and in the new version this 6016 // component no longer exists. Clean it up by removing 6017 // it from the preferred activities list, and skip it. 6018 Slog.w(TAG, "Removing dangling preferred activity: " 6019 + pa.mPref.mComponent); 6020 pir.removeFilter(pa); 6021 changed = true; 6022 continue; 6023 } 6024 for (int j=0; j<N; j++) { 6025 final ResolveInfo ri = query.get(j); 6026 if (!ri.activityInfo.applicationInfo.packageName 6027 .equals(ai.applicationInfo.packageName)) { 6028 continue; 6029 } 6030 if (!ri.activityInfo.name.equals(ai.name)) { 6031 continue; 6032 } 6033 6034 if (removeMatches) { 6035 pir.removeFilter(pa); 6036 changed = true; 6037 if (DEBUG_PREFERRED) { 6038 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6039 } 6040 break; 6041 } 6042 6043 // Okay we found a previously set preferred or last chosen app. 6044 // If the result set is different from when this 6045 // was created, we need to clear it and re-ask the 6046 // user their preference, if we're looking for an "always" type entry. 6047 if (always && !pa.mPref.sameSet(query)) { 6048 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6049 + intent + " type " + resolvedType); 6050 if (DEBUG_PREFERRED) { 6051 Slog.v(TAG, "Removing preferred activity since set changed " 6052 + pa.mPref.mComponent); 6053 } 6054 pir.removeFilter(pa); 6055 // Re-add the filter as a "last chosen" entry (!always) 6056 PreferredActivity lastChosen = new PreferredActivity( 6057 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6058 pir.addFilter(lastChosen); 6059 changed = true; 6060 return null; 6061 } 6062 6063 // Yay! Either the set matched or we're looking for the last chosen 6064 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6065 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6066 return ri; 6067 } 6068 } 6069 } finally { 6070 if (changed) { 6071 if (DEBUG_PREFERRED) { 6072 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6073 } 6074 scheduleWritePackageRestrictionsLocked(userId); 6075 } 6076 } 6077 } 6078 } 6079 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6080 return null; 6081 } 6082 6083 /* 6084 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6085 */ 6086 @Override 6087 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6088 int targetUserId) { 6089 mContext.enforceCallingOrSelfPermission( 6090 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6091 List<CrossProfileIntentFilter> matches = 6092 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6093 if (matches != null) { 6094 int size = matches.size(); 6095 for (int i = 0; i < size; i++) { 6096 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6097 } 6098 } 6099 if (hasWebURI(intent)) { 6100 // cross-profile app linking works only towards the parent. 6101 final UserInfo parent = getProfileParent(sourceUserId); 6102 synchronized(mPackages) { 6103 int flags = updateFlagsForResolve(0, parent.id, intent, false); 6104 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6105 intent, resolvedType, flags, sourceUserId, parent.id); 6106 return xpDomainInfo != null; 6107 } 6108 } 6109 return false; 6110 } 6111 6112 private UserInfo getProfileParent(int userId) { 6113 final long identity = Binder.clearCallingIdentity(); 6114 try { 6115 return sUserManager.getProfileParent(userId); 6116 } finally { 6117 Binder.restoreCallingIdentity(identity); 6118 } 6119 } 6120 6121 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6122 String resolvedType, int userId) { 6123 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6124 if (resolver != null) { 6125 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6126 } 6127 return null; 6128 } 6129 6130 @Override 6131 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6132 String resolvedType, int flags, int userId) { 6133 try { 6134 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6135 6136 return new ParceledListSlice<>( 6137 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6138 } finally { 6139 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6140 } 6141 } 6142 6143 /** 6144 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6145 * instant, returns {@code null}. 6146 */ 6147 private String getInstantAppPackageName(int callingUid) { 6148 final int appId = UserHandle.getAppId(callingUid); 6149 synchronized (mPackages) { 6150 final Object obj = mSettings.getUserIdLPr(appId); 6151 if (obj instanceof PackageSetting) { 6152 final PackageSetting ps = (PackageSetting) obj; 6153 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6154 return isInstantApp ? ps.pkg.packageName : null; 6155 } 6156 } 6157 return null; 6158 } 6159 6160 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6161 String resolvedType, int flags, int userId) { 6162 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6163 } 6164 6165 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6166 String resolvedType, int flags, int userId, boolean includeInstantApp) { 6167 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6168 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 6169 flags = updateFlagsForResolve(flags, userId, intent, includeInstantApp); 6170 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6171 false /* requireFullPermission */, false /* checkShell */, 6172 "query intent activities"); 6173 ComponentName comp = intent.getComponent(); 6174 if (comp == null) { 6175 if (intent.getSelector() != null) { 6176 intent = intent.getSelector(); 6177 comp = intent.getComponent(); 6178 } 6179 } 6180 6181 if (comp != null) { 6182 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6183 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6184 if (ai != null) { 6185 // When specifying an explicit component, we prevent the activity from being 6186 // used when either 1) the calling package is normal and the activity is within 6187 // an ephemeral application or 2) the calling package is ephemeral and the 6188 // activity is not visible to ephemeral applications. 6189 final boolean matchInstantApp = 6190 (flags & PackageManager.MATCH_INSTANT) != 0; 6191 final boolean matchVisibleToInstantAppOnly = 6192 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6193 final boolean isCallerInstantApp = 6194 instantAppPkgName != null; 6195 final boolean isTargetSameInstantApp = 6196 comp.getPackageName().equals(instantAppPkgName); 6197 final boolean isTargetInstantApp = 6198 (ai.applicationInfo.privateFlags 6199 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6200 final boolean isTargetHiddenFromInstantApp = 6201 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6202 final boolean blockResolution = 6203 !isTargetSameInstantApp 6204 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6205 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6206 && isTargetHiddenFromInstantApp)); 6207 if (!blockResolution) { 6208 final ResolveInfo ri = new ResolveInfo(); 6209 ri.activityInfo = ai; 6210 list.add(ri); 6211 } 6212 } 6213 return applyPostResolutionFilter(list, instantAppPkgName); 6214 } 6215 6216 // reader 6217 boolean sortResult = false; 6218 boolean addEphemeral = false; 6219 List<ResolveInfo> result; 6220 final String pkgName = intent.getPackage(); 6221 final boolean ephemeralDisabled = isEphemeralDisabled(); 6222 synchronized (mPackages) { 6223 if (pkgName == null) { 6224 List<CrossProfileIntentFilter> matchingFilters = 6225 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6226 // Check for results that need to skip the current profile. 6227 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6228 resolvedType, flags, userId); 6229 if (xpResolveInfo != null) { 6230 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6231 xpResult.add(xpResolveInfo); 6232 return applyPostResolutionFilter( 6233 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6234 } 6235 6236 // Check for results in the current profile. 6237 result = filterIfNotSystemUser(mActivities.queryIntent( 6238 intent, resolvedType, flags, userId), userId); 6239 addEphemeral = !ephemeralDisabled 6240 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6241 6242 // Check for cross profile results. 6243 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6244 xpResolveInfo = queryCrossProfileIntents( 6245 matchingFilters, intent, resolvedType, flags, userId, 6246 hasNonNegativePriorityResult); 6247 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6248 boolean isVisibleToUser = filterIfNotSystemUser( 6249 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6250 if (isVisibleToUser) { 6251 result.add(xpResolveInfo); 6252 sortResult = true; 6253 } 6254 } 6255 if (hasWebURI(intent)) { 6256 CrossProfileDomainInfo xpDomainInfo = null; 6257 final UserInfo parent = getProfileParent(userId); 6258 if (parent != null) { 6259 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6260 flags, userId, parent.id); 6261 } 6262 if (xpDomainInfo != null) { 6263 if (xpResolveInfo != null) { 6264 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6265 // in the result. 6266 result.remove(xpResolveInfo); 6267 } 6268 if (result.size() == 0 && !addEphemeral) { 6269 // No result in current profile, but found candidate in parent user. 6270 // And we are not going to add emphemeral app, so we can return the 6271 // result straight away. 6272 result.add(xpDomainInfo.resolveInfo); 6273 return applyPostResolutionFilter(result, instantAppPkgName); 6274 } 6275 } else if (result.size() <= 1 && !addEphemeral) { 6276 // No result in parent user and <= 1 result in current profile, and we 6277 // are not going to add emphemeral app, so we can return the result without 6278 // further processing. 6279 return applyPostResolutionFilter(result, instantAppPkgName); 6280 } 6281 // We have more than one candidate (combining results from current and parent 6282 // profile), so we need filtering and sorting. 6283 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6284 intent, flags, result, xpDomainInfo, userId); 6285 sortResult = true; 6286 } 6287 } else { 6288 final PackageParser.Package pkg = mPackages.get(pkgName); 6289 if (pkg != null) { 6290 result = applyPostResolutionFilter(filterIfNotSystemUser( 6291 mActivities.queryIntentForPackage( 6292 intent, resolvedType, flags, pkg.activities, userId), 6293 userId), instantAppPkgName); 6294 } else { 6295 // the caller wants to resolve for a particular package; however, there 6296 // were no installed results, so, try to find an ephemeral result 6297 addEphemeral = !ephemeralDisabled 6298 && isEphemeralAllowed( 6299 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6300 result = new ArrayList<ResolveInfo>(); 6301 } 6302 } 6303 } 6304 if (addEphemeral) { 6305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6306 final InstantAppRequest requestObject = new InstantAppRequest( 6307 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6308 null /*callingPackage*/, userId); 6309 final AuxiliaryResolveInfo auxiliaryResponse = 6310 InstantAppResolver.doInstantAppResolutionPhaseOne( 6311 mContext, mInstantAppResolverConnection, requestObject); 6312 if (auxiliaryResponse != null) { 6313 if (DEBUG_EPHEMERAL) { 6314 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6315 } 6316 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6317 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6318 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6319 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6320 // make sure this resolver is the default 6321 ephemeralInstaller.isDefault = true; 6322 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6323 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6324 // add a non-generic filter 6325 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6326 ephemeralInstaller.filter.addDataPath( 6327 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6328 ephemeralInstaller.instantAppAvailable = true; 6329 result.add(ephemeralInstaller); 6330 } 6331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6332 } 6333 if (sortResult) { 6334 Collections.sort(result, mResolvePrioritySorter); 6335 } 6336 return applyPostResolutionFilter(result, instantAppPkgName); 6337 } 6338 6339 private static class CrossProfileDomainInfo { 6340 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6341 ResolveInfo resolveInfo; 6342 /* Best domain verification status of the activities found in the other profile */ 6343 int bestDomainVerificationStatus; 6344 } 6345 6346 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6347 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6348 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6349 sourceUserId)) { 6350 return null; 6351 } 6352 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6353 resolvedType, flags, parentUserId); 6354 6355 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6356 return null; 6357 } 6358 CrossProfileDomainInfo result = null; 6359 int size = resultTargetUser.size(); 6360 for (int i = 0; i < size; i++) { 6361 ResolveInfo riTargetUser = resultTargetUser.get(i); 6362 // Intent filter verification is only for filters that specify a host. So don't return 6363 // those that handle all web uris. 6364 if (riTargetUser.handleAllWebDataURI) { 6365 continue; 6366 } 6367 String packageName = riTargetUser.activityInfo.packageName; 6368 PackageSetting ps = mSettings.mPackages.get(packageName); 6369 if (ps == null) { 6370 continue; 6371 } 6372 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6373 int status = (int)(verificationState >> 32); 6374 if (result == null) { 6375 result = new CrossProfileDomainInfo(); 6376 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6377 sourceUserId, parentUserId); 6378 result.bestDomainVerificationStatus = status; 6379 } else { 6380 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6381 result.bestDomainVerificationStatus); 6382 } 6383 } 6384 // Don't consider matches with status NEVER across profiles. 6385 if (result != null && result.bestDomainVerificationStatus 6386 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6387 return null; 6388 } 6389 return result; 6390 } 6391 6392 /** 6393 * Verification statuses are ordered from the worse to the best, except for 6394 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6395 */ 6396 private int bestDomainVerificationStatus(int status1, int status2) { 6397 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6398 return status2; 6399 } 6400 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6401 return status1; 6402 } 6403 return (int) MathUtils.max(status1, status2); 6404 } 6405 6406 private boolean isUserEnabled(int userId) { 6407 long callingId = Binder.clearCallingIdentity(); 6408 try { 6409 UserInfo userInfo = sUserManager.getUserInfo(userId); 6410 return userInfo != null && userInfo.isEnabled(); 6411 } finally { 6412 Binder.restoreCallingIdentity(callingId); 6413 } 6414 } 6415 6416 /** 6417 * Filter out activities with systemUserOnly flag set, when current user is not System. 6418 * 6419 * @return filtered list 6420 */ 6421 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6422 if (userId == UserHandle.USER_SYSTEM) { 6423 return resolveInfos; 6424 } 6425 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6426 ResolveInfo info = resolveInfos.get(i); 6427 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6428 resolveInfos.remove(i); 6429 } 6430 } 6431 return resolveInfos; 6432 } 6433 6434 /** 6435 * Filters out ephemeral activities. 6436 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6437 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6438 * 6439 * @param resolveInfos The pre-filtered list of resolved activities 6440 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6441 * is performed. 6442 * @return A filtered list of resolved activities. 6443 */ 6444 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6445 String ephemeralPkgName) { 6446 // TODO: When adding on-demand split support for non-instant apps, remove this check 6447 // and always apply post filtering 6448 if (ephemeralPkgName == null) { 6449 return resolveInfos; 6450 } 6451 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6452 final ResolveInfo info = resolveInfos.get(i); 6453 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6454 // allow activities that are defined in the provided package 6455 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6456 if (info.activityInfo.splitName != null 6457 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6458 info.activityInfo.splitName)) { 6459 // requested activity is defined in a split that hasn't been installed yet. 6460 // add the installer to the resolve list 6461 if (DEBUG_EPHEMERAL) { 6462 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6463 } 6464 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6465 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6466 info.activityInfo.packageName, info.activityInfo.splitName, 6467 info.activityInfo.applicationInfo.versionCode); 6468 // make sure this resolver is the default 6469 installerInfo.isDefault = true; 6470 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6471 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6472 // add a non-generic filter 6473 installerInfo.filter = new IntentFilter(); 6474 // load resources from the correct package 6475 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6476 resolveInfos.set(i, installerInfo); 6477 } 6478 continue; 6479 } 6480 // allow activities that have been explicitly exposed to ephemeral apps 6481 if (!isEphemeralApp 6482 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6483 continue; 6484 } 6485 resolveInfos.remove(i); 6486 } 6487 return resolveInfos; 6488 } 6489 6490 /** 6491 * @param resolveInfos list of resolve infos in descending priority order 6492 * @return if the list contains a resolve info with non-negative priority 6493 */ 6494 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6495 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6496 } 6497 6498 private static boolean hasWebURI(Intent intent) { 6499 if (intent.getData() == null) { 6500 return false; 6501 } 6502 final String scheme = intent.getScheme(); 6503 if (TextUtils.isEmpty(scheme)) { 6504 return false; 6505 } 6506 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6507 } 6508 6509 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6510 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6511 int userId) { 6512 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6513 6514 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6515 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6516 candidates.size()); 6517 } 6518 6519 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6520 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6521 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6522 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6523 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6524 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6525 6526 synchronized (mPackages) { 6527 final int count = candidates.size(); 6528 // First, try to use linked apps. Partition the candidates into four lists: 6529 // one for the final results, one for the "do not use ever", one for "undefined status" 6530 // and finally one for "browser app type". 6531 for (int n=0; n<count; n++) { 6532 ResolveInfo info = candidates.get(n); 6533 String packageName = info.activityInfo.packageName; 6534 PackageSetting ps = mSettings.mPackages.get(packageName); 6535 if (ps != null) { 6536 // Add to the special match all list (Browser use case) 6537 if (info.handleAllWebDataURI) { 6538 matchAllList.add(info); 6539 continue; 6540 } 6541 // Try to get the status from User settings first 6542 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6543 int status = (int)(packedStatus >> 32); 6544 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6545 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6546 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6547 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6548 + " : linkgen=" + linkGeneration); 6549 } 6550 // Use link-enabled generation as preferredOrder, i.e. 6551 // prefer newly-enabled over earlier-enabled. 6552 info.preferredOrder = linkGeneration; 6553 alwaysList.add(info); 6554 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6555 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6556 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6557 } 6558 neverList.add(info); 6559 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6560 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6561 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6562 } 6563 alwaysAskList.add(info); 6564 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6565 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6566 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6567 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6568 } 6569 undefinedList.add(info); 6570 } 6571 } 6572 } 6573 6574 // We'll want to include browser possibilities in a few cases 6575 boolean includeBrowser = false; 6576 6577 // First try to add the "always" resolution(s) for the current user, if any 6578 if (alwaysList.size() > 0) { 6579 result.addAll(alwaysList); 6580 } else { 6581 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6582 result.addAll(undefinedList); 6583 // Maybe add one for the other profile. 6584 if (xpDomainInfo != null && ( 6585 xpDomainInfo.bestDomainVerificationStatus 6586 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6587 result.add(xpDomainInfo.resolveInfo); 6588 } 6589 includeBrowser = true; 6590 } 6591 6592 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6593 // If there were 'always' entries their preferred order has been set, so we also 6594 // back that off to make the alternatives equivalent 6595 if (alwaysAskList.size() > 0) { 6596 for (ResolveInfo i : result) { 6597 i.preferredOrder = 0; 6598 } 6599 result.addAll(alwaysAskList); 6600 includeBrowser = true; 6601 } 6602 6603 if (includeBrowser) { 6604 // Also add browsers (all of them or only the default one) 6605 if (DEBUG_DOMAIN_VERIFICATION) { 6606 Slog.v(TAG, " ...including browsers in candidate set"); 6607 } 6608 if ((matchFlags & MATCH_ALL) != 0) { 6609 result.addAll(matchAllList); 6610 } else { 6611 // Browser/generic handling case. If there's a default browser, go straight 6612 // to that (but only if there is no other higher-priority match). 6613 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6614 int maxMatchPrio = 0; 6615 ResolveInfo defaultBrowserMatch = null; 6616 final int numCandidates = matchAllList.size(); 6617 for (int n = 0; n < numCandidates; n++) { 6618 ResolveInfo info = matchAllList.get(n); 6619 // track the highest overall match priority... 6620 if (info.priority > maxMatchPrio) { 6621 maxMatchPrio = info.priority; 6622 } 6623 // ...and the highest-priority default browser match 6624 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6625 if (defaultBrowserMatch == null 6626 || (defaultBrowserMatch.priority < info.priority)) { 6627 if (debug) { 6628 Slog.v(TAG, "Considering default browser match " + info); 6629 } 6630 defaultBrowserMatch = info; 6631 } 6632 } 6633 } 6634 if (defaultBrowserMatch != null 6635 && defaultBrowserMatch.priority >= maxMatchPrio 6636 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6637 { 6638 if (debug) { 6639 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6640 } 6641 result.add(defaultBrowserMatch); 6642 } else { 6643 result.addAll(matchAllList); 6644 } 6645 } 6646 6647 // If there is nothing selected, add all candidates and remove the ones that the user 6648 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6649 if (result.size() == 0) { 6650 result.addAll(candidates); 6651 result.removeAll(neverList); 6652 } 6653 } 6654 } 6655 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6656 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6657 result.size()); 6658 for (ResolveInfo info : result) { 6659 Slog.v(TAG, " + " + info.activityInfo); 6660 } 6661 } 6662 return result; 6663 } 6664 6665 // Returns a packed value as a long: 6666 // 6667 // high 'int'-sized word: link status: undefined/ask/never/always. 6668 // low 'int'-sized word: relative priority among 'always' results. 6669 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6670 long result = ps.getDomainVerificationStatusForUser(userId); 6671 // if none available, get the master status 6672 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6673 if (ps.getIntentFilterVerificationInfo() != null) { 6674 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6675 } 6676 } 6677 return result; 6678 } 6679 6680 private ResolveInfo querySkipCurrentProfileIntents( 6681 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6682 int flags, int sourceUserId) { 6683 if (matchingFilters != null) { 6684 int size = matchingFilters.size(); 6685 for (int i = 0; i < size; i ++) { 6686 CrossProfileIntentFilter filter = matchingFilters.get(i); 6687 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6688 // Checking if there are activities in the target user that can handle the 6689 // intent. 6690 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6691 resolvedType, flags, sourceUserId); 6692 if (resolveInfo != null) { 6693 return resolveInfo; 6694 } 6695 } 6696 } 6697 } 6698 return null; 6699 } 6700 6701 // Return matching ResolveInfo in target user if any. 6702 private ResolveInfo queryCrossProfileIntents( 6703 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6704 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6705 if (matchingFilters != null) { 6706 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6707 // match the same intent. For performance reasons, it is better not to 6708 // run queryIntent twice for the same userId 6709 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6710 int size = matchingFilters.size(); 6711 for (int i = 0; i < size; i++) { 6712 CrossProfileIntentFilter filter = matchingFilters.get(i); 6713 int targetUserId = filter.getTargetUserId(); 6714 boolean skipCurrentProfile = 6715 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6716 boolean skipCurrentProfileIfNoMatchFound = 6717 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6718 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6719 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6720 // Checking if there are activities in the target user that can handle the 6721 // intent. 6722 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6723 resolvedType, flags, sourceUserId); 6724 if (resolveInfo != null) return resolveInfo; 6725 alreadyTriedUserIds.put(targetUserId, true); 6726 } 6727 } 6728 } 6729 return null; 6730 } 6731 6732 /** 6733 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6734 * will forward the intent to the filter's target user. 6735 * Otherwise, returns null. 6736 */ 6737 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6738 String resolvedType, int flags, int sourceUserId) { 6739 int targetUserId = filter.getTargetUserId(); 6740 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6741 resolvedType, flags, targetUserId); 6742 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6743 // If all the matches in the target profile are suspended, return null. 6744 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6745 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6746 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6747 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6748 targetUserId); 6749 } 6750 } 6751 } 6752 return null; 6753 } 6754 6755 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6756 int sourceUserId, int targetUserId) { 6757 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6758 long ident = Binder.clearCallingIdentity(); 6759 boolean targetIsProfile; 6760 try { 6761 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6762 } finally { 6763 Binder.restoreCallingIdentity(ident); 6764 } 6765 String className; 6766 if (targetIsProfile) { 6767 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6768 } else { 6769 className = FORWARD_INTENT_TO_PARENT; 6770 } 6771 ComponentName forwardingActivityComponentName = new ComponentName( 6772 mAndroidApplication.packageName, className); 6773 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6774 sourceUserId); 6775 if (!targetIsProfile) { 6776 forwardingActivityInfo.showUserIcon = targetUserId; 6777 forwardingResolveInfo.noResourceId = true; 6778 } 6779 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6780 forwardingResolveInfo.priority = 0; 6781 forwardingResolveInfo.preferredOrder = 0; 6782 forwardingResolveInfo.match = 0; 6783 forwardingResolveInfo.isDefault = true; 6784 forwardingResolveInfo.filter = filter; 6785 forwardingResolveInfo.targetUserId = targetUserId; 6786 return forwardingResolveInfo; 6787 } 6788 6789 @Override 6790 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6791 Intent[] specifics, String[] specificTypes, Intent intent, 6792 String resolvedType, int flags, int userId) { 6793 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6794 specificTypes, intent, resolvedType, flags, userId)); 6795 } 6796 6797 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6798 Intent[] specifics, String[] specificTypes, Intent intent, 6799 String resolvedType, int flags, int userId) { 6800 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6801 flags = updateFlagsForResolve(flags, userId, intent, false); 6802 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6803 false /* requireFullPermission */, false /* checkShell */, 6804 "query intent activity options"); 6805 final String resultsAction = intent.getAction(); 6806 6807 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6808 | PackageManager.GET_RESOLVED_FILTER, userId); 6809 6810 if (DEBUG_INTENT_MATCHING) { 6811 Log.v(TAG, "Query " + intent + ": " + results); 6812 } 6813 6814 int specificsPos = 0; 6815 int N; 6816 6817 // todo: note that the algorithm used here is O(N^2). This 6818 // isn't a problem in our current environment, but if we start running 6819 // into situations where we have more than 5 or 10 matches then this 6820 // should probably be changed to something smarter... 6821 6822 // First we go through and resolve each of the specific items 6823 // that were supplied, taking care of removing any corresponding 6824 // duplicate items in the generic resolve list. 6825 if (specifics != null) { 6826 for (int i=0; i<specifics.length; i++) { 6827 final Intent sintent = specifics[i]; 6828 if (sintent == null) { 6829 continue; 6830 } 6831 6832 if (DEBUG_INTENT_MATCHING) { 6833 Log.v(TAG, "Specific #" + i + ": " + sintent); 6834 } 6835 6836 String action = sintent.getAction(); 6837 if (resultsAction != null && resultsAction.equals(action)) { 6838 // If this action was explicitly requested, then don't 6839 // remove things that have it. 6840 action = null; 6841 } 6842 6843 ResolveInfo ri = null; 6844 ActivityInfo ai = null; 6845 6846 ComponentName comp = sintent.getComponent(); 6847 if (comp == null) { 6848 ri = resolveIntent( 6849 sintent, 6850 specificTypes != null ? specificTypes[i] : null, 6851 flags, userId); 6852 if (ri == null) { 6853 continue; 6854 } 6855 if (ri == mResolveInfo) { 6856 // ACK! Must do something better with this. 6857 } 6858 ai = ri.activityInfo; 6859 comp = new ComponentName(ai.applicationInfo.packageName, 6860 ai.name); 6861 } else { 6862 ai = getActivityInfo(comp, flags, userId); 6863 if (ai == null) { 6864 continue; 6865 } 6866 } 6867 6868 // Look for any generic query activities that are duplicates 6869 // of this specific one, and remove them from the results. 6870 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6871 N = results.size(); 6872 int j; 6873 for (j=specificsPos; j<N; j++) { 6874 ResolveInfo sri = results.get(j); 6875 if ((sri.activityInfo.name.equals(comp.getClassName()) 6876 && sri.activityInfo.applicationInfo.packageName.equals( 6877 comp.getPackageName())) 6878 || (action != null && sri.filter.matchAction(action))) { 6879 results.remove(j); 6880 if (DEBUG_INTENT_MATCHING) Log.v( 6881 TAG, "Removing duplicate item from " + j 6882 + " due to specific " + specificsPos); 6883 if (ri == null) { 6884 ri = sri; 6885 } 6886 j--; 6887 N--; 6888 } 6889 } 6890 6891 // Add this specific item to its proper place. 6892 if (ri == null) { 6893 ri = new ResolveInfo(); 6894 ri.activityInfo = ai; 6895 } 6896 results.add(specificsPos, ri); 6897 ri.specificIndex = i; 6898 specificsPos++; 6899 } 6900 } 6901 6902 // Now we go through the remaining generic results and remove any 6903 // duplicate actions that are found here. 6904 N = results.size(); 6905 for (int i=specificsPos; i<N-1; i++) { 6906 final ResolveInfo rii = results.get(i); 6907 if (rii.filter == null) { 6908 continue; 6909 } 6910 6911 // Iterate over all of the actions of this result's intent 6912 // filter... typically this should be just one. 6913 final Iterator<String> it = rii.filter.actionsIterator(); 6914 if (it == null) { 6915 continue; 6916 } 6917 while (it.hasNext()) { 6918 final String action = it.next(); 6919 if (resultsAction != null && resultsAction.equals(action)) { 6920 // If this action was explicitly requested, then don't 6921 // remove things that have it. 6922 continue; 6923 } 6924 for (int j=i+1; j<N; j++) { 6925 final ResolveInfo rij = results.get(j); 6926 if (rij.filter != null && rij.filter.hasAction(action)) { 6927 results.remove(j); 6928 if (DEBUG_INTENT_MATCHING) Log.v( 6929 TAG, "Removing duplicate item from " + j 6930 + " due to action " + action + " at " + i); 6931 j--; 6932 N--; 6933 } 6934 } 6935 } 6936 6937 // If the caller didn't request filter information, drop it now 6938 // so we don't have to marshall/unmarshall it. 6939 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6940 rii.filter = null; 6941 } 6942 } 6943 6944 // Filter out the caller activity if so requested. 6945 if (caller != null) { 6946 N = results.size(); 6947 for (int i=0; i<N; i++) { 6948 ActivityInfo ainfo = results.get(i).activityInfo; 6949 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6950 && caller.getClassName().equals(ainfo.name)) { 6951 results.remove(i); 6952 break; 6953 } 6954 } 6955 } 6956 6957 // If the caller didn't request filter information, 6958 // drop them now so we don't have to 6959 // marshall/unmarshall it. 6960 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6961 N = results.size(); 6962 for (int i=0; i<N; i++) { 6963 results.get(i).filter = null; 6964 } 6965 } 6966 6967 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6968 return results; 6969 } 6970 6971 @Override 6972 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6973 String resolvedType, int flags, int userId) { 6974 return new ParceledListSlice<>( 6975 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6976 } 6977 6978 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6979 String resolvedType, int flags, int userId) { 6980 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6981 flags = updateFlagsForResolve(flags, userId, intent, false); 6982 ComponentName comp = intent.getComponent(); 6983 if (comp == null) { 6984 if (intent.getSelector() != null) { 6985 intent = intent.getSelector(); 6986 comp = intent.getComponent(); 6987 } 6988 } 6989 if (comp != null) { 6990 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6991 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6992 if (ai != null) { 6993 ResolveInfo ri = new ResolveInfo(); 6994 ri.activityInfo = ai; 6995 list.add(ri); 6996 } 6997 return list; 6998 } 6999 7000 // reader 7001 synchronized (mPackages) { 7002 String pkgName = intent.getPackage(); 7003 if (pkgName == null) { 7004 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7005 } 7006 final PackageParser.Package pkg = mPackages.get(pkgName); 7007 if (pkg != null) { 7008 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7009 userId); 7010 } 7011 return Collections.emptyList(); 7012 } 7013 } 7014 7015 @Override 7016 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7017 if (!sUserManager.exists(userId)) return null; 7018 flags = updateFlagsForResolve(flags, userId, intent, false); 7019 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 7020 if (query != null) { 7021 if (query.size() >= 1) { 7022 // If there is more than one service with the same priority, 7023 // just arbitrarily pick the first one. 7024 return query.get(0); 7025 } 7026 } 7027 return null; 7028 } 7029 7030 @Override 7031 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7032 String resolvedType, int flags, int userId) { 7033 return new ParceledListSlice<>( 7034 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 7035 } 7036 7037 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7038 String resolvedType, int flags, int userId) { 7039 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7040 flags = updateFlagsForResolve(flags, userId, intent, false); 7041 ComponentName comp = intent.getComponent(); 7042 if (comp == null) { 7043 if (intent.getSelector() != null) { 7044 intent = intent.getSelector(); 7045 comp = intent.getComponent(); 7046 } 7047 } 7048 if (comp != null) { 7049 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7050 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7051 if (si != null) { 7052 final ResolveInfo ri = new ResolveInfo(); 7053 ri.serviceInfo = si; 7054 list.add(ri); 7055 } 7056 return list; 7057 } 7058 7059 // reader 7060 synchronized (mPackages) { 7061 String pkgName = intent.getPackage(); 7062 if (pkgName == null) { 7063 return mServices.queryIntent(intent, resolvedType, flags, userId); 7064 } 7065 final PackageParser.Package pkg = mPackages.get(pkgName); 7066 if (pkg != null) { 7067 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7068 userId); 7069 } 7070 return Collections.emptyList(); 7071 } 7072 } 7073 7074 @Override 7075 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7076 String resolvedType, int flags, int userId) { 7077 return new ParceledListSlice<>( 7078 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7079 } 7080 7081 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7082 Intent intent, String resolvedType, int flags, int userId) { 7083 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7084 flags = updateFlagsForResolve(flags, userId, intent, false); 7085 ComponentName comp = intent.getComponent(); 7086 if (comp == null) { 7087 if (intent.getSelector() != null) { 7088 intent = intent.getSelector(); 7089 comp = intent.getComponent(); 7090 } 7091 } 7092 if (comp != null) { 7093 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7094 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7095 if (pi != null) { 7096 final ResolveInfo ri = new ResolveInfo(); 7097 ri.providerInfo = pi; 7098 list.add(ri); 7099 } 7100 return list; 7101 } 7102 7103 // reader 7104 synchronized (mPackages) { 7105 String pkgName = intent.getPackage(); 7106 if (pkgName == null) { 7107 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7108 } 7109 final PackageParser.Package pkg = mPackages.get(pkgName); 7110 if (pkg != null) { 7111 return mProviders.queryIntentForPackage( 7112 intent, resolvedType, flags, pkg.providers, userId); 7113 } 7114 return Collections.emptyList(); 7115 } 7116 } 7117 7118 @Override 7119 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7120 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7121 flags = updateFlagsForPackage(flags, userId, null); 7122 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7123 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7124 true /* requireFullPermission */, false /* checkShell */, 7125 "get installed packages"); 7126 7127 // writer 7128 synchronized (mPackages) { 7129 ArrayList<PackageInfo> list; 7130 if (listUninstalled) { 7131 list = new ArrayList<>(mSettings.mPackages.size()); 7132 for (PackageSetting ps : mSettings.mPackages.values()) { 7133 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7134 continue; 7135 } 7136 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7137 if (pi != null) { 7138 list.add(pi); 7139 } 7140 } 7141 } else { 7142 list = new ArrayList<>(mPackages.size()); 7143 for (PackageParser.Package p : mPackages.values()) { 7144 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7145 Binder.getCallingUid(), userId)) { 7146 continue; 7147 } 7148 final PackageInfo pi = generatePackageInfo((PackageSetting) 7149 p.mExtras, flags, userId); 7150 if (pi != null) { 7151 list.add(pi); 7152 } 7153 } 7154 } 7155 7156 return new ParceledListSlice<>(list); 7157 } 7158 } 7159 7160 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7161 String[] permissions, boolean[] tmp, int flags, int userId) { 7162 int numMatch = 0; 7163 final PermissionsState permissionsState = ps.getPermissionsState(); 7164 for (int i=0; i<permissions.length; i++) { 7165 final String permission = permissions[i]; 7166 if (permissionsState.hasPermission(permission, userId)) { 7167 tmp[i] = true; 7168 numMatch++; 7169 } else { 7170 tmp[i] = false; 7171 } 7172 } 7173 if (numMatch == 0) { 7174 return; 7175 } 7176 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7177 7178 // The above might return null in cases of uninstalled apps or install-state 7179 // skew across users/profiles. 7180 if (pi != null) { 7181 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7182 if (numMatch == permissions.length) { 7183 pi.requestedPermissions = permissions; 7184 } else { 7185 pi.requestedPermissions = new String[numMatch]; 7186 numMatch = 0; 7187 for (int i=0; i<permissions.length; i++) { 7188 if (tmp[i]) { 7189 pi.requestedPermissions[numMatch] = permissions[i]; 7190 numMatch++; 7191 } 7192 } 7193 } 7194 } 7195 list.add(pi); 7196 } 7197 } 7198 7199 @Override 7200 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7201 String[] permissions, int flags, int userId) { 7202 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7203 flags = updateFlagsForPackage(flags, userId, permissions); 7204 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7205 true /* requireFullPermission */, false /* checkShell */, 7206 "get packages holding permissions"); 7207 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7208 7209 // writer 7210 synchronized (mPackages) { 7211 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7212 boolean[] tmpBools = new boolean[permissions.length]; 7213 if (listUninstalled) { 7214 for (PackageSetting ps : mSettings.mPackages.values()) { 7215 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7216 userId); 7217 } 7218 } else { 7219 for (PackageParser.Package pkg : mPackages.values()) { 7220 PackageSetting ps = (PackageSetting)pkg.mExtras; 7221 if (ps != null) { 7222 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7223 userId); 7224 } 7225 } 7226 } 7227 7228 return new ParceledListSlice<PackageInfo>(list); 7229 } 7230 } 7231 7232 @Override 7233 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7234 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7235 flags = updateFlagsForApplication(flags, userId, null); 7236 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7237 7238 // writer 7239 synchronized (mPackages) { 7240 ArrayList<ApplicationInfo> list; 7241 if (listUninstalled) { 7242 list = new ArrayList<>(mSettings.mPackages.size()); 7243 for (PackageSetting ps : mSettings.mPackages.values()) { 7244 ApplicationInfo ai; 7245 int effectiveFlags = flags; 7246 if (ps.isSystem()) { 7247 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7248 } 7249 if (ps.pkg != null) { 7250 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7251 continue; 7252 } 7253 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7254 ps.readUserState(userId), userId); 7255 if (ai != null) { 7256 rebaseEnabledOverlays(ai, userId); 7257 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7258 } 7259 } else { 7260 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7261 // and already converts to externally visible package name 7262 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7263 Binder.getCallingUid(), effectiveFlags, userId); 7264 } 7265 if (ai != null) { 7266 list.add(ai); 7267 } 7268 } 7269 } else { 7270 list = new ArrayList<>(mPackages.size()); 7271 for (PackageParser.Package p : mPackages.values()) { 7272 if (p.mExtras != null) { 7273 PackageSetting ps = (PackageSetting) p.mExtras; 7274 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7275 continue; 7276 } 7277 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7278 ps.readUserState(userId), userId); 7279 if (ai != null) { 7280 rebaseEnabledOverlays(ai, userId); 7281 ai.packageName = resolveExternalPackageNameLPr(p); 7282 list.add(ai); 7283 } 7284 } 7285 } 7286 } 7287 7288 return new ParceledListSlice<>(list); 7289 } 7290 } 7291 7292 @Override 7293 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7294 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7295 return null; 7296 } 7297 7298 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7299 "getEphemeralApplications"); 7300 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7301 true /* requireFullPermission */, false /* checkShell */, 7302 "getEphemeralApplications"); 7303 synchronized (mPackages) { 7304 List<InstantAppInfo> instantApps = mInstantAppRegistry 7305 .getInstantAppsLPr(userId); 7306 if (instantApps != null) { 7307 return new ParceledListSlice<>(instantApps); 7308 } 7309 } 7310 return null; 7311 } 7312 7313 @Override 7314 public boolean isInstantApp(String packageName, int userId) { 7315 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7316 true /* requireFullPermission */, false /* checkShell */, 7317 "isInstantApp"); 7318 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7319 return false; 7320 } 7321 7322 synchronized (mPackages) { 7323 final PackageSetting ps = mSettings.mPackages.get(packageName); 7324 final boolean returnAllowed = 7325 ps != null 7326 && (isCallerSameApp(packageName) 7327 || mContext.checkCallingOrSelfPermission( 7328 android.Manifest.permission.ACCESS_INSTANT_APPS) 7329 == PERMISSION_GRANTED 7330 || mInstantAppRegistry.isInstantAccessGranted( 7331 userId, UserHandle.getAppId(Binder.getCallingUid()), ps.appId)); 7332 if (returnAllowed) { 7333 return ps.getInstantApp(userId); 7334 } 7335 } 7336 return false; 7337 } 7338 7339 @Override 7340 public byte[] getInstantAppCookie(String packageName, int userId) { 7341 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7342 return null; 7343 } 7344 7345 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7346 true /* requireFullPermission */, false /* checkShell */, 7347 "getInstantAppCookie"); 7348 if (!isCallerSameApp(packageName)) { 7349 return null; 7350 } 7351 synchronized (mPackages) { 7352 return mInstantAppRegistry.getInstantAppCookieLPw( 7353 packageName, userId); 7354 } 7355 } 7356 7357 @Override 7358 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7359 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7360 return true; 7361 } 7362 7363 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7364 true /* requireFullPermission */, true /* checkShell */, 7365 "setInstantAppCookie"); 7366 if (!isCallerSameApp(packageName)) { 7367 return false; 7368 } 7369 synchronized (mPackages) { 7370 return mInstantAppRegistry.setInstantAppCookieLPw( 7371 packageName, cookie, userId); 7372 } 7373 } 7374 7375 @Override 7376 public Bitmap getInstantAppIcon(String packageName, int userId) { 7377 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7378 return null; 7379 } 7380 7381 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7382 "getInstantAppIcon"); 7383 7384 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7385 true /* requireFullPermission */, false /* checkShell */, 7386 "getInstantAppIcon"); 7387 7388 synchronized (mPackages) { 7389 return mInstantAppRegistry.getInstantAppIconLPw( 7390 packageName, userId); 7391 } 7392 } 7393 7394 private boolean isCallerSameApp(String packageName) { 7395 PackageParser.Package pkg = mPackages.get(packageName); 7396 return pkg != null 7397 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 7398 } 7399 7400 @Override 7401 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7402 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7403 } 7404 7405 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7406 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7407 7408 // reader 7409 synchronized (mPackages) { 7410 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7411 final int userId = UserHandle.getCallingUserId(); 7412 while (i.hasNext()) { 7413 final PackageParser.Package p = i.next(); 7414 if (p.applicationInfo == null) continue; 7415 7416 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7417 && !p.applicationInfo.isDirectBootAware(); 7418 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7419 && p.applicationInfo.isDirectBootAware(); 7420 7421 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7422 && (!mSafeMode || isSystemApp(p)) 7423 && (matchesUnaware || matchesAware)) { 7424 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7425 if (ps != null) { 7426 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7427 ps.readUserState(userId), userId); 7428 if (ai != null) { 7429 rebaseEnabledOverlays(ai, userId); 7430 finalList.add(ai); 7431 } 7432 } 7433 } 7434 } 7435 } 7436 7437 return finalList; 7438 } 7439 7440 @Override 7441 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7442 if (!sUserManager.exists(userId)) return null; 7443 flags = updateFlagsForComponent(flags, userId, name); 7444 // reader 7445 synchronized (mPackages) { 7446 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7447 PackageSetting ps = provider != null 7448 ? mSettings.mPackages.get(provider.owner.packageName) 7449 : null; 7450 return ps != null 7451 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7452 ? PackageParser.generateProviderInfo(provider, flags, 7453 ps.readUserState(userId), userId) 7454 : null; 7455 } 7456 } 7457 7458 /** 7459 * @deprecated 7460 */ 7461 @Deprecated 7462 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7463 // reader 7464 synchronized (mPackages) { 7465 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7466 .entrySet().iterator(); 7467 final int userId = UserHandle.getCallingUserId(); 7468 while (i.hasNext()) { 7469 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7470 PackageParser.Provider p = entry.getValue(); 7471 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7472 7473 if (ps != null && p.syncable 7474 && (!mSafeMode || (p.info.applicationInfo.flags 7475 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7476 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7477 ps.readUserState(userId), userId); 7478 if (info != null) { 7479 outNames.add(entry.getKey()); 7480 outInfo.add(info); 7481 } 7482 } 7483 } 7484 } 7485 } 7486 7487 @Override 7488 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7489 int uid, int flags, String metaDataKey) { 7490 final int userId = processName != null ? UserHandle.getUserId(uid) 7491 : UserHandle.getCallingUserId(); 7492 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7493 flags = updateFlagsForComponent(flags, userId, processName); 7494 7495 ArrayList<ProviderInfo> finalList = null; 7496 // reader 7497 synchronized (mPackages) { 7498 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7499 while (i.hasNext()) { 7500 final PackageParser.Provider p = i.next(); 7501 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7502 if (ps != null && p.info.authority != null 7503 && (processName == null 7504 || (p.info.processName.equals(processName) 7505 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7506 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7507 7508 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7509 // parameter. 7510 if (metaDataKey != null 7511 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7512 continue; 7513 } 7514 7515 if (finalList == null) { 7516 finalList = new ArrayList<ProviderInfo>(3); 7517 } 7518 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7519 ps.readUserState(userId), userId); 7520 if (info != null) { 7521 finalList.add(info); 7522 } 7523 } 7524 } 7525 } 7526 7527 if (finalList != null) { 7528 Collections.sort(finalList, mProviderInitOrderSorter); 7529 return new ParceledListSlice<ProviderInfo>(finalList); 7530 } 7531 7532 return ParceledListSlice.emptyList(); 7533 } 7534 7535 @Override 7536 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7537 // reader 7538 synchronized (mPackages) { 7539 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7540 return PackageParser.generateInstrumentationInfo(i, flags); 7541 } 7542 } 7543 7544 @Override 7545 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7546 String targetPackage, int flags) { 7547 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7548 } 7549 7550 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7551 int flags) { 7552 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7553 7554 // reader 7555 synchronized (mPackages) { 7556 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7557 while (i.hasNext()) { 7558 final PackageParser.Instrumentation p = i.next(); 7559 if (targetPackage == null 7560 || targetPackage.equals(p.info.targetPackage)) { 7561 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7562 flags); 7563 if (ii != null) { 7564 finalList.add(ii); 7565 } 7566 } 7567 } 7568 } 7569 7570 return finalList; 7571 } 7572 7573 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7574 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7575 try { 7576 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7577 } finally { 7578 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7579 } 7580 } 7581 7582 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7583 final File[] files = dir.listFiles(); 7584 if (ArrayUtils.isEmpty(files)) { 7585 Log.d(TAG, "No files in app dir " + dir); 7586 return; 7587 } 7588 7589 if (DEBUG_PACKAGE_SCANNING) { 7590 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7591 + " flags=0x" + Integer.toHexString(parseFlags)); 7592 } 7593 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7594 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7595 7596 // Submit files for parsing in parallel 7597 int fileCount = 0; 7598 for (File file : files) { 7599 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7600 && !PackageInstallerService.isStageName(file.getName()); 7601 if (!isPackage) { 7602 // Ignore entries which are not packages 7603 continue; 7604 } 7605 parallelPackageParser.submit(file, parseFlags); 7606 fileCount++; 7607 } 7608 7609 // Process results one by one 7610 for (; fileCount > 0; fileCount--) { 7611 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7612 Throwable throwable = parseResult.throwable; 7613 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7614 7615 if (throwable == null) { 7616 // Static shared libraries have synthetic package names 7617 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7618 renameStaticSharedLibraryPackage(parseResult.pkg); 7619 } 7620 try { 7621 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7622 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7623 currentTime, null); 7624 } 7625 } catch (PackageManagerException e) { 7626 errorCode = e.error; 7627 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7628 } 7629 } else if (throwable instanceof PackageParser.PackageParserException) { 7630 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7631 throwable; 7632 errorCode = e.error; 7633 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7634 } else { 7635 throw new IllegalStateException("Unexpected exception occurred while parsing " 7636 + parseResult.scanFile, throwable); 7637 } 7638 7639 // Delete invalid userdata apps 7640 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7641 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7642 logCriticalInfo(Log.WARN, 7643 "Deleting invalid package at " + parseResult.scanFile); 7644 removeCodePathLI(parseResult.scanFile); 7645 } 7646 } 7647 parallelPackageParser.close(); 7648 } 7649 7650 private static File getSettingsProblemFile() { 7651 File dataDir = Environment.getDataDirectory(); 7652 File systemDir = new File(dataDir, "system"); 7653 File fname = new File(systemDir, "uiderrors.txt"); 7654 return fname; 7655 } 7656 7657 static void reportSettingsProblem(int priority, String msg) { 7658 logCriticalInfo(priority, msg); 7659 } 7660 7661 public static void logCriticalInfo(int priority, String msg) { 7662 Slog.println(priority, TAG, msg); 7663 EventLogTags.writePmCriticalInfo(msg); 7664 try { 7665 File fname = getSettingsProblemFile(); 7666 FileOutputStream out = new FileOutputStream(fname, true); 7667 PrintWriter pw = new FastPrintWriter(out); 7668 SimpleDateFormat formatter = new SimpleDateFormat(); 7669 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7670 pw.println(dateString + ": " + msg); 7671 pw.close(); 7672 FileUtils.setPermissions( 7673 fname.toString(), 7674 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7675 -1, -1); 7676 } catch (java.io.IOException e) { 7677 } 7678 } 7679 7680 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7681 if (srcFile.isDirectory()) { 7682 final File baseFile = new File(pkg.baseCodePath); 7683 long maxModifiedTime = baseFile.lastModified(); 7684 if (pkg.splitCodePaths != null) { 7685 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7686 final File splitFile = new File(pkg.splitCodePaths[i]); 7687 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7688 } 7689 } 7690 return maxModifiedTime; 7691 } 7692 return srcFile.lastModified(); 7693 } 7694 7695 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7696 final int policyFlags) throws PackageManagerException { 7697 // When upgrading from pre-N MR1, verify the package time stamp using the package 7698 // directory and not the APK file. 7699 final long lastModifiedTime = mIsPreNMR1Upgrade 7700 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7701 if (ps != null 7702 && ps.codePath.equals(srcFile) 7703 && ps.timeStamp == lastModifiedTime 7704 && !isCompatSignatureUpdateNeeded(pkg) 7705 && !isRecoverSignatureUpdateNeeded(pkg)) { 7706 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7707 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7708 ArraySet<PublicKey> signingKs; 7709 synchronized (mPackages) { 7710 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7711 } 7712 if (ps.signatures.mSignatures != null 7713 && ps.signatures.mSignatures.length != 0 7714 && signingKs != null) { 7715 // Optimization: reuse the existing cached certificates 7716 // if the package appears to be unchanged. 7717 pkg.mSignatures = ps.signatures.mSignatures; 7718 pkg.mSigningKeys = signingKs; 7719 return; 7720 } 7721 7722 Slog.w(TAG, "PackageSetting for " + ps.name 7723 + " is missing signatures. Collecting certs again to recover them."); 7724 } else { 7725 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7726 } 7727 7728 try { 7729 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7730 PackageParser.collectCertificates(pkg, policyFlags); 7731 } catch (PackageParserException e) { 7732 throw PackageManagerException.from(e); 7733 } finally { 7734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7735 } 7736 } 7737 7738 /** 7739 * Traces a package scan. 7740 * @see #scanPackageLI(File, int, int, long, UserHandle) 7741 */ 7742 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7743 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7744 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7745 try { 7746 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7747 } finally { 7748 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7749 } 7750 } 7751 7752 /** 7753 * Scans a package and returns the newly parsed package. 7754 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7755 */ 7756 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7757 long currentTime, UserHandle user) throws PackageManagerException { 7758 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7759 PackageParser pp = new PackageParser(); 7760 pp.setSeparateProcesses(mSeparateProcesses); 7761 pp.setOnlyCoreApps(mOnlyCore); 7762 pp.setDisplayMetrics(mMetrics); 7763 pp.setCallback(mPackageParserCallback); 7764 7765 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7766 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7767 } 7768 7769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7770 final PackageParser.Package pkg; 7771 try { 7772 pkg = pp.parsePackage(scanFile, parseFlags); 7773 } catch (PackageParserException e) { 7774 throw PackageManagerException.from(e); 7775 } finally { 7776 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7777 } 7778 7779 // Static shared libraries have synthetic package names 7780 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7781 renameStaticSharedLibraryPackage(pkg); 7782 } 7783 7784 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7785 } 7786 7787 /** 7788 * Scans a package and returns the newly parsed package. 7789 * @throws PackageManagerException on a parse error. 7790 */ 7791 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7792 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7793 throws PackageManagerException { 7794 // If the package has children and this is the first dive in the function 7795 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7796 // packages (parent and children) would be successfully scanned before the 7797 // actual scan since scanning mutates internal state and we want to atomically 7798 // install the package and its children. 7799 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7800 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7801 scanFlags |= SCAN_CHECK_ONLY; 7802 } 7803 } else { 7804 scanFlags &= ~SCAN_CHECK_ONLY; 7805 } 7806 7807 // Scan the parent 7808 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7809 scanFlags, currentTime, user); 7810 7811 // Scan the children 7812 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7813 for (int i = 0; i < childCount; i++) { 7814 PackageParser.Package childPackage = pkg.childPackages.get(i); 7815 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7816 currentTime, user); 7817 } 7818 7819 7820 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7821 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7822 } 7823 7824 return scannedPkg; 7825 } 7826 7827 /** 7828 * Scans a package and returns the newly parsed package. 7829 * @throws PackageManagerException on a parse error. 7830 */ 7831 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7832 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7833 throws PackageManagerException { 7834 PackageSetting ps = null; 7835 PackageSetting updatedPkg; 7836 // reader 7837 synchronized (mPackages) { 7838 // Look to see if we already know about this package. 7839 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7840 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7841 // This package has been renamed to its original name. Let's 7842 // use that. 7843 ps = mSettings.getPackageLPr(oldName); 7844 } 7845 // If there was no original package, see one for the real package name. 7846 if (ps == null) { 7847 ps = mSettings.getPackageLPr(pkg.packageName); 7848 } 7849 // Check to see if this package could be hiding/updating a system 7850 // package. Must look for it either under the original or real 7851 // package name depending on our state. 7852 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7853 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7854 7855 // If this is a package we don't know about on the system partition, we 7856 // may need to remove disabled child packages on the system partition 7857 // or may need to not add child packages if the parent apk is updated 7858 // on the data partition and no longer defines this child package. 7859 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7860 // If this is a parent package for an updated system app and this system 7861 // app got an OTA update which no longer defines some of the child packages 7862 // we have to prune them from the disabled system packages. 7863 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7864 if (disabledPs != null) { 7865 final int scannedChildCount = (pkg.childPackages != null) 7866 ? pkg.childPackages.size() : 0; 7867 final int disabledChildCount = disabledPs.childPackageNames != null 7868 ? disabledPs.childPackageNames.size() : 0; 7869 for (int i = 0; i < disabledChildCount; i++) { 7870 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7871 boolean disabledPackageAvailable = false; 7872 for (int j = 0; j < scannedChildCount; j++) { 7873 PackageParser.Package childPkg = pkg.childPackages.get(j); 7874 if (childPkg.packageName.equals(disabledChildPackageName)) { 7875 disabledPackageAvailable = true; 7876 break; 7877 } 7878 } 7879 if (!disabledPackageAvailable) { 7880 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7881 } 7882 } 7883 } 7884 } 7885 } 7886 7887 boolean updatedPkgBetter = false; 7888 // First check if this is a system package that may involve an update 7889 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7890 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7891 // it needs to drop FLAG_PRIVILEGED. 7892 if (locationIsPrivileged(scanFile)) { 7893 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7894 } else { 7895 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7896 } 7897 7898 if (ps != null && !ps.codePath.equals(scanFile)) { 7899 // The path has changed from what was last scanned... check the 7900 // version of the new path against what we have stored to determine 7901 // what to do. 7902 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7903 if (pkg.mVersionCode <= ps.versionCode) { 7904 // The system package has been updated and the code path does not match 7905 // Ignore entry. Skip it. 7906 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7907 + " ignored: updated version " + ps.versionCode 7908 + " better than this " + pkg.mVersionCode); 7909 if (!updatedPkg.codePath.equals(scanFile)) { 7910 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7911 + ps.name + " changing from " + updatedPkg.codePathString 7912 + " to " + scanFile); 7913 updatedPkg.codePath = scanFile; 7914 updatedPkg.codePathString = scanFile.toString(); 7915 updatedPkg.resourcePath = scanFile; 7916 updatedPkg.resourcePathString = scanFile.toString(); 7917 } 7918 updatedPkg.pkg = pkg; 7919 updatedPkg.versionCode = pkg.mVersionCode; 7920 7921 // Update the disabled system child packages to point to the package too. 7922 final int childCount = updatedPkg.childPackageNames != null 7923 ? updatedPkg.childPackageNames.size() : 0; 7924 for (int i = 0; i < childCount; i++) { 7925 String childPackageName = updatedPkg.childPackageNames.get(i); 7926 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7927 childPackageName); 7928 if (updatedChildPkg != null) { 7929 updatedChildPkg.pkg = pkg; 7930 updatedChildPkg.versionCode = pkg.mVersionCode; 7931 } 7932 } 7933 7934 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7935 + scanFile + " ignored: updated version " + ps.versionCode 7936 + " better than this " + pkg.mVersionCode); 7937 } else { 7938 // The current app on the system partition is better than 7939 // what we have updated to on the data partition; switch 7940 // back to the system partition version. 7941 // At this point, its safely assumed that package installation for 7942 // apps in system partition will go through. If not there won't be a working 7943 // version of the app 7944 // writer 7945 synchronized (mPackages) { 7946 // Just remove the loaded entries from package lists. 7947 mPackages.remove(ps.name); 7948 } 7949 7950 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7951 + " reverting from " + ps.codePathString 7952 + ": new version " + pkg.mVersionCode 7953 + " better than installed " + ps.versionCode); 7954 7955 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7956 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7957 synchronized (mInstallLock) { 7958 args.cleanUpResourcesLI(); 7959 } 7960 synchronized (mPackages) { 7961 mSettings.enableSystemPackageLPw(ps.name); 7962 } 7963 updatedPkgBetter = true; 7964 } 7965 } 7966 } 7967 7968 if (updatedPkg != null) { 7969 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7970 // initially 7971 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7972 7973 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7974 // flag set initially 7975 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7976 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7977 } 7978 } 7979 7980 // Verify certificates against what was last scanned 7981 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7982 7983 /* 7984 * A new system app appeared, but we already had a non-system one of the 7985 * same name installed earlier. 7986 */ 7987 boolean shouldHideSystemApp = false; 7988 if (updatedPkg == null && ps != null 7989 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7990 /* 7991 * Check to make sure the signatures match first. If they don't, 7992 * wipe the installed application and its data. 7993 */ 7994 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7995 != PackageManager.SIGNATURE_MATCH) { 7996 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7997 + " signatures don't match existing userdata copy; removing"); 7998 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7999 "scanPackageInternalLI")) { 8000 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8001 } 8002 ps = null; 8003 } else { 8004 /* 8005 * If the newly-added system app is an older version than the 8006 * already installed version, hide it. It will be scanned later 8007 * and re-added like an update. 8008 */ 8009 if (pkg.mVersionCode <= ps.versionCode) { 8010 shouldHideSystemApp = true; 8011 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8012 + " but new version " + pkg.mVersionCode + " better than installed " 8013 + ps.versionCode + "; hiding system"); 8014 } else { 8015 /* 8016 * The newly found system app is a newer version that the 8017 * one previously installed. Simply remove the 8018 * already-installed application and replace it with our own 8019 * while keeping the application data. 8020 */ 8021 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8022 + " reverting from " + ps.codePathString + ": new version " 8023 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8024 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8025 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8026 synchronized (mInstallLock) { 8027 args.cleanUpResourcesLI(); 8028 } 8029 } 8030 } 8031 } 8032 8033 // The apk is forward locked (not public) if its code and resources 8034 // are kept in different files. (except for app in either system or 8035 // vendor path). 8036 // TODO grab this value from PackageSettings 8037 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8038 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8039 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8040 } 8041 } 8042 8043 // TODO: extend to support forward-locked splits 8044 String resourcePath = null; 8045 String baseResourcePath = null; 8046 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8047 if (ps != null && ps.resourcePathString != null) { 8048 resourcePath = ps.resourcePathString; 8049 baseResourcePath = ps.resourcePathString; 8050 } else { 8051 // Should not happen at all. Just log an error. 8052 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8053 } 8054 } else { 8055 resourcePath = pkg.codePath; 8056 baseResourcePath = pkg.baseCodePath; 8057 } 8058 8059 // Set application objects path explicitly. 8060 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8061 pkg.setApplicationInfoCodePath(pkg.codePath); 8062 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8063 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8064 pkg.setApplicationInfoResourcePath(resourcePath); 8065 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8066 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8067 8068 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8069 if (ps != null && ps.getInstantApp(userId)) { 8070 scanFlags |= SCAN_AS_INSTANT_APP; 8071 } 8072 8073 // Note that we invoke the following method only if we are about to unpack an application 8074 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8075 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8076 8077 /* 8078 * If the system app should be overridden by a previously installed 8079 * data, hide the system app now and let the /data/app scan pick it up 8080 * again. 8081 */ 8082 if (shouldHideSystemApp) { 8083 synchronized (mPackages) { 8084 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8085 } 8086 } 8087 8088 return scannedPkg; 8089 } 8090 8091 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8092 // Derive the new package synthetic package name 8093 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8094 + pkg.staticSharedLibVersion); 8095 } 8096 8097 private static String fixProcessName(String defProcessName, 8098 String processName) { 8099 if (processName == null) { 8100 return defProcessName; 8101 } 8102 return processName; 8103 } 8104 8105 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8106 throws PackageManagerException { 8107 if (pkgSetting.signatures.mSignatures != null) { 8108 // Already existing package. Make sure signatures match 8109 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8110 == PackageManager.SIGNATURE_MATCH; 8111 if (!match) { 8112 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8113 == PackageManager.SIGNATURE_MATCH; 8114 } 8115 if (!match) { 8116 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8117 == PackageManager.SIGNATURE_MATCH; 8118 } 8119 if (!match) { 8120 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8121 + pkg.packageName + " signatures do not match the " 8122 + "previously installed version; ignoring!"); 8123 } 8124 } 8125 8126 // Check for shared user signatures 8127 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8128 // Already existing package. Make sure signatures match 8129 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8130 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8131 if (!match) { 8132 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8133 == PackageManager.SIGNATURE_MATCH; 8134 } 8135 if (!match) { 8136 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8137 == PackageManager.SIGNATURE_MATCH; 8138 } 8139 if (!match) { 8140 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8141 "Package " + pkg.packageName 8142 + " has no signatures that match those in shared user " 8143 + pkgSetting.sharedUser.name + "; ignoring!"); 8144 } 8145 } 8146 } 8147 8148 /** 8149 * Enforces that only the system UID or root's UID can call a method exposed 8150 * via Binder. 8151 * 8152 * @param message used as message if SecurityException is thrown 8153 * @throws SecurityException if the caller is not system or root 8154 */ 8155 private static final void enforceSystemOrRoot(String message) { 8156 final int uid = Binder.getCallingUid(); 8157 if (uid != Process.SYSTEM_UID && uid != 0) { 8158 throw new SecurityException(message); 8159 } 8160 } 8161 8162 @Override 8163 public void performFstrimIfNeeded() { 8164 enforceSystemOrRoot("Only the system can request fstrim"); 8165 8166 // Before everything else, see whether we need to fstrim. 8167 try { 8168 IStorageManager sm = PackageHelper.getStorageManager(); 8169 if (sm != null) { 8170 boolean doTrim = false; 8171 final long interval = android.provider.Settings.Global.getLong( 8172 mContext.getContentResolver(), 8173 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8174 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8175 if (interval > 0) { 8176 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8177 if (timeSinceLast > interval) { 8178 doTrim = true; 8179 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8180 + "; running immediately"); 8181 } 8182 } 8183 if (doTrim) { 8184 final boolean dexOptDialogShown; 8185 synchronized (mPackages) { 8186 dexOptDialogShown = mDexOptDialogShown; 8187 } 8188 if (!isFirstBoot() && dexOptDialogShown) { 8189 try { 8190 ActivityManager.getService().showBootMessage( 8191 mContext.getResources().getString( 8192 R.string.android_upgrading_fstrim), true); 8193 } catch (RemoteException e) { 8194 } 8195 } 8196 sm.runMaintenance(); 8197 } 8198 } else { 8199 Slog.e(TAG, "storageManager service unavailable!"); 8200 } 8201 } catch (RemoteException e) { 8202 // Can't happen; StorageManagerService is local 8203 } 8204 } 8205 8206 @Override 8207 public void updatePackagesIfNeeded() { 8208 enforceSystemOrRoot("Only the system can request package update"); 8209 8210 // We need to re-extract after an OTA. 8211 boolean causeUpgrade = isUpgrade(); 8212 8213 // First boot or factory reset. 8214 // Note: we also handle devices that are upgrading to N right now as if it is their 8215 // first boot, as they do not have profile data. 8216 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8217 8218 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8219 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8220 8221 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8222 return; 8223 } 8224 8225 List<PackageParser.Package> pkgs; 8226 synchronized (mPackages) { 8227 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8228 } 8229 8230 final long startTime = System.nanoTime(); 8231 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8232 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8233 8234 final int elapsedTimeSeconds = 8235 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8236 8237 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8238 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8239 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8240 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8241 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8242 } 8243 8244 /** 8245 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8246 * containing statistics about the invocation. The array consists of three elements, 8247 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8248 * and {@code numberOfPackagesFailed}. 8249 */ 8250 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8251 String compilerFilter) { 8252 8253 int numberOfPackagesVisited = 0; 8254 int numberOfPackagesOptimized = 0; 8255 int numberOfPackagesSkipped = 0; 8256 int numberOfPackagesFailed = 0; 8257 final int numberOfPackagesToDexopt = pkgs.size(); 8258 8259 for (PackageParser.Package pkg : pkgs) { 8260 numberOfPackagesVisited++; 8261 8262 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8263 if (DEBUG_DEXOPT) { 8264 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8265 } 8266 numberOfPackagesSkipped++; 8267 continue; 8268 } 8269 8270 if (DEBUG_DEXOPT) { 8271 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8272 numberOfPackagesToDexopt + ": " + pkg.packageName); 8273 } 8274 8275 if (showDialog) { 8276 try { 8277 ActivityManager.getService().showBootMessage( 8278 mContext.getResources().getString(R.string.android_upgrading_apk, 8279 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8280 } catch (RemoteException e) { 8281 } 8282 synchronized (mPackages) { 8283 mDexOptDialogShown = true; 8284 } 8285 } 8286 8287 // If the OTA updates a system app which was previously preopted to a non-preopted state 8288 // the app might end up being verified at runtime. That's because by default the apps 8289 // are verify-profile but for preopted apps there's no profile. 8290 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8291 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8292 // filter (by default interpret-only). 8293 // Note that at this stage unused apps are already filtered. 8294 if (isSystemApp(pkg) && 8295 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8296 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8297 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8298 } 8299 8300 // checkProfiles is false to avoid merging profiles during boot which 8301 // might interfere with background compilation (b/28612421). 8302 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8303 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8304 // trade-off worth doing to save boot time work. 8305 int dexOptStatus = performDexOptTraced(pkg.packageName, 8306 false /* checkProfiles */, 8307 compilerFilter, 8308 false /* force */); 8309 switch (dexOptStatus) { 8310 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8311 numberOfPackagesOptimized++; 8312 break; 8313 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8314 numberOfPackagesSkipped++; 8315 break; 8316 case PackageDexOptimizer.DEX_OPT_FAILED: 8317 numberOfPackagesFailed++; 8318 break; 8319 default: 8320 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8321 break; 8322 } 8323 } 8324 8325 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8326 numberOfPackagesFailed }; 8327 } 8328 8329 @Override 8330 public void notifyPackageUse(String packageName, int reason) { 8331 synchronized (mPackages) { 8332 PackageParser.Package p = mPackages.get(packageName); 8333 if (p == null) { 8334 return; 8335 } 8336 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8337 } 8338 } 8339 8340 @Override 8341 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8342 int userId = UserHandle.getCallingUserId(); 8343 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8344 if (ai == null) { 8345 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8346 + loadingPackageName + ", user=" + userId); 8347 return; 8348 } 8349 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8350 } 8351 8352 // TODO: this is not used nor needed. Delete it. 8353 @Override 8354 public boolean performDexOptIfNeeded(String packageName) { 8355 int dexOptStatus = performDexOptTraced(packageName, 8356 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8357 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8358 } 8359 8360 @Override 8361 public boolean performDexOpt(String packageName, 8362 boolean checkProfiles, int compileReason, boolean force) { 8363 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8364 getCompilerFilterForReason(compileReason), force); 8365 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8366 } 8367 8368 @Override 8369 public boolean performDexOptMode(String packageName, 8370 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8371 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8372 targetCompilerFilter, force); 8373 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8374 } 8375 8376 private int performDexOptTraced(String packageName, 8377 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8378 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8379 try { 8380 return performDexOptInternal(packageName, checkProfiles, 8381 targetCompilerFilter, force); 8382 } finally { 8383 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8384 } 8385 } 8386 8387 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8388 // if the package can now be considered up to date for the given filter. 8389 private int performDexOptInternal(String packageName, 8390 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8391 PackageParser.Package p; 8392 synchronized (mPackages) { 8393 p = mPackages.get(packageName); 8394 if (p == null) { 8395 // Package could not be found. Report failure. 8396 return PackageDexOptimizer.DEX_OPT_FAILED; 8397 } 8398 mPackageUsage.maybeWriteAsync(mPackages); 8399 mCompilerStats.maybeWriteAsync(); 8400 } 8401 long callingId = Binder.clearCallingIdentity(); 8402 try { 8403 synchronized (mInstallLock) { 8404 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8405 targetCompilerFilter, force); 8406 } 8407 } finally { 8408 Binder.restoreCallingIdentity(callingId); 8409 } 8410 } 8411 8412 public ArraySet<String> getOptimizablePackages() { 8413 ArraySet<String> pkgs = new ArraySet<String>(); 8414 synchronized (mPackages) { 8415 for (PackageParser.Package p : mPackages.values()) { 8416 if (PackageDexOptimizer.canOptimizePackage(p)) { 8417 pkgs.add(p.packageName); 8418 } 8419 } 8420 } 8421 return pkgs; 8422 } 8423 8424 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8425 boolean checkProfiles, String targetCompilerFilter, 8426 boolean force) { 8427 // Select the dex optimizer based on the force parameter. 8428 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8429 // allocate an object here. 8430 PackageDexOptimizer pdo = force 8431 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8432 : mPackageDexOptimizer; 8433 8434 // Optimize all dependencies first. Note: we ignore the return value and march on 8435 // on errors. 8436 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8437 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8438 if (!deps.isEmpty()) { 8439 for (PackageParser.Package depPackage : deps) { 8440 // TODO: Analyze and investigate if we (should) profile libraries. 8441 // Currently this will do a full compilation of the library by default. 8442 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8443 false /* checkProfiles */, 8444 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 8445 getOrCreateCompilerPackageStats(depPackage), 8446 mDexManager.isUsedByOtherApps(p.packageName)); 8447 } 8448 } 8449 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8450 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8451 mDexManager.isUsedByOtherApps(p.packageName)); 8452 } 8453 8454 // Performs dexopt on the used secondary dex files belonging to the given package. 8455 // Returns true if all dex files were process successfully (which could mean either dexopt or 8456 // skip). Returns false if any of the files caused errors. 8457 @Override 8458 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8459 boolean force) { 8460 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8461 } 8462 8463 public boolean performDexOptSecondary(String packageName, int compileReason, 8464 boolean force) { 8465 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8466 } 8467 8468 /** 8469 * Reconcile the information we have about the secondary dex files belonging to 8470 * {@code packagName} and the actual dex files. For all dex files that were 8471 * deleted, update the internal records and delete the generated oat files. 8472 */ 8473 @Override 8474 public void reconcileSecondaryDexFiles(String packageName) { 8475 mDexManager.reconcileSecondaryDexFiles(packageName); 8476 } 8477 8478 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8479 // a reference there. 8480 /*package*/ DexManager getDexManager() { 8481 return mDexManager; 8482 } 8483 8484 /** 8485 * Execute the background dexopt job immediately. 8486 */ 8487 @Override 8488 public boolean runBackgroundDexoptJob() { 8489 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8490 } 8491 8492 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8493 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8494 || p.usesStaticLibraries != null) { 8495 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8496 Set<String> collectedNames = new HashSet<>(); 8497 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8498 8499 retValue.remove(p); 8500 8501 return retValue; 8502 } else { 8503 return Collections.emptyList(); 8504 } 8505 } 8506 8507 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8508 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8509 if (!collectedNames.contains(p.packageName)) { 8510 collectedNames.add(p.packageName); 8511 collected.add(p); 8512 8513 if (p.usesLibraries != null) { 8514 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8515 null, collected, collectedNames); 8516 } 8517 if (p.usesOptionalLibraries != null) { 8518 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8519 null, collected, collectedNames); 8520 } 8521 if (p.usesStaticLibraries != null) { 8522 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8523 p.usesStaticLibrariesVersions, collected, collectedNames); 8524 } 8525 } 8526 } 8527 8528 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8529 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8530 final int libNameCount = libs.size(); 8531 for (int i = 0; i < libNameCount; i++) { 8532 String libName = libs.get(i); 8533 int version = (versions != null && versions.length == libNameCount) 8534 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8535 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8536 if (libPkg != null) { 8537 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8538 } 8539 } 8540 } 8541 8542 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8543 synchronized (mPackages) { 8544 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8545 if (libEntry != null) { 8546 return mPackages.get(libEntry.apk); 8547 } 8548 return null; 8549 } 8550 } 8551 8552 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8553 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8554 if (versionedLib == null) { 8555 return null; 8556 } 8557 return versionedLib.get(version); 8558 } 8559 8560 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8561 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8562 pkg.staticSharedLibName); 8563 if (versionedLib == null) { 8564 return null; 8565 } 8566 int previousLibVersion = -1; 8567 final int versionCount = versionedLib.size(); 8568 for (int i = 0; i < versionCount; i++) { 8569 final int libVersion = versionedLib.keyAt(i); 8570 if (libVersion < pkg.staticSharedLibVersion) { 8571 previousLibVersion = Math.max(previousLibVersion, libVersion); 8572 } 8573 } 8574 if (previousLibVersion >= 0) { 8575 return versionedLib.get(previousLibVersion); 8576 } 8577 return null; 8578 } 8579 8580 public void shutdown() { 8581 mPackageUsage.writeNow(mPackages); 8582 mCompilerStats.writeNow(); 8583 } 8584 8585 @Override 8586 public void dumpProfiles(String packageName) { 8587 PackageParser.Package pkg; 8588 synchronized (mPackages) { 8589 pkg = mPackages.get(packageName); 8590 if (pkg == null) { 8591 throw new IllegalArgumentException("Unknown package: " + packageName); 8592 } 8593 } 8594 /* Only the shell, root, or the app user should be able to dump profiles. */ 8595 int callingUid = Binder.getCallingUid(); 8596 if (callingUid != Process.SHELL_UID && 8597 callingUid != Process.ROOT_UID && 8598 callingUid != pkg.applicationInfo.uid) { 8599 throw new SecurityException("dumpProfiles"); 8600 } 8601 8602 synchronized (mInstallLock) { 8603 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8604 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8605 try { 8606 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8607 String codePaths = TextUtils.join(";", allCodePaths); 8608 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8609 } catch (InstallerException e) { 8610 Slog.w(TAG, "Failed to dump profiles", e); 8611 } 8612 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8613 } 8614 } 8615 8616 @Override 8617 public void forceDexOpt(String packageName) { 8618 enforceSystemOrRoot("forceDexOpt"); 8619 8620 PackageParser.Package pkg; 8621 synchronized (mPackages) { 8622 pkg = mPackages.get(packageName); 8623 if (pkg == null) { 8624 throw new IllegalArgumentException("Unknown package: " + packageName); 8625 } 8626 } 8627 8628 synchronized (mInstallLock) { 8629 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8630 8631 // Whoever is calling forceDexOpt wants a fully compiled package. 8632 // Don't use profiles since that may cause compilation to be skipped. 8633 final int res = performDexOptInternalWithDependenciesLI(pkg, 8634 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8635 true /* force */); 8636 8637 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8638 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8639 throw new IllegalStateException("Failed to dexopt: " + res); 8640 } 8641 } 8642 } 8643 8644 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8645 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8646 Slog.w(TAG, "Unable to update from " + oldPkg.name 8647 + " to " + newPkg.packageName 8648 + ": old package not in system partition"); 8649 return false; 8650 } else if (mPackages.get(oldPkg.name) != null) { 8651 Slog.w(TAG, "Unable to update from " + oldPkg.name 8652 + " to " + newPkg.packageName 8653 + ": old package still exists"); 8654 return false; 8655 } 8656 return true; 8657 } 8658 8659 void removeCodePathLI(File codePath) { 8660 if (codePath.isDirectory()) { 8661 try { 8662 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8663 } catch (InstallerException e) { 8664 Slog.w(TAG, "Failed to remove code path", e); 8665 } 8666 } else { 8667 codePath.delete(); 8668 } 8669 } 8670 8671 private int[] resolveUserIds(int userId) { 8672 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8673 } 8674 8675 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8676 if (pkg == null) { 8677 Slog.wtf(TAG, "Package was null!", new Throwable()); 8678 return; 8679 } 8680 clearAppDataLeafLIF(pkg, userId, flags); 8681 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8682 for (int i = 0; i < childCount; i++) { 8683 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8684 } 8685 } 8686 8687 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8688 final PackageSetting ps; 8689 synchronized (mPackages) { 8690 ps = mSettings.mPackages.get(pkg.packageName); 8691 } 8692 for (int realUserId : resolveUserIds(userId)) { 8693 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8694 try { 8695 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8696 ceDataInode); 8697 } catch (InstallerException e) { 8698 Slog.w(TAG, String.valueOf(e)); 8699 } 8700 } 8701 } 8702 8703 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8704 if (pkg == null) { 8705 Slog.wtf(TAG, "Package was null!", new Throwable()); 8706 return; 8707 } 8708 destroyAppDataLeafLIF(pkg, userId, flags); 8709 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8710 for (int i = 0; i < childCount; i++) { 8711 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8712 } 8713 } 8714 8715 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8716 final PackageSetting ps; 8717 synchronized (mPackages) { 8718 ps = mSettings.mPackages.get(pkg.packageName); 8719 } 8720 for (int realUserId : resolveUserIds(userId)) { 8721 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8722 try { 8723 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8724 ceDataInode); 8725 } catch (InstallerException e) { 8726 Slog.w(TAG, String.valueOf(e)); 8727 } 8728 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8729 } 8730 } 8731 8732 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8733 if (pkg == null) { 8734 Slog.wtf(TAG, "Package was null!", new Throwable()); 8735 return; 8736 } 8737 destroyAppProfilesLeafLIF(pkg); 8738 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8739 for (int i = 0; i < childCount; i++) { 8740 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8741 } 8742 } 8743 8744 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8745 try { 8746 mInstaller.destroyAppProfiles(pkg.packageName); 8747 } catch (InstallerException e) { 8748 Slog.w(TAG, String.valueOf(e)); 8749 } 8750 } 8751 8752 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8753 if (pkg == null) { 8754 Slog.wtf(TAG, "Package was null!", new Throwable()); 8755 return; 8756 } 8757 clearAppProfilesLeafLIF(pkg); 8758 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8759 for (int i = 0; i < childCount; i++) { 8760 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8761 } 8762 } 8763 8764 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8765 try { 8766 mInstaller.clearAppProfiles(pkg.packageName); 8767 } catch (InstallerException e) { 8768 Slog.w(TAG, String.valueOf(e)); 8769 } 8770 } 8771 8772 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8773 long lastUpdateTime) { 8774 // Set parent install/update time 8775 PackageSetting ps = (PackageSetting) pkg.mExtras; 8776 if (ps != null) { 8777 ps.firstInstallTime = firstInstallTime; 8778 ps.lastUpdateTime = lastUpdateTime; 8779 } 8780 // Set children install/update time 8781 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8782 for (int i = 0; i < childCount; i++) { 8783 PackageParser.Package childPkg = pkg.childPackages.get(i); 8784 ps = (PackageSetting) childPkg.mExtras; 8785 if (ps != null) { 8786 ps.firstInstallTime = firstInstallTime; 8787 ps.lastUpdateTime = lastUpdateTime; 8788 } 8789 } 8790 } 8791 8792 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8793 PackageParser.Package changingLib) { 8794 if (file.path != null) { 8795 usesLibraryFiles.add(file.path); 8796 return; 8797 } 8798 PackageParser.Package p = mPackages.get(file.apk); 8799 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8800 // If we are doing this while in the middle of updating a library apk, 8801 // then we need to make sure to use that new apk for determining the 8802 // dependencies here. (We haven't yet finished committing the new apk 8803 // to the package manager state.) 8804 if (p == null || p.packageName.equals(changingLib.packageName)) { 8805 p = changingLib; 8806 } 8807 } 8808 if (p != null) { 8809 usesLibraryFiles.addAll(p.getAllCodePaths()); 8810 } 8811 } 8812 8813 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8814 PackageParser.Package changingLib) throws PackageManagerException { 8815 if (pkg == null) { 8816 return; 8817 } 8818 ArraySet<String> usesLibraryFiles = null; 8819 if (pkg.usesLibraries != null) { 8820 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8821 null, null, pkg.packageName, changingLib, true, null); 8822 } 8823 if (pkg.usesStaticLibraries != null) { 8824 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8825 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8826 pkg.packageName, changingLib, true, usesLibraryFiles); 8827 } 8828 if (pkg.usesOptionalLibraries != null) { 8829 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8830 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8831 } 8832 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8833 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8834 } else { 8835 pkg.usesLibraryFiles = null; 8836 } 8837 } 8838 8839 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8840 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8841 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8842 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8843 throws PackageManagerException { 8844 final int libCount = requestedLibraries.size(); 8845 for (int i = 0; i < libCount; i++) { 8846 final String libName = requestedLibraries.get(i); 8847 final int libVersion = requiredVersions != null ? requiredVersions[i] 8848 : SharedLibraryInfo.VERSION_UNDEFINED; 8849 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8850 if (libEntry == null) { 8851 if (required) { 8852 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8853 "Package " + packageName + " requires unavailable shared library " 8854 + libName + "; failing!"); 8855 } else { 8856 Slog.w(TAG, "Package " + packageName 8857 + " desires unavailable shared library " 8858 + libName + "; ignoring!"); 8859 } 8860 } else { 8861 if (requiredVersions != null && requiredCertDigests != null) { 8862 if (libEntry.info.getVersion() != requiredVersions[i]) { 8863 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8864 "Package " + packageName + " requires unavailable static shared" 8865 + " library " + libName + " version " 8866 + libEntry.info.getVersion() + "; failing!"); 8867 } 8868 8869 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8870 if (libPkg == null) { 8871 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8872 "Package " + packageName + " requires unavailable static shared" 8873 + " library; failing!"); 8874 } 8875 8876 String expectedCertDigest = requiredCertDigests[i]; 8877 String libCertDigest = PackageUtils.computeCertSha256Digest( 8878 libPkg.mSignatures[0]); 8879 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8880 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8881 "Package " + packageName + " requires differently signed" + 8882 " static shared library; failing!"); 8883 } 8884 } 8885 8886 if (outUsedLibraries == null) { 8887 outUsedLibraries = new ArraySet<>(); 8888 } 8889 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8890 } 8891 } 8892 return outUsedLibraries; 8893 } 8894 8895 private static boolean hasString(List<String> list, List<String> which) { 8896 if (list == null) { 8897 return false; 8898 } 8899 for (int i=list.size()-1; i>=0; i--) { 8900 for (int j=which.size()-1; j>=0; j--) { 8901 if (which.get(j).equals(list.get(i))) { 8902 return true; 8903 } 8904 } 8905 } 8906 return false; 8907 } 8908 8909 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8910 PackageParser.Package changingPkg) { 8911 ArrayList<PackageParser.Package> res = null; 8912 for (PackageParser.Package pkg : mPackages.values()) { 8913 if (changingPkg != null 8914 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 8915 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 8916 && !ArrayUtils.contains(pkg.usesStaticLibraries, 8917 changingPkg.staticSharedLibName)) { 8918 return null; 8919 } 8920 if (res == null) { 8921 res = new ArrayList<>(); 8922 } 8923 res.add(pkg); 8924 try { 8925 updateSharedLibrariesLPr(pkg, changingPkg); 8926 } catch (PackageManagerException e) { 8927 // If a system app update or an app and a required lib missing we 8928 // delete the package and for updated system apps keep the data as 8929 // it is better for the user to reinstall than to be in an limbo 8930 // state. Also libs disappearing under an app should never happen 8931 // - just in case. 8932 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 8933 final int flags = pkg.isUpdatedSystemApp() 8934 ? PackageManager.DELETE_KEEP_DATA : 0; 8935 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 8936 flags , null, true, null); 8937 } 8938 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8939 } 8940 } 8941 return res; 8942 } 8943 8944 /** 8945 * Derive the value of the {@code cpuAbiOverride} based on the provided 8946 * value and an optional stored value from the package settings. 8947 */ 8948 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8949 String cpuAbiOverride = null; 8950 8951 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8952 cpuAbiOverride = null; 8953 } else if (abiOverride != null) { 8954 cpuAbiOverride = abiOverride; 8955 } else if (settings != null) { 8956 cpuAbiOverride = settings.cpuAbiOverrideString; 8957 } 8958 8959 return cpuAbiOverride; 8960 } 8961 8962 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8963 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 8964 throws PackageManagerException { 8965 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8966 // If the package has children and this is the first dive in the function 8967 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8968 // whether all packages (parent and children) would be successfully scanned 8969 // before the actual scan since scanning mutates internal state and we want 8970 // to atomically install the package and its children. 8971 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8972 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8973 scanFlags |= SCAN_CHECK_ONLY; 8974 } 8975 } else { 8976 scanFlags &= ~SCAN_CHECK_ONLY; 8977 } 8978 8979 final PackageParser.Package scannedPkg; 8980 try { 8981 // Scan the parent 8982 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8983 // Scan the children 8984 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8985 for (int i = 0; i < childCount; i++) { 8986 PackageParser.Package childPkg = pkg.childPackages.get(i); 8987 scanPackageLI(childPkg, policyFlags, 8988 scanFlags, currentTime, user); 8989 } 8990 } finally { 8991 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8992 } 8993 8994 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8995 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8996 } 8997 8998 return scannedPkg; 8999 } 9000 9001 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9002 int scanFlags, long currentTime, @Nullable UserHandle user) 9003 throws PackageManagerException { 9004 boolean success = false; 9005 try { 9006 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9007 currentTime, user); 9008 success = true; 9009 return res; 9010 } finally { 9011 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9012 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9013 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9014 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9015 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9016 } 9017 } 9018 } 9019 9020 /** 9021 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9022 */ 9023 private static boolean apkHasCode(String fileName) { 9024 StrictJarFile jarFile = null; 9025 try { 9026 jarFile = new StrictJarFile(fileName, 9027 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9028 return jarFile.findEntry("classes.dex") != null; 9029 } catch (IOException ignore) { 9030 } finally { 9031 try { 9032 if (jarFile != null) { 9033 jarFile.close(); 9034 } 9035 } catch (IOException ignore) {} 9036 } 9037 return false; 9038 } 9039 9040 /** 9041 * Enforces code policy for the package. This ensures that if an APK has 9042 * declared hasCode="true" in its manifest that the APK actually contains 9043 * code. 9044 * 9045 * @throws PackageManagerException If bytecode could not be found when it should exist 9046 */ 9047 private static void assertCodePolicy(PackageParser.Package pkg) 9048 throws PackageManagerException { 9049 final boolean shouldHaveCode = 9050 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9051 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9052 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9053 "Package " + pkg.baseCodePath + " code is missing"); 9054 } 9055 9056 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9057 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9058 final boolean splitShouldHaveCode = 9059 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9060 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9061 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9062 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9063 } 9064 } 9065 } 9066 } 9067 9068 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9069 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9070 throws PackageManagerException { 9071 if (DEBUG_PACKAGE_SCANNING) { 9072 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9073 Log.d(TAG, "Scanning package " + pkg.packageName); 9074 } 9075 9076 applyPolicy(pkg, policyFlags); 9077 9078 assertPackageIsValid(pkg, policyFlags, scanFlags); 9079 9080 // Initialize package source and resource directories 9081 final File scanFile = new File(pkg.codePath); 9082 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9083 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9084 9085 SharedUserSetting suid = null; 9086 PackageSetting pkgSetting = null; 9087 9088 // Getting the package setting may have a side-effect, so if we 9089 // are only checking if scan would succeed, stash a copy of the 9090 // old setting to restore at the end. 9091 PackageSetting nonMutatedPs = null; 9092 9093 // We keep references to the derived CPU Abis from settings in oder to reuse 9094 // them in the case where we're not upgrading or booting for the first time. 9095 String primaryCpuAbiFromSettings = null; 9096 String secondaryCpuAbiFromSettings = null; 9097 9098 // writer 9099 synchronized (mPackages) { 9100 if (pkg.mSharedUserId != null) { 9101 // SIDE EFFECTS; may potentially allocate a new shared user 9102 suid = mSettings.getSharedUserLPw( 9103 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9104 if (DEBUG_PACKAGE_SCANNING) { 9105 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9106 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9107 + "): packages=" + suid.packages); 9108 } 9109 } 9110 9111 // Check if we are renaming from an original package name. 9112 PackageSetting origPackage = null; 9113 String realName = null; 9114 if (pkg.mOriginalPackages != null) { 9115 // This package may need to be renamed to a previously 9116 // installed name. Let's check on that... 9117 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9118 if (pkg.mOriginalPackages.contains(renamed)) { 9119 // This package had originally been installed as the 9120 // original name, and we have already taken care of 9121 // transitioning to the new one. Just update the new 9122 // one to continue using the old name. 9123 realName = pkg.mRealPackage; 9124 if (!pkg.packageName.equals(renamed)) { 9125 // Callers into this function may have already taken 9126 // care of renaming the package; only do it here if 9127 // it is not already done. 9128 pkg.setPackageName(renamed); 9129 } 9130 } else { 9131 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9132 if ((origPackage = mSettings.getPackageLPr( 9133 pkg.mOriginalPackages.get(i))) != null) { 9134 // We do have the package already installed under its 9135 // original name... should we use it? 9136 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9137 // New package is not compatible with original. 9138 origPackage = null; 9139 continue; 9140 } else if (origPackage.sharedUser != null) { 9141 // Make sure uid is compatible between packages. 9142 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9143 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9144 + " to " + pkg.packageName + ": old uid " 9145 + origPackage.sharedUser.name 9146 + " differs from " + pkg.mSharedUserId); 9147 origPackage = null; 9148 continue; 9149 } 9150 // TODO: Add case when shared user id is added [b/28144775] 9151 } else { 9152 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9153 + pkg.packageName + " to old name " + origPackage.name); 9154 } 9155 break; 9156 } 9157 } 9158 } 9159 } 9160 9161 if (mTransferedPackages.contains(pkg.packageName)) { 9162 Slog.w(TAG, "Package " + pkg.packageName 9163 + " was transferred to another, but its .apk remains"); 9164 } 9165 9166 // See comments in nonMutatedPs declaration 9167 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9168 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9169 if (foundPs != null) { 9170 nonMutatedPs = new PackageSetting(foundPs); 9171 } 9172 } 9173 9174 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9175 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9176 if (foundPs != null) { 9177 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9178 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9179 } 9180 } 9181 9182 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9183 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9184 PackageManagerService.reportSettingsProblem(Log.WARN, 9185 "Package " + pkg.packageName + " shared user changed from " 9186 + (pkgSetting.sharedUser != null 9187 ? pkgSetting.sharedUser.name : "<nothing>") 9188 + " to " 9189 + (suid != null ? suid.name : "<nothing>") 9190 + "; replacing with new"); 9191 pkgSetting = null; 9192 } 9193 final PackageSetting oldPkgSetting = 9194 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9195 final PackageSetting disabledPkgSetting = 9196 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9197 9198 String[] usesStaticLibraries = null; 9199 if (pkg.usesStaticLibraries != null) { 9200 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9201 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9202 } 9203 9204 if (pkgSetting == null) { 9205 final String parentPackageName = (pkg.parentPackage != null) 9206 ? pkg.parentPackage.packageName : null; 9207 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9208 // REMOVE SharedUserSetting from method; update in a separate call 9209 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9210 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9211 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9212 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9213 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9214 true /*allowInstall*/, instantApp, parentPackageName, 9215 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9216 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9217 // SIDE EFFECTS; updates system state; move elsewhere 9218 if (origPackage != null) { 9219 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9220 } 9221 mSettings.addUserToSettingLPw(pkgSetting); 9222 } else { 9223 // REMOVE SharedUserSetting from method; update in a separate call. 9224 // 9225 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9226 // secondaryCpuAbi are not known at this point so we always update them 9227 // to null here, only to reset them at a later point. 9228 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9229 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9230 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9231 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9232 UserManagerService.getInstance(), usesStaticLibraries, 9233 pkg.usesStaticLibrariesVersions); 9234 } 9235 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9236 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9237 9238 // SIDE EFFECTS; modifies system state; move elsewhere 9239 if (pkgSetting.origPackage != null) { 9240 // If we are first transitioning from an original package, 9241 // fix up the new package's name now. We need to do this after 9242 // looking up the package under its new name, so getPackageLP 9243 // can take care of fiddling things correctly. 9244 pkg.setPackageName(origPackage.name); 9245 9246 // File a report about this. 9247 String msg = "New package " + pkgSetting.realName 9248 + " renamed to replace old package " + pkgSetting.name; 9249 reportSettingsProblem(Log.WARN, msg); 9250 9251 // Make a note of it. 9252 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9253 mTransferedPackages.add(origPackage.name); 9254 } 9255 9256 // No longer need to retain this. 9257 pkgSetting.origPackage = null; 9258 } 9259 9260 // SIDE EFFECTS; modifies system state; move elsewhere 9261 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9262 // Make a note of it. 9263 mTransferedPackages.add(pkg.packageName); 9264 } 9265 9266 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9267 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9268 } 9269 9270 if ((scanFlags & SCAN_BOOTING) == 0 9271 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9272 // Check all shared libraries and map to their actual file path. 9273 // We only do this here for apps not on a system dir, because those 9274 // are the only ones that can fail an install due to this. We 9275 // will take care of the system apps by updating all of their 9276 // library paths after the scan is done. Also during the initial 9277 // scan don't update any libs as we do this wholesale after all 9278 // apps are scanned to avoid dependency based scanning. 9279 updateSharedLibrariesLPr(pkg, null); 9280 } 9281 9282 if (mFoundPolicyFile) { 9283 SELinuxMMAC.assignSeInfoValue(pkg); 9284 } 9285 pkg.applicationInfo.uid = pkgSetting.appId; 9286 pkg.mExtras = pkgSetting; 9287 9288 9289 // Static shared libs have same package with different versions where 9290 // we internally use a synthetic package name to allow multiple versions 9291 // of the same package, therefore we need to compare signatures against 9292 // the package setting for the latest library version. 9293 PackageSetting signatureCheckPs = pkgSetting; 9294 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9295 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9296 if (libraryEntry != null) { 9297 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9298 } 9299 } 9300 9301 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9302 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9303 // We just determined the app is signed correctly, so bring 9304 // over the latest parsed certs. 9305 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9306 } else { 9307 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9308 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9309 "Package " + pkg.packageName + " upgrade keys do not match the " 9310 + "previously installed version"); 9311 } else { 9312 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9313 String msg = "System package " + pkg.packageName 9314 + " signature changed; retaining data."; 9315 reportSettingsProblem(Log.WARN, msg); 9316 } 9317 } 9318 } else { 9319 try { 9320 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9321 verifySignaturesLP(signatureCheckPs, pkg); 9322 // We just determined the app is signed correctly, so bring 9323 // over the latest parsed certs. 9324 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9325 } catch (PackageManagerException e) { 9326 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9327 throw e; 9328 } 9329 // The signature has changed, but this package is in the system 9330 // image... let's recover! 9331 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9332 // However... if this package is part of a shared user, but it 9333 // doesn't match the signature of the shared user, let's fail. 9334 // What this means is that you can't change the signatures 9335 // associated with an overall shared user, which doesn't seem all 9336 // that unreasonable. 9337 if (signatureCheckPs.sharedUser != null) { 9338 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9339 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9340 throw new PackageManagerException( 9341 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9342 "Signature mismatch for shared user: " 9343 + pkgSetting.sharedUser); 9344 } 9345 } 9346 // File a report about this. 9347 String msg = "System package " + pkg.packageName 9348 + " signature changed; retaining data."; 9349 reportSettingsProblem(Log.WARN, msg); 9350 } 9351 } 9352 9353 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9354 // This package wants to adopt ownership of permissions from 9355 // another package. 9356 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9357 final String origName = pkg.mAdoptPermissions.get(i); 9358 final PackageSetting orig = mSettings.getPackageLPr(origName); 9359 if (orig != null) { 9360 if (verifyPackageUpdateLPr(orig, pkg)) { 9361 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9362 + pkg.packageName); 9363 // SIDE EFFECTS; updates permissions system state; move elsewhere 9364 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9365 } 9366 } 9367 } 9368 } 9369 } 9370 9371 pkg.applicationInfo.processName = fixProcessName( 9372 pkg.applicationInfo.packageName, 9373 pkg.applicationInfo.processName); 9374 9375 if (pkg != mPlatformPackage) { 9376 // Get all of our default paths setup 9377 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9378 } 9379 9380 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9381 9382 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9383 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9384 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9385 derivePackageAbi( 9386 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9388 9389 // Some system apps still use directory structure for native libraries 9390 // in which case we might end up not detecting abi solely based on apk 9391 // structure. Try to detect abi based on directory structure. 9392 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9393 pkg.applicationInfo.primaryCpuAbi == null) { 9394 setBundledAppAbisAndRoots(pkg, pkgSetting); 9395 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9396 } 9397 } else { 9398 // This is not a first boot or an upgrade, don't bother deriving the 9399 // ABI during the scan. Instead, trust the value that was stored in the 9400 // package setting. 9401 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9402 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9403 9404 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9405 9406 if (DEBUG_ABI_SELECTION) { 9407 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9408 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9409 pkg.applicationInfo.secondaryCpuAbi); 9410 } 9411 } 9412 } else { 9413 if ((scanFlags & SCAN_MOVE) != 0) { 9414 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9415 // but we already have this packages package info in the PackageSetting. We just 9416 // use that and derive the native library path based on the new codepath. 9417 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9418 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9419 } 9420 9421 // Set native library paths again. For moves, the path will be updated based on the 9422 // ABIs we've determined above. For non-moves, the path will be updated based on the 9423 // ABIs we determined during compilation, but the path will depend on the final 9424 // package path (after the rename away from the stage path). 9425 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9426 } 9427 9428 // This is a special case for the "system" package, where the ABI is 9429 // dictated by the zygote configuration (and init.rc). We should keep track 9430 // of this ABI so that we can deal with "normal" applications that run under 9431 // the same UID correctly. 9432 if (mPlatformPackage == pkg) { 9433 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9434 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9435 } 9436 9437 // If there's a mismatch between the abi-override in the package setting 9438 // and the abiOverride specified for the install. Warn about this because we 9439 // would've already compiled the app without taking the package setting into 9440 // account. 9441 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9442 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9443 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9444 " for package " + pkg.packageName); 9445 } 9446 } 9447 9448 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9449 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9450 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9451 9452 // Copy the derived override back to the parsed package, so that we can 9453 // update the package settings accordingly. 9454 pkg.cpuAbiOverride = cpuAbiOverride; 9455 9456 if (DEBUG_ABI_SELECTION) { 9457 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9458 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9459 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9460 } 9461 9462 // Push the derived path down into PackageSettings so we know what to 9463 // clean up at uninstall time. 9464 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9465 9466 if (DEBUG_ABI_SELECTION) { 9467 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9468 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9469 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9470 } 9471 9472 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9473 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9474 // We don't do this here during boot because we can do it all 9475 // at once after scanning all existing packages. 9476 // 9477 // We also do this *before* we perform dexopt on this package, so that 9478 // we can avoid redundant dexopts, and also to make sure we've got the 9479 // code and package path correct. 9480 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9481 } 9482 9483 if (mFactoryTest && pkg.requestedPermissions.contains( 9484 android.Manifest.permission.FACTORY_TEST)) { 9485 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9486 } 9487 9488 if (isSystemApp(pkg)) { 9489 pkgSetting.isOrphaned = true; 9490 } 9491 9492 // Take care of first install / last update times. 9493 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9494 if (currentTime != 0) { 9495 if (pkgSetting.firstInstallTime == 0) { 9496 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9497 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9498 pkgSetting.lastUpdateTime = currentTime; 9499 } 9500 } else if (pkgSetting.firstInstallTime == 0) { 9501 // We need *something*. Take time time stamp of the file. 9502 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9503 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9504 if (scanFileTime != pkgSetting.timeStamp) { 9505 // A package on the system image has changed; consider this 9506 // to be an update. 9507 pkgSetting.lastUpdateTime = scanFileTime; 9508 } 9509 } 9510 pkgSetting.setTimeStamp(scanFileTime); 9511 9512 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9513 if (nonMutatedPs != null) { 9514 synchronized (mPackages) { 9515 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9516 } 9517 } 9518 } else { 9519 final int userId = user == null ? 0 : user.getIdentifier(); 9520 // Modify state for the given package setting 9521 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9522 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9523 if (pkgSetting.getInstantApp(userId)) { 9524 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9525 } 9526 } 9527 return pkg; 9528 } 9529 9530 /** 9531 * Applies policy to the parsed package based upon the given policy flags. 9532 * Ensures the package is in a good state. 9533 * <p> 9534 * Implementation detail: This method must NOT have any side effect. It would 9535 * ideally be static, but, it requires locks to read system state. 9536 */ 9537 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9538 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9539 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9540 if (pkg.applicationInfo.isDirectBootAware()) { 9541 // we're direct boot aware; set for all components 9542 for (PackageParser.Service s : pkg.services) { 9543 s.info.encryptionAware = s.info.directBootAware = true; 9544 } 9545 for (PackageParser.Provider p : pkg.providers) { 9546 p.info.encryptionAware = p.info.directBootAware = true; 9547 } 9548 for (PackageParser.Activity a : pkg.activities) { 9549 a.info.encryptionAware = a.info.directBootAware = true; 9550 } 9551 for (PackageParser.Activity r : pkg.receivers) { 9552 r.info.encryptionAware = r.info.directBootAware = true; 9553 } 9554 } 9555 } else { 9556 // Only allow system apps to be flagged as core apps. 9557 pkg.coreApp = false; 9558 // clear flags not applicable to regular apps 9559 pkg.applicationInfo.privateFlags &= 9560 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9561 pkg.applicationInfo.privateFlags &= 9562 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9563 } 9564 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9565 9566 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9567 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9568 } 9569 9570 if (!isSystemApp(pkg)) { 9571 // Only system apps can use these features. 9572 pkg.mOriginalPackages = null; 9573 pkg.mRealPackage = null; 9574 pkg.mAdoptPermissions = null; 9575 } 9576 } 9577 9578 /** 9579 * Asserts the parsed package is valid according to the given policy. If the 9580 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9581 * <p> 9582 * Implementation detail: This method must NOT have any side effects. It would 9583 * ideally be static, but, it requires locks to read system state. 9584 * 9585 * @throws PackageManagerException If the package fails any of the validation checks 9586 */ 9587 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9588 throws PackageManagerException { 9589 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9590 assertCodePolicy(pkg); 9591 } 9592 9593 if (pkg.applicationInfo.getCodePath() == null || 9594 pkg.applicationInfo.getResourcePath() == null) { 9595 // Bail out. The resource and code paths haven't been set. 9596 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9597 "Code and resource paths haven't been set correctly"); 9598 } 9599 9600 // Make sure we're not adding any bogus keyset info 9601 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9602 ksms.assertScannedPackageValid(pkg); 9603 9604 synchronized (mPackages) { 9605 // The special "android" package can only be defined once 9606 if (pkg.packageName.equals("android")) { 9607 if (mAndroidApplication != null) { 9608 Slog.w(TAG, "*************************************************"); 9609 Slog.w(TAG, "Core android package being redefined. Skipping."); 9610 Slog.w(TAG, " codePath=" + pkg.codePath); 9611 Slog.w(TAG, "*************************************************"); 9612 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9613 "Core android package being redefined. Skipping."); 9614 } 9615 } 9616 9617 // A package name must be unique; don't allow duplicates 9618 if (mPackages.containsKey(pkg.packageName)) { 9619 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9620 "Application package " + pkg.packageName 9621 + " already installed. Skipping duplicate."); 9622 } 9623 9624 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9625 // Static libs have a synthetic package name containing the version 9626 // but we still want the base name to be unique. 9627 if (mPackages.containsKey(pkg.manifestPackageName)) { 9628 throw new PackageManagerException( 9629 "Duplicate static shared lib provider package"); 9630 } 9631 9632 // Static shared libraries should have at least O target SDK 9633 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9634 throw new PackageManagerException( 9635 "Packages declaring static-shared libs must target O SDK or higher"); 9636 } 9637 9638 // Package declaring static a shared lib cannot be instant apps 9639 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9640 throw new PackageManagerException( 9641 "Packages declaring static-shared libs cannot be instant apps"); 9642 } 9643 9644 // Package declaring static a shared lib cannot be renamed since the package 9645 // name is synthetic and apps can't code around package manager internals. 9646 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9647 throw new PackageManagerException( 9648 "Packages declaring static-shared libs cannot be renamed"); 9649 } 9650 9651 // Package declaring static a shared lib cannot declare child packages 9652 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9653 throw new PackageManagerException( 9654 "Packages declaring static-shared libs cannot have child packages"); 9655 } 9656 9657 // Package declaring static a shared lib cannot declare dynamic libs 9658 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9659 throw new PackageManagerException( 9660 "Packages declaring static-shared libs cannot declare dynamic libs"); 9661 } 9662 9663 // Package declaring static a shared lib cannot declare shared users 9664 if (pkg.mSharedUserId != null) { 9665 throw new PackageManagerException( 9666 "Packages declaring static-shared libs cannot declare shared users"); 9667 } 9668 9669 // Static shared libs cannot declare activities 9670 if (!pkg.activities.isEmpty()) { 9671 throw new PackageManagerException( 9672 "Static shared libs cannot declare activities"); 9673 } 9674 9675 // Static shared libs cannot declare services 9676 if (!pkg.services.isEmpty()) { 9677 throw new PackageManagerException( 9678 "Static shared libs cannot declare services"); 9679 } 9680 9681 // Static shared libs cannot declare providers 9682 if (!pkg.providers.isEmpty()) { 9683 throw new PackageManagerException( 9684 "Static shared libs cannot declare content providers"); 9685 } 9686 9687 // Static shared libs cannot declare receivers 9688 if (!pkg.receivers.isEmpty()) { 9689 throw new PackageManagerException( 9690 "Static shared libs cannot declare broadcast receivers"); 9691 } 9692 9693 // Static shared libs cannot declare permission groups 9694 if (!pkg.permissionGroups.isEmpty()) { 9695 throw new PackageManagerException( 9696 "Static shared libs cannot declare permission groups"); 9697 } 9698 9699 // Static shared libs cannot declare permissions 9700 if (!pkg.permissions.isEmpty()) { 9701 throw new PackageManagerException( 9702 "Static shared libs cannot declare permissions"); 9703 } 9704 9705 // Static shared libs cannot declare protected broadcasts 9706 if (pkg.protectedBroadcasts != null) { 9707 throw new PackageManagerException( 9708 "Static shared libs cannot declare protected broadcasts"); 9709 } 9710 9711 // Static shared libs cannot be overlay targets 9712 if (pkg.mOverlayTarget != null) { 9713 throw new PackageManagerException( 9714 "Static shared libs cannot be overlay targets"); 9715 } 9716 9717 // The version codes must be ordered as lib versions 9718 int minVersionCode = Integer.MIN_VALUE; 9719 int maxVersionCode = Integer.MAX_VALUE; 9720 9721 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9722 pkg.staticSharedLibName); 9723 if (versionedLib != null) { 9724 final int versionCount = versionedLib.size(); 9725 for (int i = 0; i < versionCount; i++) { 9726 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9727 // TODO: We will change version code to long, so in the new API it is long 9728 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9729 .getVersionCode(); 9730 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9731 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9732 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9733 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9734 } else { 9735 minVersionCode = maxVersionCode = libVersionCode; 9736 break; 9737 } 9738 } 9739 } 9740 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9741 throw new PackageManagerException("Static shared" 9742 + " lib version codes must be ordered as lib versions"); 9743 } 9744 } 9745 9746 // Only privileged apps and updated privileged apps can add child packages. 9747 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9748 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9749 throw new PackageManagerException("Only privileged apps can add child " 9750 + "packages. Ignoring package " + pkg.packageName); 9751 } 9752 final int childCount = pkg.childPackages.size(); 9753 for (int i = 0; i < childCount; i++) { 9754 PackageParser.Package childPkg = pkg.childPackages.get(i); 9755 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9756 childPkg.packageName)) { 9757 throw new PackageManagerException("Can't override child of " 9758 + "another disabled app. Ignoring package " + pkg.packageName); 9759 } 9760 } 9761 } 9762 9763 // If we're only installing presumed-existing packages, require that the 9764 // scanned APK is both already known and at the path previously established 9765 // for it. Previously unknown packages we pick up normally, but if we have an 9766 // a priori expectation about this package's install presence, enforce it. 9767 // With a singular exception for new system packages. When an OTA contains 9768 // a new system package, we allow the codepath to change from a system location 9769 // to the user-installed location. If we don't allow this change, any newer, 9770 // user-installed version of the application will be ignored. 9771 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9772 if (mExpectingBetter.containsKey(pkg.packageName)) { 9773 logCriticalInfo(Log.WARN, 9774 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9775 } else { 9776 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9777 if (known != null) { 9778 if (DEBUG_PACKAGE_SCANNING) { 9779 Log.d(TAG, "Examining " + pkg.codePath 9780 + " and requiring known paths " + known.codePathString 9781 + " & " + known.resourcePathString); 9782 } 9783 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9784 || !pkg.applicationInfo.getResourcePath().equals( 9785 known.resourcePathString)) { 9786 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9787 "Application package " + pkg.packageName 9788 + " found at " + pkg.applicationInfo.getCodePath() 9789 + " but expected at " + known.codePathString 9790 + "; ignoring."); 9791 } 9792 } 9793 } 9794 } 9795 9796 // Verify that this new package doesn't have any content providers 9797 // that conflict with existing packages. Only do this if the 9798 // package isn't already installed, since we don't want to break 9799 // things that are installed. 9800 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9801 final int N = pkg.providers.size(); 9802 int i; 9803 for (i=0; i<N; i++) { 9804 PackageParser.Provider p = pkg.providers.get(i); 9805 if (p.info.authority != null) { 9806 String names[] = p.info.authority.split(";"); 9807 for (int j = 0; j < names.length; j++) { 9808 if (mProvidersByAuthority.containsKey(names[j])) { 9809 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9810 final String otherPackageName = 9811 ((other != null && other.getComponentName() != null) ? 9812 other.getComponentName().getPackageName() : "?"); 9813 throw new PackageManagerException( 9814 INSTALL_FAILED_CONFLICTING_PROVIDER, 9815 "Can't install because provider name " + names[j] 9816 + " (in package " + pkg.applicationInfo.packageName 9817 + ") is already used by " + otherPackageName); 9818 } 9819 } 9820 } 9821 } 9822 } 9823 } 9824 } 9825 9826 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9827 int type, String declaringPackageName, int declaringVersionCode) { 9828 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9829 if (versionedLib == null) { 9830 versionedLib = new SparseArray<>(); 9831 mSharedLibraries.put(name, versionedLib); 9832 if (type == SharedLibraryInfo.TYPE_STATIC) { 9833 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9834 } 9835 } else if (versionedLib.indexOfKey(version) >= 0) { 9836 return false; 9837 } 9838 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9839 version, type, declaringPackageName, declaringVersionCode); 9840 versionedLib.put(version, libEntry); 9841 return true; 9842 } 9843 9844 private boolean removeSharedLibraryLPw(String name, int version) { 9845 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9846 if (versionedLib == null) { 9847 return false; 9848 } 9849 final int libIdx = versionedLib.indexOfKey(version); 9850 if (libIdx < 0) { 9851 return false; 9852 } 9853 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9854 versionedLib.remove(version); 9855 if (versionedLib.size() <= 0) { 9856 mSharedLibraries.remove(name); 9857 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9858 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9859 .getPackageName()); 9860 } 9861 } 9862 return true; 9863 } 9864 9865 /** 9866 * Adds a scanned package to the system. When this method is finished, the package will 9867 * be available for query, resolution, etc... 9868 */ 9869 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9870 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9871 final String pkgName = pkg.packageName; 9872 if (mCustomResolverComponentName != null && 9873 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9874 setUpCustomResolverActivity(pkg); 9875 } 9876 9877 if (pkg.packageName.equals("android")) { 9878 synchronized (mPackages) { 9879 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9880 // Set up information for our fall-back user intent resolution activity. 9881 mPlatformPackage = pkg; 9882 pkg.mVersionCode = mSdkVersion; 9883 mAndroidApplication = pkg.applicationInfo; 9884 if (!mResolverReplaced) { 9885 mResolveActivity.applicationInfo = mAndroidApplication; 9886 mResolveActivity.name = ResolverActivity.class.getName(); 9887 mResolveActivity.packageName = mAndroidApplication.packageName; 9888 mResolveActivity.processName = "system:ui"; 9889 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9890 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9891 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9892 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9893 mResolveActivity.exported = true; 9894 mResolveActivity.enabled = true; 9895 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9896 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 9897 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 9898 | ActivityInfo.CONFIG_SCREEN_LAYOUT 9899 | ActivityInfo.CONFIG_ORIENTATION 9900 | ActivityInfo.CONFIG_KEYBOARD 9901 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 9902 mResolveInfo.activityInfo = mResolveActivity; 9903 mResolveInfo.priority = 0; 9904 mResolveInfo.preferredOrder = 0; 9905 mResolveInfo.match = 0; 9906 mResolveComponentName = new ComponentName( 9907 mAndroidApplication.packageName, mResolveActivity.name); 9908 } 9909 } 9910 } 9911 } 9912 9913 ArrayList<PackageParser.Package> clientLibPkgs = null; 9914 // writer 9915 synchronized (mPackages) { 9916 boolean hasStaticSharedLibs = false; 9917 9918 // Any app can add new static shared libraries 9919 if (pkg.staticSharedLibName != null) { 9920 // Static shared libs don't allow renaming as they have synthetic package 9921 // names to allow install of multiple versions, so use name from manifest. 9922 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 9923 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 9924 pkg.manifestPackageName, pkg.mVersionCode)) { 9925 hasStaticSharedLibs = true; 9926 } else { 9927 Slog.w(TAG, "Package " + pkg.packageName + " library " 9928 + pkg.staticSharedLibName + " already exists; skipping"); 9929 } 9930 // Static shared libs cannot be updated once installed since they 9931 // use synthetic package name which includes the version code, so 9932 // not need to update other packages's shared lib dependencies. 9933 } 9934 9935 if (!hasStaticSharedLibs 9936 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 9937 // Only system apps can add new dynamic shared libraries. 9938 if (pkg.libraryNames != null) { 9939 for (int i = 0; i < pkg.libraryNames.size(); i++) { 9940 String name = pkg.libraryNames.get(i); 9941 boolean allowed = false; 9942 if (pkg.isUpdatedSystemApp()) { 9943 // New library entries can only be added through the 9944 // system image. This is important to get rid of a lot 9945 // of nasty edge cases: for example if we allowed a non- 9946 // system update of the app to add a library, then uninstalling 9947 // the update would make the library go away, and assumptions 9948 // we made such as through app install filtering would now 9949 // have allowed apps on the device which aren't compatible 9950 // with it. Better to just have the restriction here, be 9951 // conservative, and create many fewer cases that can negatively 9952 // impact the user experience. 9953 final PackageSetting sysPs = mSettings 9954 .getDisabledSystemPkgLPr(pkg.packageName); 9955 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 9956 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 9957 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 9958 allowed = true; 9959 break; 9960 } 9961 } 9962 } 9963 } else { 9964 allowed = true; 9965 } 9966 if (allowed) { 9967 if (!addSharedLibraryLPw(null, pkg.packageName, name, 9968 SharedLibraryInfo.VERSION_UNDEFINED, 9969 SharedLibraryInfo.TYPE_DYNAMIC, 9970 pkg.packageName, pkg.mVersionCode)) { 9971 Slog.w(TAG, "Package " + pkg.packageName + " library " 9972 + name + " already exists; skipping"); 9973 } 9974 } else { 9975 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 9976 + name + " that is not declared on system image; skipping"); 9977 } 9978 } 9979 9980 if ((scanFlags & SCAN_BOOTING) == 0) { 9981 // If we are not booting, we need to update any applications 9982 // that are clients of our shared library. If we are booting, 9983 // this will all be done once the scan is complete. 9984 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 9985 } 9986 } 9987 } 9988 } 9989 9990 if ((scanFlags & SCAN_BOOTING) != 0) { 9991 // No apps can run during boot scan, so they don't need to be frozen 9992 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 9993 // Caller asked to not kill app, so it's probably not frozen 9994 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 9995 // Caller asked us to ignore frozen check for some reason; they 9996 // probably didn't know the package name 9997 } else { 9998 // We're doing major surgery on this package, so it better be frozen 9999 // right now to keep it from launching 10000 checkPackageFrozen(pkgName); 10001 } 10002 10003 // Also need to kill any apps that are dependent on the library. 10004 if (clientLibPkgs != null) { 10005 for (int i=0; i<clientLibPkgs.size(); i++) { 10006 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10007 killApplication(clientPkg.applicationInfo.packageName, 10008 clientPkg.applicationInfo.uid, "update lib"); 10009 } 10010 } 10011 10012 // writer 10013 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10014 10015 synchronized (mPackages) { 10016 // We don't expect installation to fail beyond this point 10017 10018 // Add the new setting to mSettings 10019 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10020 // Add the new setting to mPackages 10021 mPackages.put(pkg.applicationInfo.packageName, pkg); 10022 // Make sure we don't accidentally delete its data. 10023 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10024 while (iter.hasNext()) { 10025 PackageCleanItem item = iter.next(); 10026 if (pkgName.equals(item.packageName)) { 10027 iter.remove(); 10028 } 10029 } 10030 10031 // Add the package's KeySets to the global KeySetManagerService 10032 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10033 ksms.addScannedPackageLPw(pkg); 10034 10035 int N = pkg.providers.size(); 10036 StringBuilder r = null; 10037 int i; 10038 for (i=0; i<N; i++) { 10039 PackageParser.Provider p = pkg.providers.get(i); 10040 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10041 p.info.processName); 10042 mProviders.addProvider(p); 10043 p.syncable = p.info.isSyncable; 10044 if (p.info.authority != null) { 10045 String names[] = p.info.authority.split(";"); 10046 p.info.authority = null; 10047 for (int j = 0; j < names.length; j++) { 10048 if (j == 1 && p.syncable) { 10049 // We only want the first authority for a provider to possibly be 10050 // syncable, so if we already added this provider using a different 10051 // authority clear the syncable flag. We copy the provider before 10052 // changing it because the mProviders object contains a reference 10053 // to a provider that we don't want to change. 10054 // Only do this for the second authority since the resulting provider 10055 // object can be the same for all future authorities for this provider. 10056 p = new PackageParser.Provider(p); 10057 p.syncable = false; 10058 } 10059 if (!mProvidersByAuthority.containsKey(names[j])) { 10060 mProvidersByAuthority.put(names[j], p); 10061 if (p.info.authority == null) { 10062 p.info.authority = names[j]; 10063 } else { 10064 p.info.authority = p.info.authority + ";" + names[j]; 10065 } 10066 if (DEBUG_PACKAGE_SCANNING) { 10067 if (chatty) 10068 Log.d(TAG, "Registered content provider: " + names[j] 10069 + ", className = " + p.info.name + ", isSyncable = " 10070 + p.info.isSyncable); 10071 } 10072 } else { 10073 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10074 Slog.w(TAG, "Skipping provider name " + names[j] + 10075 " (in package " + pkg.applicationInfo.packageName + 10076 "): name already used by " 10077 + ((other != null && other.getComponentName() != null) 10078 ? other.getComponentName().getPackageName() : "?")); 10079 } 10080 } 10081 } 10082 if (chatty) { 10083 if (r == null) { 10084 r = new StringBuilder(256); 10085 } else { 10086 r.append(' '); 10087 } 10088 r.append(p.info.name); 10089 } 10090 } 10091 if (r != null) { 10092 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10093 } 10094 10095 N = pkg.services.size(); 10096 r = null; 10097 for (i=0; i<N; i++) { 10098 PackageParser.Service s = pkg.services.get(i); 10099 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10100 s.info.processName); 10101 mServices.addService(s); 10102 if (chatty) { 10103 if (r == null) { 10104 r = new StringBuilder(256); 10105 } else { 10106 r.append(' '); 10107 } 10108 r.append(s.info.name); 10109 } 10110 } 10111 if (r != null) { 10112 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10113 } 10114 10115 N = pkg.receivers.size(); 10116 r = null; 10117 for (i=0; i<N; i++) { 10118 PackageParser.Activity a = pkg.receivers.get(i); 10119 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10120 a.info.processName); 10121 mReceivers.addActivity(a, "receiver"); 10122 if (chatty) { 10123 if (r == null) { 10124 r = new StringBuilder(256); 10125 } else { 10126 r.append(' '); 10127 } 10128 r.append(a.info.name); 10129 } 10130 } 10131 if (r != null) { 10132 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10133 } 10134 10135 N = pkg.activities.size(); 10136 r = null; 10137 for (i=0; i<N; i++) { 10138 PackageParser.Activity a = pkg.activities.get(i); 10139 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10140 a.info.processName); 10141 mActivities.addActivity(a, "activity"); 10142 if (chatty) { 10143 if (r == null) { 10144 r = new StringBuilder(256); 10145 } else { 10146 r.append(' '); 10147 } 10148 r.append(a.info.name); 10149 } 10150 } 10151 if (r != null) { 10152 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10153 } 10154 10155 N = pkg.permissionGroups.size(); 10156 r = null; 10157 for (i=0; i<N; i++) { 10158 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10159 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10160 final String curPackageName = cur == null ? null : cur.info.packageName; 10161 // Dont allow ephemeral apps to define new permission groups. 10162 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10163 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10164 + pg.info.packageName 10165 + " ignored: instant apps cannot define new permission groups."); 10166 continue; 10167 } 10168 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10169 if (cur == null || isPackageUpdate) { 10170 mPermissionGroups.put(pg.info.name, pg); 10171 if (chatty) { 10172 if (r == null) { 10173 r = new StringBuilder(256); 10174 } else { 10175 r.append(' '); 10176 } 10177 if (isPackageUpdate) { 10178 r.append("UPD:"); 10179 } 10180 r.append(pg.info.name); 10181 } 10182 } else { 10183 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10184 + pg.info.packageName + " ignored: original from " 10185 + cur.info.packageName); 10186 if (chatty) { 10187 if (r == null) { 10188 r = new StringBuilder(256); 10189 } else { 10190 r.append(' '); 10191 } 10192 r.append("DUP:"); 10193 r.append(pg.info.name); 10194 } 10195 } 10196 } 10197 if (r != null) { 10198 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10199 } 10200 10201 N = pkg.permissions.size(); 10202 r = null; 10203 for (i=0; i<N; i++) { 10204 PackageParser.Permission p = pkg.permissions.get(i); 10205 10206 // Dont allow ephemeral apps to define new permissions. 10207 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10208 Slog.w(TAG, "Permission " + p.info.name + " from package " 10209 + p.info.packageName 10210 + " ignored: instant apps cannot define new permissions."); 10211 continue; 10212 } 10213 10214 // Assume by default that we did not install this permission into the system. 10215 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10216 10217 // Now that permission groups have a special meaning, we ignore permission 10218 // groups for legacy apps to prevent unexpected behavior. In particular, 10219 // permissions for one app being granted to someone just becase they happen 10220 // to be in a group defined by another app (before this had no implications). 10221 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10222 p.group = mPermissionGroups.get(p.info.group); 10223 // Warn for a permission in an unknown group. 10224 if (p.info.group != null && p.group == null) { 10225 Slog.w(TAG, "Permission " + p.info.name + " from package " 10226 + p.info.packageName + " in an unknown group " + p.info.group); 10227 } 10228 } 10229 10230 ArrayMap<String, BasePermission> permissionMap = 10231 p.tree ? mSettings.mPermissionTrees 10232 : mSettings.mPermissions; 10233 BasePermission bp = permissionMap.get(p.info.name); 10234 10235 // Allow system apps to redefine non-system permissions 10236 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10237 final boolean currentOwnerIsSystem = (bp.perm != null 10238 && isSystemApp(bp.perm.owner)); 10239 if (isSystemApp(p.owner)) { 10240 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10241 // It's a built-in permission and no owner, take ownership now 10242 bp.packageSetting = pkgSetting; 10243 bp.perm = p; 10244 bp.uid = pkg.applicationInfo.uid; 10245 bp.sourcePackage = p.info.packageName; 10246 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10247 } else if (!currentOwnerIsSystem) { 10248 String msg = "New decl " + p.owner + " of permission " 10249 + p.info.name + " is system; overriding " + bp.sourcePackage; 10250 reportSettingsProblem(Log.WARN, msg); 10251 bp = null; 10252 } 10253 } 10254 } 10255 10256 if (bp == null) { 10257 bp = new BasePermission(p.info.name, p.info.packageName, 10258 BasePermission.TYPE_NORMAL); 10259 permissionMap.put(p.info.name, bp); 10260 } 10261 10262 if (bp.perm == null) { 10263 if (bp.sourcePackage == null 10264 || bp.sourcePackage.equals(p.info.packageName)) { 10265 BasePermission tree = findPermissionTreeLP(p.info.name); 10266 if (tree == null 10267 || tree.sourcePackage.equals(p.info.packageName)) { 10268 bp.packageSetting = pkgSetting; 10269 bp.perm = p; 10270 bp.uid = pkg.applicationInfo.uid; 10271 bp.sourcePackage = p.info.packageName; 10272 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10273 if (chatty) { 10274 if (r == null) { 10275 r = new StringBuilder(256); 10276 } else { 10277 r.append(' '); 10278 } 10279 r.append(p.info.name); 10280 } 10281 } else { 10282 Slog.w(TAG, "Permission " + p.info.name + " from package " 10283 + p.info.packageName + " ignored: base tree " 10284 + tree.name + " is from package " 10285 + tree.sourcePackage); 10286 } 10287 } else { 10288 Slog.w(TAG, "Permission " + p.info.name + " from package " 10289 + p.info.packageName + " ignored: original from " 10290 + bp.sourcePackage); 10291 } 10292 } else if (chatty) { 10293 if (r == null) { 10294 r = new StringBuilder(256); 10295 } else { 10296 r.append(' '); 10297 } 10298 r.append("DUP:"); 10299 r.append(p.info.name); 10300 } 10301 if (bp.perm == p) { 10302 bp.protectionLevel = p.info.protectionLevel; 10303 } 10304 } 10305 10306 if (r != null) { 10307 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10308 } 10309 10310 N = pkg.instrumentation.size(); 10311 r = null; 10312 for (i=0; i<N; i++) { 10313 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10314 a.info.packageName = pkg.applicationInfo.packageName; 10315 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10316 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10317 a.info.splitNames = pkg.splitNames; 10318 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10319 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10320 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10321 a.info.dataDir = pkg.applicationInfo.dataDir; 10322 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10323 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10324 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10325 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10326 mInstrumentation.put(a.getComponentName(), a); 10327 if (chatty) { 10328 if (r == null) { 10329 r = new StringBuilder(256); 10330 } else { 10331 r.append(' '); 10332 } 10333 r.append(a.info.name); 10334 } 10335 } 10336 if (r != null) { 10337 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10338 } 10339 10340 if (pkg.protectedBroadcasts != null) { 10341 N = pkg.protectedBroadcasts.size(); 10342 for (i=0; i<N; i++) { 10343 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10344 } 10345 } 10346 } 10347 10348 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10349 } 10350 10351 /** 10352 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10353 * is derived purely on the basis of the contents of {@code scanFile} and 10354 * {@code cpuAbiOverride}. 10355 * 10356 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10357 */ 10358 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10359 String cpuAbiOverride, boolean extractLibs, 10360 File appLib32InstallDir) 10361 throws PackageManagerException { 10362 // Give ourselves some initial paths; we'll come back for another 10363 // pass once we've determined ABI below. 10364 setNativeLibraryPaths(pkg, appLib32InstallDir); 10365 10366 // We would never need to extract libs for forward-locked and external packages, 10367 // since the container service will do it for us. We shouldn't attempt to 10368 // extract libs from system app when it was not updated. 10369 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10370 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10371 extractLibs = false; 10372 } 10373 10374 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10375 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10376 10377 NativeLibraryHelper.Handle handle = null; 10378 try { 10379 handle = NativeLibraryHelper.Handle.create(pkg); 10380 // TODO(multiArch): This can be null for apps that didn't go through the 10381 // usual installation process. We can calculate it again, like we 10382 // do during install time. 10383 // 10384 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10385 // unnecessary. 10386 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10387 10388 // Null out the abis so that they can be recalculated. 10389 pkg.applicationInfo.primaryCpuAbi = null; 10390 pkg.applicationInfo.secondaryCpuAbi = null; 10391 if (isMultiArch(pkg.applicationInfo)) { 10392 // Warn if we've set an abiOverride for multi-lib packages.. 10393 // By definition, we need to copy both 32 and 64 bit libraries for 10394 // such packages. 10395 if (pkg.cpuAbiOverride != null 10396 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10397 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10398 } 10399 10400 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10401 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10402 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10403 if (extractLibs) { 10404 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10405 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10406 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10407 useIsaSpecificSubdirs); 10408 } else { 10409 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10410 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10411 } 10412 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10413 } 10414 10415 maybeThrowExceptionForMultiArchCopy( 10416 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10417 10418 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10419 if (extractLibs) { 10420 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10421 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10422 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10423 useIsaSpecificSubdirs); 10424 } else { 10425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10426 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10427 } 10428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10429 } 10430 10431 maybeThrowExceptionForMultiArchCopy( 10432 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10433 10434 if (abi64 >= 0) { 10435 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10436 } 10437 10438 if (abi32 >= 0) { 10439 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10440 if (abi64 >= 0) { 10441 if (pkg.use32bitAbi) { 10442 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10443 pkg.applicationInfo.primaryCpuAbi = abi; 10444 } else { 10445 pkg.applicationInfo.secondaryCpuAbi = abi; 10446 } 10447 } else { 10448 pkg.applicationInfo.primaryCpuAbi = abi; 10449 } 10450 } 10451 10452 } else { 10453 String[] abiList = (cpuAbiOverride != null) ? 10454 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10455 10456 // Enable gross and lame hacks for apps that are built with old 10457 // SDK tools. We must scan their APKs for renderscript bitcode and 10458 // not launch them if it's present. Don't bother checking on devices 10459 // that don't have 64 bit support. 10460 boolean needsRenderScriptOverride = false; 10461 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10462 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10463 abiList = Build.SUPPORTED_32_BIT_ABIS; 10464 needsRenderScriptOverride = true; 10465 } 10466 10467 final int copyRet; 10468 if (extractLibs) { 10469 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10470 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10471 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10472 } else { 10473 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10474 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10475 } 10476 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10477 10478 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10479 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10480 "Error unpackaging native libs for app, errorCode=" + copyRet); 10481 } 10482 10483 if (copyRet >= 0) { 10484 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10485 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10486 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10487 } else if (needsRenderScriptOverride) { 10488 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10489 } 10490 } 10491 } catch (IOException ioe) { 10492 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10493 } finally { 10494 IoUtils.closeQuietly(handle); 10495 } 10496 10497 // Now that we've calculated the ABIs and determined if it's an internal app, 10498 // we will go ahead and populate the nativeLibraryPath. 10499 setNativeLibraryPaths(pkg, appLib32InstallDir); 10500 } 10501 10502 /** 10503 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10504 * i.e, so that all packages can be run inside a single process if required. 10505 * 10506 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10507 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10508 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10509 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10510 * updating a package that belongs to a shared user. 10511 * 10512 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10513 * adds unnecessary complexity. 10514 */ 10515 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10516 PackageParser.Package scannedPackage) { 10517 String requiredInstructionSet = null; 10518 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10519 requiredInstructionSet = VMRuntime.getInstructionSet( 10520 scannedPackage.applicationInfo.primaryCpuAbi); 10521 } 10522 10523 PackageSetting requirer = null; 10524 for (PackageSetting ps : packagesForUser) { 10525 // If packagesForUser contains scannedPackage, we skip it. This will happen 10526 // when scannedPackage is an update of an existing package. Without this check, 10527 // we will never be able to change the ABI of any package belonging to a shared 10528 // user, even if it's compatible with other packages. 10529 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10530 if (ps.primaryCpuAbiString == null) { 10531 continue; 10532 } 10533 10534 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10535 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10536 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10537 // this but there's not much we can do. 10538 String errorMessage = "Instruction set mismatch, " 10539 + ((requirer == null) ? "[caller]" : requirer) 10540 + " requires " + requiredInstructionSet + " whereas " + ps 10541 + " requires " + instructionSet; 10542 Slog.w(TAG, errorMessage); 10543 } 10544 10545 if (requiredInstructionSet == null) { 10546 requiredInstructionSet = instructionSet; 10547 requirer = ps; 10548 } 10549 } 10550 } 10551 10552 if (requiredInstructionSet != null) { 10553 String adjustedAbi; 10554 if (requirer != null) { 10555 // requirer != null implies that either scannedPackage was null or that scannedPackage 10556 // did not require an ABI, in which case we have to adjust scannedPackage to match 10557 // the ABI of the set (which is the same as requirer's ABI) 10558 adjustedAbi = requirer.primaryCpuAbiString; 10559 if (scannedPackage != null) { 10560 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10561 } 10562 } else { 10563 // requirer == null implies that we're updating all ABIs in the set to 10564 // match scannedPackage. 10565 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10566 } 10567 10568 for (PackageSetting ps : packagesForUser) { 10569 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10570 if (ps.primaryCpuAbiString != null) { 10571 continue; 10572 } 10573 10574 ps.primaryCpuAbiString = adjustedAbi; 10575 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10576 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10577 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10578 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10579 + " (requirer=" 10580 + (requirer != null ? requirer.pkg : "null") 10581 + ", scannedPackage=" 10582 + (scannedPackage != null ? scannedPackage : "null") 10583 + ")"); 10584 try { 10585 mInstaller.rmdex(ps.codePathString, 10586 getDexCodeInstructionSet(getPreferredInstructionSet())); 10587 } catch (InstallerException ignored) { 10588 } 10589 } 10590 } 10591 } 10592 } 10593 } 10594 10595 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10596 synchronized (mPackages) { 10597 mResolverReplaced = true; 10598 // Set up information for custom user intent resolution activity. 10599 mResolveActivity.applicationInfo = pkg.applicationInfo; 10600 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10601 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10602 mResolveActivity.processName = pkg.applicationInfo.packageName; 10603 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10604 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10605 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10606 mResolveActivity.theme = 0; 10607 mResolveActivity.exported = true; 10608 mResolveActivity.enabled = true; 10609 mResolveInfo.activityInfo = mResolveActivity; 10610 mResolveInfo.priority = 0; 10611 mResolveInfo.preferredOrder = 0; 10612 mResolveInfo.match = 0; 10613 mResolveComponentName = mCustomResolverComponentName; 10614 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10615 mResolveComponentName); 10616 } 10617 } 10618 10619 private void setUpInstantAppInstallerActivityLP(ComponentName installerComponent) { 10620 if (installerComponent == null) { 10621 if (DEBUG_EPHEMERAL) { 10622 Slog.d(TAG, "Clear ephemeral installer activity"); 10623 } 10624 mInstantAppInstallerActivity.applicationInfo = null; 10625 return; 10626 } 10627 10628 if (DEBUG_EPHEMERAL) { 10629 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 10630 } 10631 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 10632 // Set up information for ephemeral installer activity 10633 mInstantAppInstallerActivity.applicationInfo = pkg.applicationInfo; 10634 mInstantAppInstallerActivity.name = installerComponent.getClassName(); 10635 mInstantAppInstallerActivity.packageName = pkg.applicationInfo.packageName; 10636 mInstantAppInstallerActivity.processName = pkg.applicationInfo.packageName; 10637 mInstantAppInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10638 mInstantAppInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10639 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10640 mInstantAppInstallerActivity.theme = 0; 10641 mInstantAppInstallerActivity.exported = true; 10642 mInstantAppInstallerActivity.enabled = true; 10643 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10644 mInstantAppInstallerInfo.priority = 0; 10645 mInstantAppInstallerInfo.preferredOrder = 1; 10646 mInstantAppInstallerInfo.isDefault = true; 10647 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10648 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10649 } 10650 10651 private static String calculateBundledApkRoot(final String codePathString) { 10652 final File codePath = new File(codePathString); 10653 final File codeRoot; 10654 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10655 codeRoot = Environment.getRootDirectory(); 10656 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10657 codeRoot = Environment.getOemDirectory(); 10658 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10659 codeRoot = Environment.getVendorDirectory(); 10660 } else { 10661 // Unrecognized code path; take its top real segment as the apk root: 10662 // e.g. /something/app/blah.apk => /something 10663 try { 10664 File f = codePath.getCanonicalFile(); 10665 File parent = f.getParentFile(); // non-null because codePath is a file 10666 File tmp; 10667 while ((tmp = parent.getParentFile()) != null) { 10668 f = parent; 10669 parent = tmp; 10670 } 10671 codeRoot = f; 10672 Slog.w(TAG, "Unrecognized code path " 10673 + codePath + " - using " + codeRoot); 10674 } catch (IOException e) { 10675 // Can't canonicalize the code path -- shenanigans? 10676 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10677 return Environment.getRootDirectory().getPath(); 10678 } 10679 } 10680 return codeRoot.getPath(); 10681 } 10682 10683 /** 10684 * Derive and set the location of native libraries for the given package, 10685 * which varies depending on where and how the package was installed. 10686 */ 10687 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10688 final ApplicationInfo info = pkg.applicationInfo; 10689 final String codePath = pkg.codePath; 10690 final File codeFile = new File(codePath); 10691 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10692 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10693 10694 info.nativeLibraryRootDir = null; 10695 info.nativeLibraryRootRequiresIsa = false; 10696 info.nativeLibraryDir = null; 10697 info.secondaryNativeLibraryDir = null; 10698 10699 if (isApkFile(codeFile)) { 10700 // Monolithic install 10701 if (bundledApp) { 10702 // If "/system/lib64/apkname" exists, assume that is the per-package 10703 // native library directory to use; otherwise use "/system/lib/apkname". 10704 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10705 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10706 getPrimaryInstructionSet(info)); 10707 10708 // This is a bundled system app so choose the path based on the ABI. 10709 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10710 // is just the default path. 10711 final String apkName = deriveCodePathName(codePath); 10712 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10713 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10714 apkName).getAbsolutePath(); 10715 10716 if (info.secondaryCpuAbi != null) { 10717 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10718 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10719 secondaryLibDir, apkName).getAbsolutePath(); 10720 } 10721 } else if (asecApp) { 10722 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10723 .getAbsolutePath(); 10724 } else { 10725 final String apkName = deriveCodePathName(codePath); 10726 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10727 .getAbsolutePath(); 10728 } 10729 10730 info.nativeLibraryRootRequiresIsa = false; 10731 info.nativeLibraryDir = info.nativeLibraryRootDir; 10732 } else { 10733 // Cluster install 10734 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10735 info.nativeLibraryRootRequiresIsa = true; 10736 10737 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10738 getPrimaryInstructionSet(info)).getAbsolutePath(); 10739 10740 if (info.secondaryCpuAbi != null) { 10741 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10742 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10743 } 10744 } 10745 } 10746 10747 /** 10748 * Calculate the abis and roots for a bundled app. These can uniquely 10749 * be determined from the contents of the system partition, i.e whether 10750 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10751 * of this information, and instead assume that the system was built 10752 * sensibly. 10753 */ 10754 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10755 PackageSetting pkgSetting) { 10756 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10757 10758 // If "/system/lib64/apkname" exists, assume that is the per-package 10759 // native library directory to use; otherwise use "/system/lib/apkname". 10760 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10761 setBundledAppAbi(pkg, apkRoot, apkName); 10762 // pkgSetting might be null during rescan following uninstall of updates 10763 // to a bundled app, so accommodate that possibility. The settings in 10764 // that case will be established later from the parsed package. 10765 // 10766 // If the settings aren't null, sync them up with what we've just derived. 10767 // note that apkRoot isn't stored in the package settings. 10768 if (pkgSetting != null) { 10769 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10770 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10771 } 10772 } 10773 10774 /** 10775 * Deduces the ABI of a bundled app and sets the relevant fields on the 10776 * parsed pkg object. 10777 * 10778 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10779 * under which system libraries are installed. 10780 * @param apkName the name of the installed package. 10781 */ 10782 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10783 final File codeFile = new File(pkg.codePath); 10784 10785 final boolean has64BitLibs; 10786 final boolean has32BitLibs; 10787 if (isApkFile(codeFile)) { 10788 // Monolithic install 10789 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10790 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10791 } else { 10792 // Cluster install 10793 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10794 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10795 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10796 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10797 has64BitLibs = (new File(rootDir, isa)).exists(); 10798 } else { 10799 has64BitLibs = false; 10800 } 10801 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10802 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10803 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10804 has32BitLibs = (new File(rootDir, isa)).exists(); 10805 } else { 10806 has32BitLibs = false; 10807 } 10808 } 10809 10810 if (has64BitLibs && !has32BitLibs) { 10811 // The package has 64 bit libs, but not 32 bit libs. Its primary 10812 // ABI should be 64 bit. We can safely assume here that the bundled 10813 // native libraries correspond to the most preferred ABI in the list. 10814 10815 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10816 pkg.applicationInfo.secondaryCpuAbi = null; 10817 } else if (has32BitLibs && !has64BitLibs) { 10818 // The package has 32 bit libs but not 64 bit libs. Its primary 10819 // ABI should be 32 bit. 10820 10821 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10822 pkg.applicationInfo.secondaryCpuAbi = null; 10823 } else if (has32BitLibs && has64BitLibs) { 10824 // The application has both 64 and 32 bit bundled libraries. We check 10825 // here that the app declares multiArch support, and warn if it doesn't. 10826 // 10827 // We will be lenient here and record both ABIs. The primary will be the 10828 // ABI that's higher on the list, i.e, a device that's configured to prefer 10829 // 64 bit apps will see a 64 bit primary ABI, 10830 10831 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10832 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10833 } 10834 10835 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10836 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10837 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10838 } else { 10839 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10840 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10841 } 10842 } else { 10843 pkg.applicationInfo.primaryCpuAbi = null; 10844 pkg.applicationInfo.secondaryCpuAbi = null; 10845 } 10846 } 10847 10848 private void killApplication(String pkgName, int appId, String reason) { 10849 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10850 } 10851 10852 private void killApplication(String pkgName, int appId, int userId, String reason) { 10853 // Request the ActivityManager to kill the process(only for existing packages) 10854 // so that we do not end up in a confused state while the user is still using the older 10855 // version of the application while the new one gets installed. 10856 final long token = Binder.clearCallingIdentity(); 10857 try { 10858 IActivityManager am = ActivityManager.getService(); 10859 if (am != null) { 10860 try { 10861 am.killApplication(pkgName, appId, userId, reason); 10862 } catch (RemoteException e) { 10863 } 10864 } 10865 } finally { 10866 Binder.restoreCallingIdentity(token); 10867 } 10868 } 10869 10870 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10871 // Remove the parent package setting 10872 PackageSetting ps = (PackageSetting) pkg.mExtras; 10873 if (ps != null) { 10874 removePackageLI(ps, chatty); 10875 } 10876 // Remove the child package setting 10877 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10878 for (int i = 0; i < childCount; i++) { 10879 PackageParser.Package childPkg = pkg.childPackages.get(i); 10880 ps = (PackageSetting) childPkg.mExtras; 10881 if (ps != null) { 10882 removePackageLI(ps, chatty); 10883 } 10884 } 10885 } 10886 10887 void removePackageLI(PackageSetting ps, boolean chatty) { 10888 if (DEBUG_INSTALL) { 10889 if (chatty) 10890 Log.d(TAG, "Removing package " + ps.name); 10891 } 10892 10893 // writer 10894 synchronized (mPackages) { 10895 mPackages.remove(ps.name); 10896 final PackageParser.Package pkg = ps.pkg; 10897 if (pkg != null) { 10898 cleanPackageDataStructuresLILPw(pkg, chatty); 10899 } 10900 } 10901 } 10902 10903 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 10904 if (DEBUG_INSTALL) { 10905 if (chatty) 10906 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 10907 } 10908 10909 // writer 10910 synchronized (mPackages) { 10911 // Remove the parent package 10912 mPackages.remove(pkg.applicationInfo.packageName); 10913 cleanPackageDataStructuresLILPw(pkg, chatty); 10914 10915 // Remove the child packages 10916 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10917 for (int i = 0; i < childCount; i++) { 10918 PackageParser.Package childPkg = pkg.childPackages.get(i); 10919 mPackages.remove(childPkg.applicationInfo.packageName); 10920 cleanPackageDataStructuresLILPw(childPkg, chatty); 10921 } 10922 } 10923 } 10924 10925 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 10926 int N = pkg.providers.size(); 10927 StringBuilder r = null; 10928 int i; 10929 for (i=0; i<N; i++) { 10930 PackageParser.Provider p = pkg.providers.get(i); 10931 mProviders.removeProvider(p); 10932 if (p.info.authority == null) { 10933 10934 /* There was another ContentProvider with this authority when 10935 * this app was installed so this authority is null, 10936 * Ignore it as we don't have to unregister the provider. 10937 */ 10938 continue; 10939 } 10940 String names[] = p.info.authority.split(";"); 10941 for (int j = 0; j < names.length; j++) { 10942 if (mProvidersByAuthority.get(names[j]) == p) { 10943 mProvidersByAuthority.remove(names[j]); 10944 if (DEBUG_REMOVE) { 10945 if (chatty) 10946 Log.d(TAG, "Unregistered content provider: " + names[j] 10947 + ", className = " + p.info.name + ", isSyncable = " 10948 + p.info.isSyncable); 10949 } 10950 } 10951 } 10952 if (DEBUG_REMOVE && chatty) { 10953 if (r == null) { 10954 r = new StringBuilder(256); 10955 } else { 10956 r.append(' '); 10957 } 10958 r.append(p.info.name); 10959 } 10960 } 10961 if (r != null) { 10962 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 10963 } 10964 10965 N = pkg.services.size(); 10966 r = null; 10967 for (i=0; i<N; i++) { 10968 PackageParser.Service s = pkg.services.get(i); 10969 mServices.removeService(s); 10970 if (chatty) { 10971 if (r == null) { 10972 r = new StringBuilder(256); 10973 } else { 10974 r.append(' '); 10975 } 10976 r.append(s.info.name); 10977 } 10978 } 10979 if (r != null) { 10980 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10981 } 10982 10983 N = pkg.receivers.size(); 10984 r = null; 10985 for (i=0; i<N; i++) { 10986 PackageParser.Activity a = pkg.receivers.get(i); 10987 mReceivers.removeActivity(a, "receiver"); 10988 if (DEBUG_REMOVE && chatty) { 10989 if (r == null) { 10990 r = new StringBuilder(256); 10991 } else { 10992 r.append(' '); 10993 } 10994 r.append(a.info.name); 10995 } 10996 } 10997 if (r != null) { 10998 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10999 } 11000 11001 N = pkg.activities.size(); 11002 r = null; 11003 for (i=0; i<N; i++) { 11004 PackageParser.Activity a = pkg.activities.get(i); 11005 mActivities.removeActivity(a, "activity"); 11006 if (DEBUG_REMOVE && chatty) { 11007 if (r == null) { 11008 r = new StringBuilder(256); 11009 } else { 11010 r.append(' '); 11011 } 11012 r.append(a.info.name); 11013 } 11014 } 11015 if (r != null) { 11016 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11017 } 11018 11019 N = pkg.permissions.size(); 11020 r = null; 11021 for (i=0; i<N; i++) { 11022 PackageParser.Permission p = pkg.permissions.get(i); 11023 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11024 if (bp == null) { 11025 bp = mSettings.mPermissionTrees.get(p.info.name); 11026 } 11027 if (bp != null && bp.perm == p) { 11028 bp.perm = null; 11029 if (DEBUG_REMOVE && chatty) { 11030 if (r == null) { 11031 r = new StringBuilder(256); 11032 } else { 11033 r.append(' '); 11034 } 11035 r.append(p.info.name); 11036 } 11037 } 11038 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11039 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11040 if (appOpPkgs != null) { 11041 appOpPkgs.remove(pkg.packageName); 11042 } 11043 } 11044 } 11045 if (r != null) { 11046 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11047 } 11048 11049 N = pkg.requestedPermissions.size(); 11050 r = null; 11051 for (i=0; i<N; i++) { 11052 String perm = pkg.requestedPermissions.get(i); 11053 BasePermission bp = mSettings.mPermissions.get(perm); 11054 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11055 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11056 if (appOpPkgs != null) { 11057 appOpPkgs.remove(pkg.packageName); 11058 if (appOpPkgs.isEmpty()) { 11059 mAppOpPermissionPackages.remove(perm); 11060 } 11061 } 11062 } 11063 } 11064 if (r != null) { 11065 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11066 } 11067 11068 N = pkg.instrumentation.size(); 11069 r = null; 11070 for (i=0; i<N; i++) { 11071 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11072 mInstrumentation.remove(a.getComponentName()); 11073 if (DEBUG_REMOVE && chatty) { 11074 if (r == null) { 11075 r = new StringBuilder(256); 11076 } else { 11077 r.append(' '); 11078 } 11079 r.append(a.info.name); 11080 } 11081 } 11082 if (r != null) { 11083 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11084 } 11085 11086 r = null; 11087 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11088 // Only system apps can hold shared libraries. 11089 if (pkg.libraryNames != null) { 11090 for (i = 0; i < pkg.libraryNames.size(); i++) { 11091 String name = pkg.libraryNames.get(i); 11092 if (removeSharedLibraryLPw(name, 0)) { 11093 if (DEBUG_REMOVE && chatty) { 11094 if (r == null) { 11095 r = new StringBuilder(256); 11096 } else { 11097 r.append(' '); 11098 } 11099 r.append(name); 11100 } 11101 } 11102 } 11103 } 11104 } 11105 11106 r = null; 11107 11108 // Any package can hold static shared libraries. 11109 if (pkg.staticSharedLibName != null) { 11110 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11111 if (DEBUG_REMOVE && chatty) { 11112 if (r == null) { 11113 r = new StringBuilder(256); 11114 } else { 11115 r.append(' '); 11116 } 11117 r.append(pkg.staticSharedLibName); 11118 } 11119 } 11120 } 11121 11122 if (r != null) { 11123 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11124 } 11125 } 11126 11127 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11128 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11129 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11130 return true; 11131 } 11132 } 11133 return false; 11134 } 11135 11136 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11137 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11138 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11139 11140 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11141 // Update the parent permissions 11142 updatePermissionsLPw(pkg.packageName, pkg, flags); 11143 // Update the child permissions 11144 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11145 for (int i = 0; i < childCount; i++) { 11146 PackageParser.Package childPkg = pkg.childPackages.get(i); 11147 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11148 } 11149 } 11150 11151 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11152 int flags) { 11153 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11154 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11155 } 11156 11157 private void updatePermissionsLPw(String changingPkg, 11158 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11159 // Make sure there are no dangling permission trees. 11160 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11161 while (it.hasNext()) { 11162 final BasePermission bp = it.next(); 11163 if (bp.packageSetting == null) { 11164 // We may not yet have parsed the package, so just see if 11165 // we still know about its settings. 11166 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11167 } 11168 if (bp.packageSetting == null) { 11169 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11170 + " from package " + bp.sourcePackage); 11171 it.remove(); 11172 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11173 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11174 Slog.i(TAG, "Removing old permission tree: " + bp.name 11175 + " from package " + bp.sourcePackage); 11176 flags |= UPDATE_PERMISSIONS_ALL; 11177 it.remove(); 11178 } 11179 } 11180 } 11181 11182 // Make sure all dynamic permissions have been assigned to a package, 11183 // and make sure there are no dangling permissions. 11184 it = mSettings.mPermissions.values().iterator(); 11185 while (it.hasNext()) { 11186 final BasePermission bp = it.next(); 11187 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11188 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11189 + bp.name + " pkg=" + bp.sourcePackage 11190 + " info=" + bp.pendingInfo); 11191 if (bp.packageSetting == null && bp.pendingInfo != null) { 11192 final BasePermission tree = findPermissionTreeLP(bp.name); 11193 if (tree != null && tree.perm != null) { 11194 bp.packageSetting = tree.packageSetting; 11195 bp.perm = new PackageParser.Permission(tree.perm.owner, 11196 new PermissionInfo(bp.pendingInfo)); 11197 bp.perm.info.packageName = tree.perm.info.packageName; 11198 bp.perm.info.name = bp.name; 11199 bp.uid = tree.uid; 11200 } 11201 } 11202 } 11203 if (bp.packageSetting == null) { 11204 // We may not yet have parsed the package, so just see if 11205 // we still know about its settings. 11206 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11207 } 11208 if (bp.packageSetting == null) { 11209 Slog.w(TAG, "Removing dangling permission: " + bp.name 11210 + " from package " + bp.sourcePackage); 11211 it.remove(); 11212 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11213 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11214 Slog.i(TAG, "Removing old permission: " + bp.name 11215 + " from package " + bp.sourcePackage); 11216 flags |= UPDATE_PERMISSIONS_ALL; 11217 it.remove(); 11218 } 11219 } 11220 } 11221 11222 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11223 // Now update the permissions for all packages, in particular 11224 // replace the granted permissions of the system packages. 11225 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11226 for (PackageParser.Package pkg : mPackages.values()) { 11227 if (pkg != pkgInfo) { 11228 // Only replace for packages on requested volume 11229 final String volumeUuid = getVolumeUuidForPackage(pkg); 11230 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11231 && Objects.equals(replaceVolumeUuid, volumeUuid); 11232 grantPermissionsLPw(pkg, replace, changingPkg); 11233 } 11234 } 11235 } 11236 11237 if (pkgInfo != null) { 11238 // Only replace for packages on requested volume 11239 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11240 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11241 && Objects.equals(replaceVolumeUuid, volumeUuid); 11242 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11243 } 11244 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11245 } 11246 11247 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11248 String packageOfInterest) { 11249 // IMPORTANT: There are two types of permissions: install and runtime. 11250 // Install time permissions are granted when the app is installed to 11251 // all device users and users added in the future. Runtime permissions 11252 // are granted at runtime explicitly to specific users. Normal and signature 11253 // protected permissions are install time permissions. Dangerous permissions 11254 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11255 // otherwise they are runtime permissions. This function does not manage 11256 // runtime permissions except for the case an app targeting Lollipop MR1 11257 // being upgraded to target a newer SDK, in which case dangerous permissions 11258 // are transformed from install time to runtime ones. 11259 11260 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11261 if (ps == null) { 11262 return; 11263 } 11264 11265 PermissionsState permissionsState = ps.getPermissionsState(); 11266 PermissionsState origPermissions = permissionsState; 11267 11268 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11269 11270 boolean runtimePermissionsRevoked = false; 11271 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11272 11273 boolean changedInstallPermission = false; 11274 11275 if (replace) { 11276 ps.installPermissionsFixed = false; 11277 if (!ps.isSharedUser()) { 11278 origPermissions = new PermissionsState(permissionsState); 11279 permissionsState.reset(); 11280 } else { 11281 // We need to know only about runtime permission changes since the 11282 // calling code always writes the install permissions state but 11283 // the runtime ones are written only if changed. The only cases of 11284 // changed runtime permissions here are promotion of an install to 11285 // runtime and revocation of a runtime from a shared user. 11286 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11287 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11288 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11289 runtimePermissionsRevoked = true; 11290 } 11291 } 11292 } 11293 11294 permissionsState.setGlobalGids(mGlobalGids); 11295 11296 final int N = pkg.requestedPermissions.size(); 11297 for (int i=0; i<N; i++) { 11298 final String name = pkg.requestedPermissions.get(i); 11299 final BasePermission bp = mSettings.mPermissions.get(name); 11300 11301 if (DEBUG_INSTALL) { 11302 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11303 } 11304 11305 if (bp == null || bp.packageSetting == null) { 11306 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11307 Slog.w(TAG, "Unknown permission " + name 11308 + " in package " + pkg.packageName); 11309 } 11310 continue; 11311 } 11312 11313 11314 // Limit ephemeral apps to ephemeral allowed permissions. 11315 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11316 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11317 + pkg.packageName); 11318 continue; 11319 } 11320 11321 final String perm = bp.name; 11322 boolean allowedSig = false; 11323 int grant = GRANT_DENIED; 11324 11325 // Keep track of app op permissions. 11326 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11327 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11328 if (pkgs == null) { 11329 pkgs = new ArraySet<>(); 11330 mAppOpPermissionPackages.put(bp.name, pkgs); 11331 } 11332 pkgs.add(pkg.packageName); 11333 } 11334 11335 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11336 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11337 >= Build.VERSION_CODES.M; 11338 switch (level) { 11339 case PermissionInfo.PROTECTION_NORMAL: { 11340 // For all apps normal permissions are install time ones. 11341 grant = GRANT_INSTALL; 11342 } break; 11343 11344 case PermissionInfo.PROTECTION_DANGEROUS: { 11345 // If a permission review is required for legacy apps we represent 11346 // their permissions as always granted runtime ones since we need 11347 // to keep the review required permission flag per user while an 11348 // install permission's state is shared across all users. 11349 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11350 // For legacy apps dangerous permissions are install time ones. 11351 grant = GRANT_INSTALL; 11352 } else if (origPermissions.hasInstallPermission(bp.name)) { 11353 // For legacy apps that became modern, install becomes runtime. 11354 grant = GRANT_UPGRADE; 11355 } else if (mPromoteSystemApps 11356 && isSystemApp(ps) 11357 && mExistingSystemPackages.contains(ps.name)) { 11358 // For legacy system apps, install becomes runtime. 11359 // We cannot check hasInstallPermission() for system apps since those 11360 // permissions were granted implicitly and not persisted pre-M. 11361 grant = GRANT_UPGRADE; 11362 } else { 11363 // For modern apps keep runtime permissions unchanged. 11364 grant = GRANT_RUNTIME; 11365 } 11366 } break; 11367 11368 case PermissionInfo.PROTECTION_SIGNATURE: { 11369 // For all apps signature permissions are install time ones. 11370 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11371 if (allowedSig) { 11372 grant = GRANT_INSTALL; 11373 } 11374 } break; 11375 } 11376 11377 if (DEBUG_INSTALL) { 11378 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11379 } 11380 11381 if (grant != GRANT_DENIED) { 11382 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11383 // If this is an existing, non-system package, then 11384 // we can't add any new permissions to it. 11385 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11386 // Except... if this is a permission that was added 11387 // to the platform (note: need to only do this when 11388 // updating the platform). 11389 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11390 grant = GRANT_DENIED; 11391 } 11392 } 11393 } 11394 11395 switch (grant) { 11396 case GRANT_INSTALL: { 11397 // Revoke this as runtime permission to handle the case of 11398 // a runtime permission being downgraded to an install one. 11399 // Also in permission review mode we keep dangerous permissions 11400 // for legacy apps 11401 for (int userId : UserManagerService.getInstance().getUserIds()) { 11402 if (origPermissions.getRuntimePermissionState( 11403 bp.name, userId) != null) { 11404 // Revoke the runtime permission and clear the flags. 11405 origPermissions.revokeRuntimePermission(bp, userId); 11406 origPermissions.updatePermissionFlags(bp, userId, 11407 PackageManager.MASK_PERMISSION_FLAGS, 0); 11408 // If we revoked a permission permission, we have to write. 11409 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11410 changedRuntimePermissionUserIds, userId); 11411 } 11412 } 11413 // Grant an install permission. 11414 if (permissionsState.grantInstallPermission(bp) != 11415 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11416 changedInstallPermission = true; 11417 } 11418 } break; 11419 11420 case GRANT_RUNTIME: { 11421 // Grant previously granted runtime permissions. 11422 for (int userId : UserManagerService.getInstance().getUserIds()) { 11423 PermissionState permissionState = origPermissions 11424 .getRuntimePermissionState(bp.name, userId); 11425 int flags = permissionState != null 11426 ? permissionState.getFlags() : 0; 11427 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11428 // Don't propagate the permission in a permission review mode if 11429 // the former was revoked, i.e. marked to not propagate on upgrade. 11430 // Note that in a permission review mode install permissions are 11431 // represented as constantly granted runtime ones since we need to 11432 // keep a per user state associated with the permission. Also the 11433 // revoke on upgrade flag is no longer applicable and is reset. 11434 final boolean revokeOnUpgrade = (flags & PackageManager 11435 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11436 if (revokeOnUpgrade) { 11437 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11438 // Since we changed the flags, we have to write. 11439 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11440 changedRuntimePermissionUserIds, userId); 11441 } 11442 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11443 if (permissionsState.grantRuntimePermission(bp, userId) == 11444 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11445 // If we cannot put the permission as it was, 11446 // we have to write. 11447 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11448 changedRuntimePermissionUserIds, userId); 11449 } 11450 } 11451 11452 // If the app supports runtime permissions no need for a review. 11453 if (mPermissionReviewRequired 11454 && appSupportsRuntimePermissions 11455 && (flags & PackageManager 11456 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11457 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11458 // Since we changed the flags, we have to write. 11459 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11460 changedRuntimePermissionUserIds, userId); 11461 } 11462 } else if (mPermissionReviewRequired 11463 && !appSupportsRuntimePermissions) { 11464 // For legacy apps that need a permission review, every new 11465 // runtime permission is granted but it is pending a review. 11466 // We also need to review only platform defined runtime 11467 // permissions as these are the only ones the platform knows 11468 // how to disable the API to simulate revocation as legacy 11469 // apps don't expect to run with revoked permissions. 11470 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11471 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11472 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11473 // We changed the flags, hence have to write. 11474 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11475 changedRuntimePermissionUserIds, userId); 11476 } 11477 } 11478 if (permissionsState.grantRuntimePermission(bp, userId) 11479 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11480 // We changed the permission, hence have to write. 11481 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11482 changedRuntimePermissionUserIds, userId); 11483 } 11484 } 11485 // Propagate the permission flags. 11486 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11487 } 11488 } break; 11489 11490 case GRANT_UPGRADE: { 11491 // Grant runtime permissions for a previously held install permission. 11492 PermissionState permissionState = origPermissions 11493 .getInstallPermissionState(bp.name); 11494 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11495 11496 if (origPermissions.revokeInstallPermission(bp) 11497 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11498 // We will be transferring the permission flags, so clear them. 11499 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11500 PackageManager.MASK_PERMISSION_FLAGS, 0); 11501 changedInstallPermission = true; 11502 } 11503 11504 // If the permission is not to be promoted to runtime we ignore it and 11505 // also its other flags as they are not applicable to install permissions. 11506 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11507 for (int userId : currentUserIds) { 11508 if (permissionsState.grantRuntimePermission(bp, userId) != 11509 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11510 // Transfer the permission flags. 11511 permissionsState.updatePermissionFlags(bp, userId, 11512 flags, flags); 11513 // If we granted the permission, we have to write. 11514 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11515 changedRuntimePermissionUserIds, userId); 11516 } 11517 } 11518 } 11519 } break; 11520 11521 default: { 11522 if (packageOfInterest == null 11523 || packageOfInterest.equals(pkg.packageName)) { 11524 Slog.w(TAG, "Not granting permission " + perm 11525 + " to package " + pkg.packageName 11526 + " because it was previously installed without"); 11527 } 11528 } break; 11529 } 11530 } else { 11531 if (permissionsState.revokeInstallPermission(bp) != 11532 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11533 // Also drop the permission flags. 11534 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11535 PackageManager.MASK_PERMISSION_FLAGS, 0); 11536 changedInstallPermission = true; 11537 Slog.i(TAG, "Un-granting permission " + perm 11538 + " from package " + pkg.packageName 11539 + " (protectionLevel=" + bp.protectionLevel 11540 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11541 + ")"); 11542 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11543 // Don't print warning for app op permissions, since it is fine for them 11544 // not to be granted, there is a UI for the user to decide. 11545 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11546 Slog.w(TAG, "Not granting permission " + perm 11547 + " to package " + pkg.packageName 11548 + " (protectionLevel=" + bp.protectionLevel 11549 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11550 + ")"); 11551 } 11552 } 11553 } 11554 } 11555 11556 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11557 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11558 // This is the first that we have heard about this package, so the 11559 // permissions we have now selected are fixed until explicitly 11560 // changed. 11561 ps.installPermissionsFixed = true; 11562 } 11563 11564 // Persist the runtime permissions state for users with changes. If permissions 11565 // were revoked because no app in the shared user declares them we have to 11566 // write synchronously to avoid losing runtime permissions state. 11567 for (int userId : changedRuntimePermissionUserIds) { 11568 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11569 } 11570 } 11571 11572 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11573 boolean allowed = false; 11574 final int NP = PackageParser.NEW_PERMISSIONS.length; 11575 for (int ip=0; ip<NP; ip++) { 11576 final PackageParser.NewPermissionInfo npi 11577 = PackageParser.NEW_PERMISSIONS[ip]; 11578 if (npi.name.equals(perm) 11579 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11580 allowed = true; 11581 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11582 + pkg.packageName); 11583 break; 11584 } 11585 } 11586 return allowed; 11587 } 11588 11589 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11590 BasePermission bp, PermissionsState origPermissions) { 11591 boolean privilegedPermission = (bp.protectionLevel 11592 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11593 boolean privappPermissionsDisable = 11594 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11595 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11596 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11597 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11598 && !platformPackage && platformPermission) { 11599 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11600 .getPrivAppPermissions(pkg.packageName); 11601 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11602 if (!whitelisted) { 11603 Slog.w(TAG, "Privileged permission " + perm + " for package " 11604 + pkg.packageName + " - not in privapp-permissions whitelist"); 11605 // Only report violations for apps on system image 11606 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11607 if (mPrivappPermissionsViolations == null) { 11608 mPrivappPermissionsViolations = new ArraySet<>(); 11609 } 11610 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11611 } 11612 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11613 return false; 11614 } 11615 } 11616 } 11617 boolean allowed = (compareSignatures( 11618 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11619 == PackageManager.SIGNATURE_MATCH) 11620 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11621 == PackageManager.SIGNATURE_MATCH); 11622 if (!allowed && privilegedPermission) { 11623 if (isSystemApp(pkg)) { 11624 // For updated system applications, a system permission 11625 // is granted only if it had been defined by the original application. 11626 if (pkg.isUpdatedSystemApp()) { 11627 final PackageSetting sysPs = mSettings 11628 .getDisabledSystemPkgLPr(pkg.packageName); 11629 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11630 // If the original was granted this permission, we take 11631 // that grant decision as read and propagate it to the 11632 // update. 11633 if (sysPs.isPrivileged()) { 11634 allowed = true; 11635 } 11636 } else { 11637 // The system apk may have been updated with an older 11638 // version of the one on the data partition, but which 11639 // granted a new system permission that it didn't have 11640 // before. In this case we do want to allow the app to 11641 // now get the new permission if the ancestral apk is 11642 // privileged to get it. 11643 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11644 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11645 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11646 allowed = true; 11647 break; 11648 } 11649 } 11650 } 11651 // Also if a privileged parent package on the system image or any of 11652 // its children requested a privileged permission, the updated child 11653 // packages can also get the permission. 11654 if (pkg.parentPackage != null) { 11655 final PackageSetting disabledSysParentPs = mSettings 11656 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11657 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11658 && disabledSysParentPs.isPrivileged()) { 11659 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11660 allowed = true; 11661 } else if (disabledSysParentPs.pkg.childPackages != null) { 11662 final int count = disabledSysParentPs.pkg.childPackages.size(); 11663 for (int i = 0; i < count; i++) { 11664 PackageParser.Package disabledSysChildPkg = 11665 disabledSysParentPs.pkg.childPackages.get(i); 11666 if (isPackageRequestingPermission(disabledSysChildPkg, 11667 perm)) { 11668 allowed = true; 11669 break; 11670 } 11671 } 11672 } 11673 } 11674 } 11675 } 11676 } else { 11677 allowed = isPrivilegedApp(pkg); 11678 } 11679 } 11680 } 11681 if (!allowed) { 11682 if (!allowed && (bp.protectionLevel 11683 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11684 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11685 // If this was a previously normal/dangerous permission that got moved 11686 // to a system permission as part of the runtime permission redesign, then 11687 // we still want to blindly grant it to old apps. 11688 allowed = true; 11689 } 11690 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11691 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11692 // If this permission is to be granted to the system installer and 11693 // this app is an installer, then it gets the permission. 11694 allowed = true; 11695 } 11696 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11697 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11698 // If this permission is to be granted to the system verifier and 11699 // this app is a verifier, then it gets the permission. 11700 allowed = true; 11701 } 11702 if (!allowed && (bp.protectionLevel 11703 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11704 && isSystemApp(pkg)) { 11705 // Any pre-installed system app is allowed to get this permission. 11706 allowed = true; 11707 } 11708 if (!allowed && (bp.protectionLevel 11709 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11710 // For development permissions, a development permission 11711 // is granted only if it was already granted. 11712 allowed = origPermissions.hasInstallPermission(perm); 11713 } 11714 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11715 && pkg.packageName.equals(mSetupWizardPackage)) { 11716 // If this permission is to be granted to the system setup wizard and 11717 // this app is a setup wizard, then it gets the permission. 11718 allowed = true; 11719 } 11720 } 11721 return allowed; 11722 } 11723 11724 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11725 final int permCount = pkg.requestedPermissions.size(); 11726 for (int j = 0; j < permCount; j++) { 11727 String requestedPermission = pkg.requestedPermissions.get(j); 11728 if (permission.equals(requestedPermission)) { 11729 return true; 11730 } 11731 } 11732 return false; 11733 } 11734 11735 final class ActivityIntentResolver 11736 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11737 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11738 boolean defaultOnly, int userId) { 11739 if (!sUserManager.exists(userId)) return null; 11740 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11741 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11742 } 11743 11744 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11745 int userId) { 11746 if (!sUserManager.exists(userId)) return null; 11747 mFlags = flags; 11748 return super.queryIntent(intent, resolvedType, 11749 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11750 userId); 11751 } 11752 11753 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11754 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11755 if (!sUserManager.exists(userId)) return null; 11756 if (packageActivities == null) { 11757 return null; 11758 } 11759 mFlags = flags; 11760 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11761 final int N = packageActivities.size(); 11762 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11763 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11764 11765 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11766 for (int i = 0; i < N; ++i) { 11767 intentFilters = packageActivities.get(i).intents; 11768 if (intentFilters != null && intentFilters.size() > 0) { 11769 PackageParser.ActivityIntentInfo[] array = 11770 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11771 intentFilters.toArray(array); 11772 listCut.add(array); 11773 } 11774 } 11775 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11776 } 11777 11778 /** 11779 * Finds a privileged activity that matches the specified activity names. 11780 */ 11781 private PackageParser.Activity findMatchingActivity( 11782 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11783 for (PackageParser.Activity sysActivity : activityList) { 11784 if (sysActivity.info.name.equals(activityInfo.name)) { 11785 return sysActivity; 11786 } 11787 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11788 return sysActivity; 11789 } 11790 if (sysActivity.info.targetActivity != null) { 11791 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11792 return sysActivity; 11793 } 11794 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11795 return sysActivity; 11796 } 11797 } 11798 } 11799 return null; 11800 } 11801 11802 public class IterGenerator<E> { 11803 public Iterator<E> generate(ActivityIntentInfo info) { 11804 return null; 11805 } 11806 } 11807 11808 public class ActionIterGenerator extends IterGenerator<String> { 11809 @Override 11810 public Iterator<String> generate(ActivityIntentInfo info) { 11811 return info.actionsIterator(); 11812 } 11813 } 11814 11815 public class CategoriesIterGenerator extends IterGenerator<String> { 11816 @Override 11817 public Iterator<String> generate(ActivityIntentInfo info) { 11818 return info.categoriesIterator(); 11819 } 11820 } 11821 11822 public class SchemesIterGenerator extends IterGenerator<String> { 11823 @Override 11824 public Iterator<String> generate(ActivityIntentInfo info) { 11825 return info.schemesIterator(); 11826 } 11827 } 11828 11829 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11830 @Override 11831 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11832 return info.authoritiesIterator(); 11833 } 11834 } 11835 11836 /** 11837 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11838 * MODIFIED. Do not pass in a list that should not be changed. 11839 */ 11840 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11841 IterGenerator<T> generator, Iterator<T> searchIterator) { 11842 // loop through the set of actions; every one must be found in the intent filter 11843 while (searchIterator.hasNext()) { 11844 // we must have at least one filter in the list to consider a match 11845 if (intentList.size() == 0) { 11846 break; 11847 } 11848 11849 final T searchAction = searchIterator.next(); 11850 11851 // loop through the set of intent filters 11852 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11853 while (intentIter.hasNext()) { 11854 final ActivityIntentInfo intentInfo = intentIter.next(); 11855 boolean selectionFound = false; 11856 11857 // loop through the intent filter's selection criteria; at least one 11858 // of them must match the searched criteria 11859 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11860 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11861 final T intentSelection = intentSelectionIter.next(); 11862 if (intentSelection != null && intentSelection.equals(searchAction)) { 11863 selectionFound = true; 11864 break; 11865 } 11866 } 11867 11868 // the selection criteria wasn't found in this filter's set; this filter 11869 // is not a potential match 11870 if (!selectionFound) { 11871 intentIter.remove(); 11872 } 11873 } 11874 } 11875 } 11876 11877 private boolean isProtectedAction(ActivityIntentInfo filter) { 11878 final Iterator<String> actionsIter = filter.actionsIterator(); 11879 while (actionsIter != null && actionsIter.hasNext()) { 11880 final String filterAction = actionsIter.next(); 11881 if (PROTECTED_ACTIONS.contains(filterAction)) { 11882 return true; 11883 } 11884 } 11885 return false; 11886 } 11887 11888 /** 11889 * Adjusts the priority of the given intent filter according to policy. 11890 * <p> 11891 * <ul> 11892 * <li>The priority for non privileged applications is capped to '0'</li> 11893 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11894 * <li>The priority for unbundled updates to privileged applications is capped to the 11895 * priority defined on the system partition</li> 11896 * </ul> 11897 * <p> 11898 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 11899 * allowed to obtain any priority on any action. 11900 */ 11901 private void adjustPriority( 11902 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 11903 // nothing to do; priority is fine as-is 11904 if (intent.getPriority() <= 0) { 11905 return; 11906 } 11907 11908 final ActivityInfo activityInfo = intent.activity.info; 11909 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 11910 11911 final boolean privilegedApp = 11912 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 11913 if (!privilegedApp) { 11914 // non-privileged applications can never define a priority >0 11915 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 11916 + " package: " + applicationInfo.packageName 11917 + " activity: " + intent.activity.className 11918 + " origPrio: " + intent.getPriority()); 11919 intent.setPriority(0); 11920 return; 11921 } 11922 11923 if (systemActivities == null) { 11924 // the system package is not disabled; we're parsing the system partition 11925 if (isProtectedAction(intent)) { 11926 if (mDeferProtectedFilters) { 11927 // We can't deal with these just yet. No component should ever obtain a 11928 // >0 priority for a protected actions, with ONE exception -- the setup 11929 // wizard. The setup wizard, however, cannot be known until we're able to 11930 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 11931 // until all intent filters have been processed. Chicken, meet egg. 11932 // Let the filter temporarily have a high priority and rectify the 11933 // priorities after all system packages have been scanned. 11934 mProtectedFilters.add(intent); 11935 if (DEBUG_FILTERS) { 11936 Slog.i(TAG, "Protected action; save for later;" 11937 + " package: " + applicationInfo.packageName 11938 + " activity: " + intent.activity.className 11939 + " origPrio: " + intent.getPriority()); 11940 } 11941 return; 11942 } else { 11943 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 11944 Slog.i(TAG, "No setup wizard;" 11945 + " All protected intents capped to priority 0"); 11946 } 11947 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 11948 if (DEBUG_FILTERS) { 11949 Slog.i(TAG, "Found setup wizard;" 11950 + " allow priority " + intent.getPriority() + ";" 11951 + " package: " + intent.activity.info.packageName 11952 + " activity: " + intent.activity.className 11953 + " priority: " + intent.getPriority()); 11954 } 11955 // setup wizard gets whatever it wants 11956 return; 11957 } 11958 Slog.w(TAG, "Protected action; cap priority to 0;" 11959 + " package: " + intent.activity.info.packageName 11960 + " activity: " + intent.activity.className 11961 + " origPrio: " + intent.getPriority()); 11962 intent.setPriority(0); 11963 return; 11964 } 11965 } 11966 // privileged apps on the system image get whatever priority they request 11967 return; 11968 } 11969 11970 // privileged app unbundled update ... try to find the same activity 11971 final PackageParser.Activity foundActivity = 11972 findMatchingActivity(systemActivities, activityInfo); 11973 if (foundActivity == null) { 11974 // this is a new activity; it cannot obtain >0 priority 11975 if (DEBUG_FILTERS) { 11976 Slog.i(TAG, "New activity; cap priority to 0;" 11977 + " package: " + applicationInfo.packageName 11978 + " activity: " + intent.activity.className 11979 + " origPrio: " + intent.getPriority()); 11980 } 11981 intent.setPriority(0); 11982 return; 11983 } 11984 11985 // found activity, now check for filter equivalence 11986 11987 // a shallow copy is enough; we modify the list, not its contents 11988 final List<ActivityIntentInfo> intentListCopy = 11989 new ArrayList<>(foundActivity.intents); 11990 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 11991 11992 // find matching action subsets 11993 final Iterator<String> actionsIterator = intent.actionsIterator(); 11994 if (actionsIterator != null) { 11995 getIntentListSubset( 11996 intentListCopy, new ActionIterGenerator(), actionsIterator); 11997 if (intentListCopy.size() == 0) { 11998 // no more intents to match; we're not equivalent 11999 if (DEBUG_FILTERS) { 12000 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12001 + " package: " + applicationInfo.packageName 12002 + " activity: " + intent.activity.className 12003 + " origPrio: " + intent.getPriority()); 12004 } 12005 intent.setPriority(0); 12006 return; 12007 } 12008 } 12009 12010 // find matching category subsets 12011 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12012 if (categoriesIterator != null) { 12013 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12014 categoriesIterator); 12015 if (intentListCopy.size() == 0) { 12016 // no more intents to match; we're not equivalent 12017 if (DEBUG_FILTERS) { 12018 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12019 + " package: " + applicationInfo.packageName 12020 + " activity: " + intent.activity.className 12021 + " origPrio: " + intent.getPriority()); 12022 } 12023 intent.setPriority(0); 12024 return; 12025 } 12026 } 12027 12028 // find matching schemes subsets 12029 final Iterator<String> schemesIterator = intent.schemesIterator(); 12030 if (schemesIterator != null) { 12031 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12032 schemesIterator); 12033 if (intentListCopy.size() == 0) { 12034 // no more intents to match; we're not equivalent 12035 if (DEBUG_FILTERS) { 12036 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12037 + " package: " + applicationInfo.packageName 12038 + " activity: " + intent.activity.className 12039 + " origPrio: " + intent.getPriority()); 12040 } 12041 intent.setPriority(0); 12042 return; 12043 } 12044 } 12045 12046 // find matching authorities subsets 12047 final Iterator<IntentFilter.AuthorityEntry> 12048 authoritiesIterator = intent.authoritiesIterator(); 12049 if (authoritiesIterator != null) { 12050 getIntentListSubset(intentListCopy, 12051 new AuthoritiesIterGenerator(), 12052 authoritiesIterator); 12053 if (intentListCopy.size() == 0) { 12054 // no more intents to match; we're not equivalent 12055 if (DEBUG_FILTERS) { 12056 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12057 + " package: " + applicationInfo.packageName 12058 + " activity: " + intent.activity.className 12059 + " origPrio: " + intent.getPriority()); 12060 } 12061 intent.setPriority(0); 12062 return; 12063 } 12064 } 12065 12066 // we found matching filter(s); app gets the max priority of all intents 12067 int cappedPriority = 0; 12068 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12069 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12070 } 12071 if (intent.getPriority() > cappedPriority) { 12072 if (DEBUG_FILTERS) { 12073 Slog.i(TAG, "Found matching filter(s);" 12074 + " cap priority to " + cappedPriority + ";" 12075 + " package: " + applicationInfo.packageName 12076 + " activity: " + intent.activity.className 12077 + " origPrio: " + intent.getPriority()); 12078 } 12079 intent.setPriority(cappedPriority); 12080 return; 12081 } 12082 // all this for nothing; the requested priority was <= what was on the system 12083 } 12084 12085 public final void addActivity(PackageParser.Activity a, String type) { 12086 mActivities.put(a.getComponentName(), a); 12087 if (DEBUG_SHOW_INFO) 12088 Log.v( 12089 TAG, " " + type + " " + 12090 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12091 if (DEBUG_SHOW_INFO) 12092 Log.v(TAG, " Class=" + a.info.name); 12093 final int NI = a.intents.size(); 12094 for (int j=0; j<NI; j++) { 12095 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12096 if ("activity".equals(type)) { 12097 final PackageSetting ps = 12098 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12099 final List<PackageParser.Activity> systemActivities = 12100 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12101 adjustPriority(systemActivities, intent); 12102 } 12103 if (DEBUG_SHOW_INFO) { 12104 Log.v(TAG, " IntentFilter:"); 12105 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12106 } 12107 if (!intent.debugCheck()) { 12108 Log.w(TAG, "==> For Activity " + a.info.name); 12109 } 12110 addFilter(intent); 12111 } 12112 } 12113 12114 public final void removeActivity(PackageParser.Activity a, String type) { 12115 mActivities.remove(a.getComponentName()); 12116 if (DEBUG_SHOW_INFO) { 12117 Log.v(TAG, " " + type + " " 12118 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12119 : a.info.name) + ":"); 12120 Log.v(TAG, " Class=" + a.info.name); 12121 } 12122 final int NI = a.intents.size(); 12123 for (int j=0; j<NI; j++) { 12124 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12125 if (DEBUG_SHOW_INFO) { 12126 Log.v(TAG, " IntentFilter:"); 12127 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12128 } 12129 removeFilter(intent); 12130 } 12131 } 12132 12133 @Override 12134 protected boolean allowFilterResult( 12135 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12136 ActivityInfo filterAi = filter.activity.info; 12137 for (int i=dest.size()-1; i>=0; i--) { 12138 ActivityInfo destAi = dest.get(i).activityInfo; 12139 if (destAi.name == filterAi.name 12140 && destAi.packageName == filterAi.packageName) { 12141 return false; 12142 } 12143 } 12144 return true; 12145 } 12146 12147 @Override 12148 protected ActivityIntentInfo[] newArray(int size) { 12149 return new ActivityIntentInfo[size]; 12150 } 12151 12152 @Override 12153 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12154 if (!sUserManager.exists(userId)) return true; 12155 PackageParser.Package p = filter.activity.owner; 12156 if (p != null) { 12157 PackageSetting ps = (PackageSetting)p.mExtras; 12158 if (ps != null) { 12159 // System apps are never considered stopped for purposes of 12160 // filtering, because there may be no way for the user to 12161 // actually re-launch them. 12162 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12163 && ps.getStopped(userId); 12164 } 12165 } 12166 return false; 12167 } 12168 12169 @Override 12170 protected boolean isPackageForFilter(String packageName, 12171 PackageParser.ActivityIntentInfo info) { 12172 return packageName.equals(info.activity.owner.packageName); 12173 } 12174 12175 @Override 12176 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12177 int match, int userId) { 12178 if (!sUserManager.exists(userId)) return null; 12179 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12180 return null; 12181 } 12182 final PackageParser.Activity activity = info.activity; 12183 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12184 if (ps == null) { 12185 return null; 12186 } 12187 final PackageUserState userState = ps.readUserState(userId); 12188 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12189 userState, userId); 12190 if (ai == null) { 12191 return null; 12192 } 12193 final boolean matchVisibleToInstantApp = 12194 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12195 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12196 // throw out filters that aren't visible to ephemeral apps 12197 if (matchVisibleToInstantApp 12198 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12199 return null; 12200 } 12201 // throw out ephemeral filters if we're not explicitly requesting them 12202 if (!isInstantApp && userState.instantApp) { 12203 return null; 12204 } 12205 // throw out instant app filters if updates are available; will trigger 12206 // instant app resolution 12207 if (userState.instantApp && ps.isUpdateAvailable()) { 12208 return null; 12209 } 12210 final ResolveInfo res = new ResolveInfo(); 12211 res.activityInfo = ai; 12212 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12213 res.filter = info; 12214 } 12215 if (info != null) { 12216 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12217 } 12218 res.priority = info.getPriority(); 12219 res.preferredOrder = activity.owner.mPreferredOrder; 12220 //System.out.println("Result: " + res.activityInfo.className + 12221 // " = " + res.priority); 12222 res.match = match; 12223 res.isDefault = info.hasDefault; 12224 res.labelRes = info.labelRes; 12225 res.nonLocalizedLabel = info.nonLocalizedLabel; 12226 if (userNeedsBadging(userId)) { 12227 res.noResourceId = true; 12228 } else { 12229 res.icon = info.icon; 12230 } 12231 res.iconResourceId = info.icon; 12232 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12233 res.instantAppAvailable = userState.instantApp; 12234 return res; 12235 } 12236 12237 @Override 12238 protected void sortResults(List<ResolveInfo> results) { 12239 Collections.sort(results, mResolvePrioritySorter); 12240 } 12241 12242 @Override 12243 protected void dumpFilter(PrintWriter out, String prefix, 12244 PackageParser.ActivityIntentInfo filter) { 12245 out.print(prefix); out.print( 12246 Integer.toHexString(System.identityHashCode(filter.activity))); 12247 out.print(' '); 12248 filter.activity.printComponentShortName(out); 12249 out.print(" filter "); 12250 out.println(Integer.toHexString(System.identityHashCode(filter))); 12251 } 12252 12253 @Override 12254 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12255 return filter.activity; 12256 } 12257 12258 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12259 PackageParser.Activity activity = (PackageParser.Activity)label; 12260 out.print(prefix); out.print( 12261 Integer.toHexString(System.identityHashCode(activity))); 12262 out.print(' '); 12263 activity.printComponentShortName(out); 12264 if (count > 1) { 12265 out.print(" ("); out.print(count); out.print(" filters)"); 12266 } 12267 out.println(); 12268 } 12269 12270 // Keys are String (activity class name), values are Activity. 12271 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12272 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12273 private int mFlags; 12274 } 12275 12276 private final class ServiceIntentResolver 12277 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12278 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12279 boolean defaultOnly, int userId) { 12280 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12281 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12282 } 12283 12284 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12285 int userId) { 12286 if (!sUserManager.exists(userId)) return null; 12287 mFlags = flags; 12288 return super.queryIntent(intent, resolvedType, 12289 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12290 userId); 12291 } 12292 12293 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12294 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12295 if (!sUserManager.exists(userId)) return null; 12296 if (packageServices == null) { 12297 return null; 12298 } 12299 mFlags = flags; 12300 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12301 final int N = packageServices.size(); 12302 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12303 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12304 12305 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12306 for (int i = 0; i < N; ++i) { 12307 intentFilters = packageServices.get(i).intents; 12308 if (intentFilters != null && intentFilters.size() > 0) { 12309 PackageParser.ServiceIntentInfo[] array = 12310 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12311 intentFilters.toArray(array); 12312 listCut.add(array); 12313 } 12314 } 12315 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12316 } 12317 12318 public final void addService(PackageParser.Service s) { 12319 mServices.put(s.getComponentName(), s); 12320 if (DEBUG_SHOW_INFO) { 12321 Log.v(TAG, " " 12322 + (s.info.nonLocalizedLabel != null 12323 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12324 Log.v(TAG, " Class=" + s.info.name); 12325 } 12326 final int NI = s.intents.size(); 12327 int j; 12328 for (j=0; j<NI; j++) { 12329 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12330 if (DEBUG_SHOW_INFO) { 12331 Log.v(TAG, " IntentFilter:"); 12332 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12333 } 12334 if (!intent.debugCheck()) { 12335 Log.w(TAG, "==> For Service " + s.info.name); 12336 } 12337 addFilter(intent); 12338 } 12339 } 12340 12341 public final void removeService(PackageParser.Service s) { 12342 mServices.remove(s.getComponentName()); 12343 if (DEBUG_SHOW_INFO) { 12344 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12345 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12346 Log.v(TAG, " Class=" + s.info.name); 12347 } 12348 final int NI = s.intents.size(); 12349 int j; 12350 for (j=0; j<NI; j++) { 12351 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12352 if (DEBUG_SHOW_INFO) { 12353 Log.v(TAG, " IntentFilter:"); 12354 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12355 } 12356 removeFilter(intent); 12357 } 12358 } 12359 12360 @Override 12361 protected boolean allowFilterResult( 12362 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12363 ServiceInfo filterSi = filter.service.info; 12364 for (int i=dest.size()-1; i>=0; i--) { 12365 ServiceInfo destAi = dest.get(i).serviceInfo; 12366 if (destAi.name == filterSi.name 12367 && destAi.packageName == filterSi.packageName) { 12368 return false; 12369 } 12370 } 12371 return true; 12372 } 12373 12374 @Override 12375 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12376 return new PackageParser.ServiceIntentInfo[size]; 12377 } 12378 12379 @Override 12380 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12381 if (!sUserManager.exists(userId)) return true; 12382 PackageParser.Package p = filter.service.owner; 12383 if (p != null) { 12384 PackageSetting ps = (PackageSetting)p.mExtras; 12385 if (ps != null) { 12386 // System apps are never considered stopped for purposes of 12387 // filtering, because there may be no way for the user to 12388 // actually re-launch them. 12389 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12390 && ps.getStopped(userId); 12391 } 12392 } 12393 return false; 12394 } 12395 12396 @Override 12397 protected boolean isPackageForFilter(String packageName, 12398 PackageParser.ServiceIntentInfo info) { 12399 return packageName.equals(info.service.owner.packageName); 12400 } 12401 12402 @Override 12403 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12404 int match, int userId) { 12405 if (!sUserManager.exists(userId)) return null; 12406 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12407 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12408 return null; 12409 } 12410 final PackageParser.Service service = info.service; 12411 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12412 if (ps == null) { 12413 return null; 12414 } 12415 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12416 ps.readUserState(userId), userId); 12417 if (si == null) { 12418 return null; 12419 } 12420 final ResolveInfo res = new ResolveInfo(); 12421 res.serviceInfo = si; 12422 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12423 res.filter = filter; 12424 } 12425 res.priority = info.getPriority(); 12426 res.preferredOrder = service.owner.mPreferredOrder; 12427 res.match = match; 12428 res.isDefault = info.hasDefault; 12429 res.labelRes = info.labelRes; 12430 res.nonLocalizedLabel = info.nonLocalizedLabel; 12431 res.icon = info.icon; 12432 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12433 return res; 12434 } 12435 12436 @Override 12437 protected void sortResults(List<ResolveInfo> results) { 12438 Collections.sort(results, mResolvePrioritySorter); 12439 } 12440 12441 @Override 12442 protected void dumpFilter(PrintWriter out, String prefix, 12443 PackageParser.ServiceIntentInfo filter) { 12444 out.print(prefix); out.print( 12445 Integer.toHexString(System.identityHashCode(filter.service))); 12446 out.print(' '); 12447 filter.service.printComponentShortName(out); 12448 out.print(" filter "); 12449 out.println(Integer.toHexString(System.identityHashCode(filter))); 12450 } 12451 12452 @Override 12453 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12454 return filter.service; 12455 } 12456 12457 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12458 PackageParser.Service service = (PackageParser.Service)label; 12459 out.print(prefix); out.print( 12460 Integer.toHexString(System.identityHashCode(service))); 12461 out.print(' '); 12462 service.printComponentShortName(out); 12463 if (count > 1) { 12464 out.print(" ("); out.print(count); out.print(" filters)"); 12465 } 12466 out.println(); 12467 } 12468 12469// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12470// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12471// final List<ResolveInfo> retList = Lists.newArrayList(); 12472// while (i.hasNext()) { 12473// final ResolveInfo resolveInfo = (ResolveInfo) i; 12474// if (isEnabledLP(resolveInfo.serviceInfo)) { 12475// retList.add(resolveInfo); 12476// } 12477// } 12478// return retList; 12479// } 12480 12481 // Keys are String (activity class name), values are Activity. 12482 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12483 = new ArrayMap<ComponentName, PackageParser.Service>(); 12484 private int mFlags; 12485 } 12486 12487 private final class ProviderIntentResolver 12488 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12489 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12490 boolean defaultOnly, int userId) { 12491 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12492 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12493 } 12494 12495 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12496 int userId) { 12497 if (!sUserManager.exists(userId)) 12498 return null; 12499 mFlags = flags; 12500 return super.queryIntent(intent, resolvedType, 12501 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12502 userId); 12503 } 12504 12505 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12506 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12507 if (!sUserManager.exists(userId)) 12508 return null; 12509 if (packageProviders == null) { 12510 return null; 12511 } 12512 mFlags = flags; 12513 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12514 final int N = packageProviders.size(); 12515 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12516 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12517 12518 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12519 for (int i = 0; i < N; ++i) { 12520 intentFilters = packageProviders.get(i).intents; 12521 if (intentFilters != null && intentFilters.size() > 0) { 12522 PackageParser.ProviderIntentInfo[] array = 12523 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12524 intentFilters.toArray(array); 12525 listCut.add(array); 12526 } 12527 } 12528 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12529 } 12530 12531 public final void addProvider(PackageParser.Provider p) { 12532 if (mProviders.containsKey(p.getComponentName())) { 12533 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12534 return; 12535 } 12536 12537 mProviders.put(p.getComponentName(), p); 12538 if (DEBUG_SHOW_INFO) { 12539 Log.v(TAG, " " 12540 + (p.info.nonLocalizedLabel != null 12541 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12542 Log.v(TAG, " Class=" + p.info.name); 12543 } 12544 final int NI = p.intents.size(); 12545 int j; 12546 for (j = 0; j < NI; j++) { 12547 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12548 if (DEBUG_SHOW_INFO) { 12549 Log.v(TAG, " IntentFilter:"); 12550 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12551 } 12552 if (!intent.debugCheck()) { 12553 Log.w(TAG, "==> For Provider " + p.info.name); 12554 } 12555 addFilter(intent); 12556 } 12557 } 12558 12559 public final void removeProvider(PackageParser.Provider p) { 12560 mProviders.remove(p.getComponentName()); 12561 if (DEBUG_SHOW_INFO) { 12562 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12563 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12564 Log.v(TAG, " Class=" + p.info.name); 12565 } 12566 final int NI = p.intents.size(); 12567 int j; 12568 for (j = 0; j < NI; j++) { 12569 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12570 if (DEBUG_SHOW_INFO) { 12571 Log.v(TAG, " IntentFilter:"); 12572 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12573 } 12574 removeFilter(intent); 12575 } 12576 } 12577 12578 @Override 12579 protected boolean allowFilterResult( 12580 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12581 ProviderInfo filterPi = filter.provider.info; 12582 for (int i = dest.size() - 1; i >= 0; i--) { 12583 ProviderInfo destPi = dest.get(i).providerInfo; 12584 if (destPi.name == filterPi.name 12585 && destPi.packageName == filterPi.packageName) { 12586 return false; 12587 } 12588 } 12589 return true; 12590 } 12591 12592 @Override 12593 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12594 return new PackageParser.ProviderIntentInfo[size]; 12595 } 12596 12597 @Override 12598 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12599 if (!sUserManager.exists(userId)) 12600 return true; 12601 PackageParser.Package p = filter.provider.owner; 12602 if (p != null) { 12603 PackageSetting ps = (PackageSetting) p.mExtras; 12604 if (ps != null) { 12605 // System apps are never considered stopped for purposes of 12606 // filtering, because there may be no way for the user to 12607 // actually re-launch them. 12608 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12609 && ps.getStopped(userId); 12610 } 12611 } 12612 return false; 12613 } 12614 12615 @Override 12616 protected boolean isPackageForFilter(String packageName, 12617 PackageParser.ProviderIntentInfo info) { 12618 return packageName.equals(info.provider.owner.packageName); 12619 } 12620 12621 @Override 12622 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12623 int match, int userId) { 12624 if (!sUserManager.exists(userId)) 12625 return null; 12626 final PackageParser.ProviderIntentInfo info = filter; 12627 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12628 return null; 12629 } 12630 final PackageParser.Provider provider = info.provider; 12631 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12632 if (ps == null) { 12633 return null; 12634 } 12635 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12636 ps.readUserState(userId), userId); 12637 if (pi == null) { 12638 return null; 12639 } 12640 final ResolveInfo res = new ResolveInfo(); 12641 res.providerInfo = pi; 12642 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12643 res.filter = filter; 12644 } 12645 res.priority = info.getPriority(); 12646 res.preferredOrder = provider.owner.mPreferredOrder; 12647 res.match = match; 12648 res.isDefault = info.hasDefault; 12649 res.labelRes = info.labelRes; 12650 res.nonLocalizedLabel = info.nonLocalizedLabel; 12651 res.icon = info.icon; 12652 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12653 return res; 12654 } 12655 12656 @Override 12657 protected void sortResults(List<ResolveInfo> results) { 12658 Collections.sort(results, mResolvePrioritySorter); 12659 } 12660 12661 @Override 12662 protected void dumpFilter(PrintWriter out, String prefix, 12663 PackageParser.ProviderIntentInfo filter) { 12664 out.print(prefix); 12665 out.print( 12666 Integer.toHexString(System.identityHashCode(filter.provider))); 12667 out.print(' '); 12668 filter.provider.printComponentShortName(out); 12669 out.print(" filter "); 12670 out.println(Integer.toHexString(System.identityHashCode(filter))); 12671 } 12672 12673 @Override 12674 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12675 return filter.provider; 12676 } 12677 12678 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12679 PackageParser.Provider provider = (PackageParser.Provider)label; 12680 out.print(prefix); out.print( 12681 Integer.toHexString(System.identityHashCode(provider))); 12682 out.print(' '); 12683 provider.printComponentShortName(out); 12684 if (count > 1) { 12685 out.print(" ("); out.print(count); out.print(" filters)"); 12686 } 12687 out.println(); 12688 } 12689 12690 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12691 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12692 private int mFlags; 12693 } 12694 12695 static final class EphemeralIntentResolver 12696 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12697 /** 12698 * The result that has the highest defined order. Ordering applies on a 12699 * per-package basis. Mapping is from package name to Pair of order and 12700 * EphemeralResolveInfo. 12701 * <p> 12702 * NOTE: This is implemented as a field variable for convenience and efficiency. 12703 * By having a field variable, we're able to track filter ordering as soon as 12704 * a non-zero order is defined. Otherwise, multiple loops across the result set 12705 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12706 * this needs to be contained entirely within {@link #filterResults}. 12707 */ 12708 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12709 12710 @Override 12711 protected AuxiliaryResolveInfo[] newArray(int size) { 12712 return new AuxiliaryResolveInfo[size]; 12713 } 12714 12715 @Override 12716 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12717 return true; 12718 } 12719 12720 @Override 12721 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12722 int userId) { 12723 if (!sUserManager.exists(userId)) { 12724 return null; 12725 } 12726 final String packageName = responseObj.resolveInfo.getPackageName(); 12727 final Integer order = responseObj.getOrder(); 12728 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12729 mOrderResult.get(packageName); 12730 // ordering is enabled and this item's order isn't high enough 12731 if (lastOrderResult != null && lastOrderResult.first >= order) { 12732 return null; 12733 } 12734 final InstantAppResolveInfo res = responseObj.resolveInfo; 12735 if (order > 0) { 12736 // non-zero order, enable ordering 12737 mOrderResult.put(packageName, new Pair<>(order, res)); 12738 } 12739 return responseObj; 12740 } 12741 12742 @Override 12743 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12744 // only do work if ordering is enabled [most of the time it won't be] 12745 if (mOrderResult.size() == 0) { 12746 return; 12747 } 12748 int resultSize = results.size(); 12749 for (int i = 0; i < resultSize; i++) { 12750 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12751 final String packageName = info.getPackageName(); 12752 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12753 if (savedInfo == null) { 12754 // package doesn't having ordering 12755 continue; 12756 } 12757 if (savedInfo.second == info) { 12758 // circled back to the highest ordered item; remove from order list 12759 mOrderResult.remove(savedInfo); 12760 if (mOrderResult.size() == 0) { 12761 // no more ordered items 12762 break; 12763 } 12764 continue; 12765 } 12766 // item has a worse order, remove it from the result list 12767 results.remove(i); 12768 resultSize--; 12769 i--; 12770 } 12771 } 12772 } 12773 12774 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12775 new Comparator<ResolveInfo>() { 12776 public int compare(ResolveInfo r1, ResolveInfo r2) { 12777 int v1 = r1.priority; 12778 int v2 = r2.priority; 12779 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12780 if (v1 != v2) { 12781 return (v1 > v2) ? -1 : 1; 12782 } 12783 v1 = r1.preferredOrder; 12784 v2 = r2.preferredOrder; 12785 if (v1 != v2) { 12786 return (v1 > v2) ? -1 : 1; 12787 } 12788 if (r1.isDefault != r2.isDefault) { 12789 return r1.isDefault ? -1 : 1; 12790 } 12791 v1 = r1.match; 12792 v2 = r2.match; 12793 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12794 if (v1 != v2) { 12795 return (v1 > v2) ? -1 : 1; 12796 } 12797 if (r1.system != r2.system) { 12798 return r1.system ? -1 : 1; 12799 } 12800 if (r1.activityInfo != null) { 12801 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12802 } 12803 if (r1.serviceInfo != null) { 12804 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12805 } 12806 if (r1.providerInfo != null) { 12807 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12808 } 12809 return 0; 12810 } 12811 }; 12812 12813 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12814 new Comparator<ProviderInfo>() { 12815 public int compare(ProviderInfo p1, ProviderInfo p2) { 12816 final int v1 = p1.initOrder; 12817 final int v2 = p2.initOrder; 12818 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12819 } 12820 }; 12821 12822 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12823 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12824 final int[] userIds) { 12825 mHandler.post(new Runnable() { 12826 @Override 12827 public void run() { 12828 try { 12829 final IActivityManager am = ActivityManager.getService(); 12830 if (am == null) return; 12831 final int[] resolvedUserIds; 12832 if (userIds == null) { 12833 resolvedUserIds = am.getRunningUserIds(); 12834 } else { 12835 resolvedUserIds = userIds; 12836 } 12837 for (int id : resolvedUserIds) { 12838 final Intent intent = new Intent(action, 12839 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12840 if (extras != null) { 12841 intent.putExtras(extras); 12842 } 12843 if (targetPkg != null) { 12844 intent.setPackage(targetPkg); 12845 } 12846 // Modify the UID when posting to other users 12847 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12848 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12849 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12850 intent.putExtra(Intent.EXTRA_UID, uid); 12851 } 12852 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12853 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12854 if (DEBUG_BROADCASTS) { 12855 RuntimeException here = new RuntimeException("here"); 12856 here.fillInStackTrace(); 12857 Slog.d(TAG, "Sending to user " + id + ": " 12858 + intent.toShortString(false, true, false, false) 12859 + " " + intent.getExtras(), here); 12860 } 12861 am.broadcastIntent(null, intent, null, finishedReceiver, 12862 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12863 null, finishedReceiver != null, false, id); 12864 } 12865 } catch (RemoteException ex) { 12866 } 12867 } 12868 }); 12869 } 12870 12871 /** 12872 * Check if the external storage media is available. This is true if there 12873 * is a mounted external storage medium or if the external storage is 12874 * emulated. 12875 */ 12876 private boolean isExternalMediaAvailable() { 12877 return mMediaMounted || Environment.isExternalStorageEmulated(); 12878 } 12879 12880 @Override 12881 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 12882 // writer 12883 synchronized (mPackages) { 12884 if (!isExternalMediaAvailable()) { 12885 // If the external storage is no longer mounted at this point, 12886 // the caller may not have been able to delete all of this 12887 // packages files and can not delete any more. Bail. 12888 return null; 12889 } 12890 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 12891 if (lastPackage != null) { 12892 pkgs.remove(lastPackage); 12893 } 12894 if (pkgs.size() > 0) { 12895 return pkgs.get(0); 12896 } 12897 } 12898 return null; 12899 } 12900 12901 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 12902 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 12903 userId, andCode ? 1 : 0, packageName); 12904 if (mSystemReady) { 12905 msg.sendToTarget(); 12906 } else { 12907 if (mPostSystemReadyMessages == null) { 12908 mPostSystemReadyMessages = new ArrayList<>(); 12909 } 12910 mPostSystemReadyMessages.add(msg); 12911 } 12912 } 12913 12914 void startCleaningPackages() { 12915 // reader 12916 if (!isExternalMediaAvailable()) { 12917 return; 12918 } 12919 synchronized (mPackages) { 12920 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 12921 return; 12922 } 12923 } 12924 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 12925 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 12926 IActivityManager am = ActivityManager.getService(); 12927 if (am != null) { 12928 try { 12929 am.startService(null, intent, null, -1, null, mContext.getOpPackageName(), 12930 UserHandle.USER_SYSTEM); 12931 } catch (RemoteException e) { 12932 } 12933 } 12934 } 12935 12936 @Override 12937 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 12938 int installFlags, String installerPackageName, int userId) { 12939 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 12940 12941 final int callingUid = Binder.getCallingUid(); 12942 enforceCrossUserPermission(callingUid, userId, 12943 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 12944 12945 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12946 try { 12947 if (observer != null) { 12948 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 12949 } 12950 } catch (RemoteException re) { 12951 } 12952 return; 12953 } 12954 12955 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 12956 installFlags |= PackageManager.INSTALL_FROM_ADB; 12957 12958 } else { 12959 // Caller holds INSTALL_PACKAGES permission, so we're less strict 12960 // about installerPackageName. 12961 12962 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 12963 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 12964 } 12965 12966 UserHandle user; 12967 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 12968 user = UserHandle.ALL; 12969 } else { 12970 user = new UserHandle(userId); 12971 } 12972 12973 // Only system components can circumvent runtime permissions when installing. 12974 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 12975 && mContext.checkCallingOrSelfPermission(Manifest.permission 12976 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 12977 throw new SecurityException("You need the " 12978 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 12979 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 12980 } 12981 12982 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 12983 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12984 throw new IllegalArgumentException( 12985 "New installs into ASEC containers no longer supported"); 12986 } 12987 12988 final File originFile = new File(originPath); 12989 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 12990 12991 final Message msg = mHandler.obtainMessage(INIT_COPY); 12992 final VerificationInfo verificationInfo = new VerificationInfo( 12993 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 12994 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 12995 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 12996 null /*packageAbiOverride*/, null /*grantedPermissions*/, 12997 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 12998 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 12999 msg.obj = params; 13000 13001 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13002 System.identityHashCode(msg.obj)); 13003 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13004 System.identityHashCode(msg.obj)); 13005 13006 mHandler.sendMessage(msg); 13007 } 13008 13009 13010 /** 13011 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13012 * it is acting on behalf on an enterprise or the user). 13013 * 13014 * Note that the ordering of the conditionals in this method is important. The checks we perform 13015 * are as follows, in this order: 13016 * 13017 * 1) If the install is being performed by a system app, we can trust the app to have set the 13018 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13019 * what it is. 13020 * 2) If the install is being performed by a device or profile owner app, the install reason 13021 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13022 * set the install reason correctly. If the app targets an older SDK version where install 13023 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13024 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13025 * 3) In all other cases, the install is being performed by a regular app that is neither part 13026 * of the system nor a device or profile owner. We have no reason to believe that this app is 13027 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13028 * set to enterprise policy and if so, change it to unknown instead. 13029 */ 13030 private int fixUpInstallReason(String installerPackageName, int installerUid, 13031 int installReason) { 13032 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13033 == PERMISSION_GRANTED) { 13034 // If the install is being performed by a system app, we trust that app to have set the 13035 // install reason correctly. 13036 return installReason; 13037 } 13038 13039 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13040 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13041 if (dpm != null) { 13042 ComponentName owner = null; 13043 try { 13044 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13045 if (owner == null) { 13046 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13047 } 13048 } catch (RemoteException e) { 13049 } 13050 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13051 // If the install is being performed by a device or profile owner, the install 13052 // reason should be enterprise policy. 13053 return PackageManager.INSTALL_REASON_POLICY; 13054 } 13055 } 13056 13057 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13058 // If the install is being performed by a regular app (i.e. neither system app nor 13059 // device or profile owner), we have no reason to believe that the app is acting on 13060 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13061 // change it to unknown instead. 13062 return PackageManager.INSTALL_REASON_UNKNOWN; 13063 } 13064 13065 // If the install is being performed by a regular app and the install reason was set to any 13066 // value but enterprise policy, leave the install reason unchanged. 13067 return installReason; 13068 } 13069 13070 void installStage(String packageName, File stagedDir, String stagedCid, 13071 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13072 String installerPackageName, int installerUid, UserHandle user, 13073 Certificate[][] certificates) { 13074 if (DEBUG_EPHEMERAL) { 13075 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13076 Slog.d(TAG, "Ephemeral install of " + packageName); 13077 } 13078 } 13079 final VerificationInfo verificationInfo = new VerificationInfo( 13080 sessionParams.originatingUri, sessionParams.referrerUri, 13081 sessionParams.originatingUid, installerUid); 13082 13083 final OriginInfo origin; 13084 if (stagedDir != null) { 13085 origin = OriginInfo.fromStagedFile(stagedDir); 13086 } else { 13087 origin = OriginInfo.fromStagedContainer(stagedCid); 13088 } 13089 13090 final Message msg = mHandler.obtainMessage(INIT_COPY); 13091 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13092 sessionParams.installReason); 13093 final InstallParams params = new InstallParams(origin, null, observer, 13094 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13095 verificationInfo, user, sessionParams.abiOverride, 13096 sessionParams.grantedRuntimePermissions, certificates, installReason); 13097 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13098 msg.obj = params; 13099 13100 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13101 System.identityHashCode(msg.obj)); 13102 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13103 System.identityHashCode(msg.obj)); 13104 13105 mHandler.sendMessage(msg); 13106 } 13107 13108 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13109 int userId) { 13110 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13111 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13112 } 13113 13114 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13115 int appId, int... userIds) { 13116 if (ArrayUtils.isEmpty(userIds)) { 13117 return; 13118 } 13119 Bundle extras = new Bundle(1); 13120 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13121 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13122 13123 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13124 packageName, extras, 0, null, null, userIds); 13125 if (isSystem) { 13126 mHandler.post(() -> { 13127 for (int userId : userIds) { 13128 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13129 } 13130 } 13131 ); 13132 } 13133 } 13134 13135 /** 13136 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13137 * automatically without needing an explicit launch. 13138 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13139 */ 13140 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13141 // If user is not running, the app didn't miss any broadcast 13142 if (!mUserManagerInternal.isUserRunning(userId)) { 13143 return; 13144 } 13145 final IActivityManager am = ActivityManager.getService(); 13146 try { 13147 // Deliver LOCKED_BOOT_COMPLETED first 13148 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13149 .setPackage(packageName); 13150 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13151 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13152 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13153 13154 // Deliver BOOT_COMPLETED only if user is unlocked 13155 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13156 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13157 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13158 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13159 } 13160 } catch (RemoteException e) { 13161 throw e.rethrowFromSystemServer(); 13162 } 13163 } 13164 13165 @Override 13166 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13167 int userId) { 13168 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13169 PackageSetting pkgSetting; 13170 final int uid = Binder.getCallingUid(); 13171 enforceCrossUserPermission(uid, userId, 13172 true /* requireFullPermission */, true /* checkShell */, 13173 "setApplicationHiddenSetting for user " + userId); 13174 13175 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13176 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13177 return false; 13178 } 13179 13180 long callingId = Binder.clearCallingIdentity(); 13181 try { 13182 boolean sendAdded = false; 13183 boolean sendRemoved = false; 13184 // writer 13185 synchronized (mPackages) { 13186 pkgSetting = mSettings.mPackages.get(packageName); 13187 if (pkgSetting == null) { 13188 return false; 13189 } 13190 // Do not allow "android" is being disabled 13191 if ("android".equals(packageName)) { 13192 Slog.w(TAG, "Cannot hide package: android"); 13193 return false; 13194 } 13195 // Cannot hide static shared libs as they are considered 13196 // a part of the using app (emulating static linking). Also 13197 // static libs are installed always on internal storage. 13198 PackageParser.Package pkg = mPackages.get(packageName); 13199 if (pkg != null && pkg.staticSharedLibName != null) { 13200 Slog.w(TAG, "Cannot hide package: " + packageName 13201 + " providing static shared library: " 13202 + pkg.staticSharedLibName); 13203 return false; 13204 } 13205 // Only allow protected packages to hide themselves. 13206 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13207 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13208 Slog.w(TAG, "Not hiding protected package: " + packageName); 13209 return false; 13210 } 13211 13212 if (pkgSetting.getHidden(userId) != hidden) { 13213 pkgSetting.setHidden(hidden, userId); 13214 mSettings.writePackageRestrictionsLPr(userId); 13215 if (hidden) { 13216 sendRemoved = true; 13217 } else { 13218 sendAdded = true; 13219 } 13220 } 13221 } 13222 if (sendAdded) { 13223 sendPackageAddedForUser(packageName, pkgSetting, userId); 13224 return true; 13225 } 13226 if (sendRemoved) { 13227 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13228 "hiding pkg"); 13229 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13230 return true; 13231 } 13232 } finally { 13233 Binder.restoreCallingIdentity(callingId); 13234 } 13235 return false; 13236 } 13237 13238 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13239 int userId) { 13240 final PackageRemovedInfo info = new PackageRemovedInfo(); 13241 info.removedPackage = packageName; 13242 info.removedUsers = new int[] {userId}; 13243 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13244 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13245 } 13246 13247 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13248 if (pkgList.length > 0) { 13249 Bundle extras = new Bundle(1); 13250 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13251 13252 sendPackageBroadcast( 13253 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13254 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13255 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13256 new int[] {userId}); 13257 } 13258 } 13259 13260 /** 13261 * Returns true if application is not found or there was an error. Otherwise it returns 13262 * the hidden state of the package for the given user. 13263 */ 13264 @Override 13265 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13266 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13267 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13268 true /* requireFullPermission */, false /* checkShell */, 13269 "getApplicationHidden for user " + userId); 13270 PackageSetting pkgSetting; 13271 long callingId = Binder.clearCallingIdentity(); 13272 try { 13273 // writer 13274 synchronized (mPackages) { 13275 pkgSetting = mSettings.mPackages.get(packageName); 13276 if (pkgSetting == null) { 13277 return true; 13278 } 13279 return pkgSetting.getHidden(userId); 13280 } 13281 } finally { 13282 Binder.restoreCallingIdentity(callingId); 13283 } 13284 } 13285 13286 /** 13287 * @hide 13288 */ 13289 @Override 13290 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13291 int installReason) { 13292 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13293 null); 13294 PackageSetting pkgSetting; 13295 final int uid = Binder.getCallingUid(); 13296 enforceCrossUserPermission(uid, userId, 13297 true /* requireFullPermission */, true /* checkShell */, 13298 "installExistingPackage for user " + userId); 13299 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13300 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13301 } 13302 13303 long callingId = Binder.clearCallingIdentity(); 13304 try { 13305 boolean installed = false; 13306 final boolean instantApp = 13307 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13308 final boolean fullApp = 13309 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13310 13311 // writer 13312 synchronized (mPackages) { 13313 pkgSetting = mSettings.mPackages.get(packageName); 13314 if (pkgSetting == null) { 13315 return PackageManager.INSTALL_FAILED_INVALID_URI; 13316 } 13317 if (!pkgSetting.getInstalled(userId)) { 13318 pkgSetting.setInstalled(true, userId); 13319 pkgSetting.setHidden(false, userId); 13320 pkgSetting.setInstallReason(installReason, userId); 13321 mSettings.writePackageRestrictionsLPr(userId); 13322 mSettings.writeKernelMappingLPr(pkgSetting); 13323 installed = true; 13324 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13325 // upgrade app from instant to full; we don't allow app downgrade 13326 installed = true; 13327 } 13328 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13329 } 13330 13331 if (installed) { 13332 if (pkgSetting.pkg != null) { 13333 synchronized (mInstallLock) { 13334 // We don't need to freeze for a brand new install 13335 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13336 } 13337 } 13338 sendPackageAddedForUser(packageName, pkgSetting, userId); 13339 synchronized (mPackages) { 13340 updateSequenceNumberLP(packageName, new int[]{ userId }); 13341 } 13342 } 13343 } finally { 13344 Binder.restoreCallingIdentity(callingId); 13345 } 13346 13347 return PackageManager.INSTALL_SUCCEEDED; 13348 } 13349 13350 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13351 boolean instantApp, boolean fullApp) { 13352 // no state specified; do nothing 13353 if (!instantApp && !fullApp) { 13354 return; 13355 } 13356 if (userId != UserHandle.USER_ALL) { 13357 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13358 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13359 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13360 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13361 } 13362 } else { 13363 for (int currentUserId : sUserManager.getUserIds()) { 13364 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13365 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13366 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13367 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13368 } 13369 } 13370 } 13371 } 13372 13373 boolean isUserRestricted(int userId, String restrictionKey) { 13374 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13375 if (restrictions.getBoolean(restrictionKey, false)) { 13376 Log.w(TAG, "User is restricted: " + restrictionKey); 13377 return true; 13378 } 13379 return false; 13380 } 13381 13382 @Override 13383 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13384 int userId) { 13385 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13386 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13387 true /* requireFullPermission */, true /* checkShell */, 13388 "setPackagesSuspended for user " + userId); 13389 13390 if (ArrayUtils.isEmpty(packageNames)) { 13391 return packageNames; 13392 } 13393 13394 // List of package names for whom the suspended state has changed. 13395 List<String> changedPackages = new ArrayList<>(packageNames.length); 13396 // List of package names for whom the suspended state is not set as requested in this 13397 // method. 13398 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13399 long callingId = Binder.clearCallingIdentity(); 13400 try { 13401 for (int i = 0; i < packageNames.length; i++) { 13402 String packageName = packageNames[i]; 13403 boolean changed = false; 13404 final int appId; 13405 synchronized (mPackages) { 13406 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13407 if (pkgSetting == null) { 13408 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13409 + "\". Skipping suspending/un-suspending."); 13410 unactionedPackages.add(packageName); 13411 continue; 13412 } 13413 appId = pkgSetting.appId; 13414 if (pkgSetting.getSuspended(userId) != suspended) { 13415 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13416 unactionedPackages.add(packageName); 13417 continue; 13418 } 13419 pkgSetting.setSuspended(suspended, userId); 13420 mSettings.writePackageRestrictionsLPr(userId); 13421 changed = true; 13422 changedPackages.add(packageName); 13423 } 13424 } 13425 13426 if (changed && suspended) { 13427 killApplication(packageName, UserHandle.getUid(userId, appId), 13428 "suspending package"); 13429 } 13430 } 13431 } finally { 13432 Binder.restoreCallingIdentity(callingId); 13433 } 13434 13435 if (!changedPackages.isEmpty()) { 13436 sendPackagesSuspendedForUser(changedPackages.toArray( 13437 new String[changedPackages.size()]), userId, suspended); 13438 } 13439 13440 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13441 } 13442 13443 @Override 13444 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13445 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13446 true /* requireFullPermission */, false /* checkShell */, 13447 "isPackageSuspendedForUser for user " + userId); 13448 synchronized (mPackages) { 13449 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13450 if (pkgSetting == null) { 13451 throw new IllegalArgumentException("Unknown target package: " + packageName); 13452 } 13453 return pkgSetting.getSuspended(userId); 13454 } 13455 } 13456 13457 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13458 if (isPackageDeviceAdmin(packageName, userId)) { 13459 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13460 + "\": has an active device admin"); 13461 return false; 13462 } 13463 13464 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13465 if (packageName.equals(activeLauncherPackageName)) { 13466 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13467 + "\": contains the active launcher"); 13468 return false; 13469 } 13470 13471 if (packageName.equals(mRequiredInstallerPackage)) { 13472 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13473 + "\": required for package installation"); 13474 return false; 13475 } 13476 13477 if (packageName.equals(mRequiredUninstallerPackage)) { 13478 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13479 + "\": required for package uninstallation"); 13480 return false; 13481 } 13482 13483 if (packageName.equals(mRequiredVerifierPackage)) { 13484 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13485 + "\": required for package verification"); 13486 return false; 13487 } 13488 13489 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13490 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13491 + "\": is the default dialer"); 13492 return false; 13493 } 13494 13495 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13496 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13497 + "\": protected package"); 13498 return false; 13499 } 13500 13501 // Cannot suspend static shared libs as they are considered 13502 // a part of the using app (emulating static linking). Also 13503 // static libs are installed always on internal storage. 13504 PackageParser.Package pkg = mPackages.get(packageName); 13505 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13506 Slog.w(TAG, "Cannot suspend package: " + packageName 13507 + " providing static shared library: " 13508 + pkg.staticSharedLibName); 13509 return false; 13510 } 13511 13512 return true; 13513 } 13514 13515 private String getActiveLauncherPackageName(int userId) { 13516 Intent intent = new Intent(Intent.ACTION_MAIN); 13517 intent.addCategory(Intent.CATEGORY_HOME); 13518 ResolveInfo resolveInfo = resolveIntent( 13519 intent, 13520 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13521 PackageManager.MATCH_DEFAULT_ONLY, 13522 userId); 13523 13524 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13525 } 13526 13527 private String getDefaultDialerPackageName(int userId) { 13528 synchronized (mPackages) { 13529 return mSettings.getDefaultDialerPackageNameLPw(userId); 13530 } 13531 } 13532 13533 @Override 13534 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13535 mContext.enforceCallingOrSelfPermission( 13536 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13537 "Only package verification agents can verify applications"); 13538 13539 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13540 final PackageVerificationResponse response = new PackageVerificationResponse( 13541 verificationCode, Binder.getCallingUid()); 13542 msg.arg1 = id; 13543 msg.obj = response; 13544 mHandler.sendMessage(msg); 13545 } 13546 13547 @Override 13548 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13549 long millisecondsToDelay) { 13550 mContext.enforceCallingOrSelfPermission( 13551 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13552 "Only package verification agents can extend verification timeouts"); 13553 13554 final PackageVerificationState state = mPendingVerification.get(id); 13555 final PackageVerificationResponse response = new PackageVerificationResponse( 13556 verificationCodeAtTimeout, Binder.getCallingUid()); 13557 13558 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13559 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13560 } 13561 if (millisecondsToDelay < 0) { 13562 millisecondsToDelay = 0; 13563 } 13564 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13565 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13566 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13567 } 13568 13569 if ((state != null) && !state.timeoutExtended()) { 13570 state.extendTimeout(); 13571 13572 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13573 msg.arg1 = id; 13574 msg.obj = response; 13575 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13576 } 13577 } 13578 13579 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13580 int verificationCode, UserHandle user) { 13581 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13582 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13583 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13584 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13585 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13586 13587 mContext.sendBroadcastAsUser(intent, user, 13588 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13589 } 13590 13591 private ComponentName matchComponentForVerifier(String packageName, 13592 List<ResolveInfo> receivers) { 13593 ActivityInfo targetReceiver = null; 13594 13595 final int NR = receivers.size(); 13596 for (int i = 0; i < NR; i++) { 13597 final ResolveInfo info = receivers.get(i); 13598 if (info.activityInfo == null) { 13599 continue; 13600 } 13601 13602 if (packageName.equals(info.activityInfo.packageName)) { 13603 targetReceiver = info.activityInfo; 13604 break; 13605 } 13606 } 13607 13608 if (targetReceiver == null) { 13609 return null; 13610 } 13611 13612 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13613 } 13614 13615 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13616 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13617 if (pkgInfo.verifiers.length == 0) { 13618 return null; 13619 } 13620 13621 final int N = pkgInfo.verifiers.length; 13622 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13623 for (int i = 0; i < N; i++) { 13624 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13625 13626 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13627 receivers); 13628 if (comp == null) { 13629 continue; 13630 } 13631 13632 final int verifierUid = getUidForVerifier(verifierInfo); 13633 if (verifierUid == -1) { 13634 continue; 13635 } 13636 13637 if (DEBUG_VERIFY) { 13638 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13639 + " with the correct signature"); 13640 } 13641 sufficientVerifiers.add(comp); 13642 verificationState.addSufficientVerifier(verifierUid); 13643 } 13644 13645 return sufficientVerifiers; 13646 } 13647 13648 private int getUidForVerifier(VerifierInfo verifierInfo) { 13649 synchronized (mPackages) { 13650 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13651 if (pkg == null) { 13652 return -1; 13653 } else if (pkg.mSignatures.length != 1) { 13654 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13655 + " has more than one signature; ignoring"); 13656 return -1; 13657 } 13658 13659 /* 13660 * If the public key of the package's signature does not match 13661 * our expected public key, then this is a different package and 13662 * we should skip. 13663 */ 13664 13665 final byte[] expectedPublicKey; 13666 try { 13667 final Signature verifierSig = pkg.mSignatures[0]; 13668 final PublicKey publicKey = verifierSig.getPublicKey(); 13669 expectedPublicKey = publicKey.getEncoded(); 13670 } catch (CertificateException e) { 13671 return -1; 13672 } 13673 13674 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13675 13676 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13677 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13678 + " does not have the expected public key; ignoring"); 13679 return -1; 13680 } 13681 13682 return pkg.applicationInfo.uid; 13683 } 13684 } 13685 13686 @Override 13687 public void finishPackageInstall(int token, boolean didLaunch) { 13688 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13689 13690 if (DEBUG_INSTALL) { 13691 Slog.v(TAG, "BM finishing package install for " + token); 13692 } 13693 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13694 13695 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13696 mHandler.sendMessage(msg); 13697 } 13698 13699 /** 13700 * Get the verification agent timeout. 13701 * 13702 * @return verification timeout in milliseconds 13703 */ 13704 private long getVerificationTimeout() { 13705 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13706 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13707 DEFAULT_VERIFICATION_TIMEOUT); 13708 } 13709 13710 /** 13711 * Get the default verification agent response code. 13712 * 13713 * @return default verification response code 13714 */ 13715 private int getDefaultVerificationResponse() { 13716 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13717 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13718 DEFAULT_VERIFICATION_RESPONSE); 13719 } 13720 13721 /** 13722 * Check whether or not package verification has been enabled. 13723 * 13724 * @return true if verification should be performed 13725 */ 13726 private boolean isVerificationEnabled(int userId, int installFlags) { 13727 if (!DEFAULT_VERIFY_ENABLE) { 13728 return false; 13729 } 13730 13731 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13732 13733 // Check if installing from ADB 13734 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13735 // Do not run verification in a test harness environment 13736 if (ActivityManager.isRunningInTestHarness()) { 13737 return false; 13738 } 13739 if (ensureVerifyAppsEnabled) { 13740 return true; 13741 } 13742 // Check if the developer does not want package verification for ADB installs 13743 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13744 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13745 return false; 13746 } 13747 } 13748 13749 if (ensureVerifyAppsEnabled) { 13750 return true; 13751 } 13752 13753 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13754 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13755 } 13756 13757 @Override 13758 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13759 throws RemoteException { 13760 mContext.enforceCallingOrSelfPermission( 13761 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13762 "Only intentfilter verification agents can verify applications"); 13763 13764 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13765 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13766 Binder.getCallingUid(), verificationCode, failedDomains); 13767 msg.arg1 = id; 13768 msg.obj = response; 13769 mHandler.sendMessage(msg); 13770 } 13771 13772 @Override 13773 public int getIntentVerificationStatus(String packageName, int userId) { 13774 synchronized (mPackages) { 13775 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13776 } 13777 } 13778 13779 @Override 13780 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13781 mContext.enforceCallingOrSelfPermission( 13782 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13783 13784 boolean result = false; 13785 synchronized (mPackages) { 13786 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13787 } 13788 if (result) { 13789 scheduleWritePackageRestrictionsLocked(userId); 13790 } 13791 return result; 13792 } 13793 13794 @Override 13795 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13796 String packageName) { 13797 synchronized (mPackages) { 13798 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13799 } 13800 } 13801 13802 @Override 13803 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13804 if (TextUtils.isEmpty(packageName)) { 13805 return ParceledListSlice.emptyList(); 13806 } 13807 synchronized (mPackages) { 13808 PackageParser.Package pkg = mPackages.get(packageName); 13809 if (pkg == null || pkg.activities == null) { 13810 return ParceledListSlice.emptyList(); 13811 } 13812 final int count = pkg.activities.size(); 13813 ArrayList<IntentFilter> result = new ArrayList<>(); 13814 for (int n=0; n<count; n++) { 13815 PackageParser.Activity activity = pkg.activities.get(n); 13816 if (activity.intents != null && activity.intents.size() > 0) { 13817 result.addAll(activity.intents); 13818 } 13819 } 13820 return new ParceledListSlice<>(result); 13821 } 13822 } 13823 13824 @Override 13825 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13826 mContext.enforceCallingOrSelfPermission( 13827 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13828 13829 synchronized (mPackages) { 13830 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13831 if (packageName != null) { 13832 result |= updateIntentVerificationStatus(packageName, 13833 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13834 userId); 13835 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13836 packageName, userId); 13837 } 13838 return result; 13839 } 13840 } 13841 13842 @Override 13843 public String getDefaultBrowserPackageName(int userId) { 13844 synchronized (mPackages) { 13845 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13846 } 13847 } 13848 13849 /** 13850 * Get the "allow unknown sources" setting. 13851 * 13852 * @return the current "allow unknown sources" setting 13853 */ 13854 private int getUnknownSourcesSettings() { 13855 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13856 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13857 -1); 13858 } 13859 13860 @Override 13861 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13862 final int uid = Binder.getCallingUid(); 13863 // writer 13864 synchronized (mPackages) { 13865 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13866 if (targetPackageSetting == null) { 13867 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 13868 } 13869 13870 PackageSetting installerPackageSetting; 13871 if (installerPackageName != null) { 13872 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 13873 if (installerPackageSetting == null) { 13874 throw new IllegalArgumentException("Unknown installer package: " 13875 + installerPackageName); 13876 } 13877 } else { 13878 installerPackageSetting = null; 13879 } 13880 13881 Signature[] callerSignature; 13882 Object obj = mSettings.getUserIdLPr(uid); 13883 if (obj != null) { 13884 if (obj instanceof SharedUserSetting) { 13885 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 13886 } else if (obj instanceof PackageSetting) { 13887 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 13888 } else { 13889 throw new SecurityException("Bad object " + obj + " for uid " + uid); 13890 } 13891 } else { 13892 throw new SecurityException("Unknown calling UID: " + uid); 13893 } 13894 13895 // Verify: can't set installerPackageName to a package that is 13896 // not signed with the same cert as the caller. 13897 if (installerPackageSetting != null) { 13898 if (compareSignatures(callerSignature, 13899 installerPackageSetting.signatures.mSignatures) 13900 != PackageManager.SIGNATURE_MATCH) { 13901 throw new SecurityException( 13902 "Caller does not have same cert as new installer package " 13903 + installerPackageName); 13904 } 13905 } 13906 13907 // Verify: if target already has an installer package, it must 13908 // be signed with the same cert as the caller. 13909 if (targetPackageSetting.installerPackageName != null) { 13910 PackageSetting setting = mSettings.mPackages.get( 13911 targetPackageSetting.installerPackageName); 13912 // If the currently set package isn't valid, then it's always 13913 // okay to change it. 13914 if (setting != null) { 13915 if (compareSignatures(callerSignature, 13916 setting.signatures.mSignatures) 13917 != PackageManager.SIGNATURE_MATCH) { 13918 throw new SecurityException( 13919 "Caller does not have same cert as old installer package " 13920 + targetPackageSetting.installerPackageName); 13921 } 13922 } 13923 } 13924 13925 // Okay! 13926 targetPackageSetting.installerPackageName = installerPackageName; 13927 if (installerPackageName != null) { 13928 mSettings.mInstallerPackages.add(installerPackageName); 13929 } 13930 scheduleWriteSettingsLocked(); 13931 } 13932 } 13933 13934 @Override 13935 public void setApplicationCategoryHint(String packageName, int categoryHint, 13936 String callerPackageName) { 13937 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 13938 callerPackageName); 13939 synchronized (mPackages) { 13940 PackageSetting ps = mSettings.mPackages.get(packageName); 13941 if (ps == null) { 13942 throw new IllegalArgumentException("Unknown target package " + packageName); 13943 } 13944 13945 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 13946 throw new IllegalArgumentException("Calling package " + callerPackageName 13947 + " is not installer for " + packageName); 13948 } 13949 13950 if (ps.categoryHint != categoryHint) { 13951 ps.categoryHint = categoryHint; 13952 scheduleWriteSettingsLocked(); 13953 } 13954 } 13955 } 13956 13957 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 13958 // Queue up an async operation since the package installation may take a little while. 13959 mHandler.post(new Runnable() { 13960 public void run() { 13961 mHandler.removeCallbacks(this); 13962 // Result object to be returned 13963 PackageInstalledInfo res = new PackageInstalledInfo(); 13964 res.setReturnCode(currentStatus); 13965 res.uid = -1; 13966 res.pkg = null; 13967 res.removedInfo = null; 13968 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13969 args.doPreInstall(res.returnCode); 13970 synchronized (mInstallLock) { 13971 installPackageTracedLI(args, res); 13972 } 13973 args.doPostInstall(res.returnCode, res.uid); 13974 } 13975 13976 // A restore should be performed at this point if (a) the install 13977 // succeeded, (b) the operation is not an update, and (c) the new 13978 // package has not opted out of backup participation. 13979 final boolean update = res.removedInfo != null 13980 && res.removedInfo.removedPackage != null; 13981 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 13982 boolean doRestore = !update 13983 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 13984 13985 // Set up the post-install work request bookkeeping. This will be used 13986 // and cleaned up by the post-install event handling regardless of whether 13987 // there's a restore pass performed. Token values are >= 1. 13988 int token; 13989 if (mNextInstallToken < 0) mNextInstallToken = 1; 13990 token = mNextInstallToken++; 13991 13992 PostInstallData data = new PostInstallData(args, res); 13993 mRunningInstalls.put(token, data); 13994 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 13995 13996 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 13997 // Pass responsibility to the Backup Manager. It will perform a 13998 // restore if appropriate, then pass responsibility back to the 13999 // Package Manager to run the post-install observer callbacks 14000 // and broadcasts. 14001 IBackupManager bm = IBackupManager.Stub.asInterface( 14002 ServiceManager.getService(Context.BACKUP_SERVICE)); 14003 if (bm != null) { 14004 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14005 + " to BM for possible restore"); 14006 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14007 try { 14008 // TODO: http://b/22388012 14009 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14010 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14011 } else { 14012 doRestore = false; 14013 } 14014 } catch (RemoteException e) { 14015 // can't happen; the backup manager is local 14016 } catch (Exception e) { 14017 Slog.e(TAG, "Exception trying to enqueue restore", e); 14018 doRestore = false; 14019 } 14020 } else { 14021 Slog.e(TAG, "Backup Manager not found!"); 14022 doRestore = false; 14023 } 14024 } 14025 14026 if (!doRestore) { 14027 // No restore possible, or the Backup Manager was mysteriously not 14028 // available -- just fire the post-install work request directly. 14029 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14030 14031 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14032 14033 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14034 mHandler.sendMessage(msg); 14035 } 14036 } 14037 }); 14038 } 14039 14040 /** 14041 * Callback from PackageSettings whenever an app is first transitioned out of the 14042 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14043 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14044 * here whether the app is the target of an ongoing install, and only send the 14045 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14046 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14047 * handling. 14048 */ 14049 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14050 // Serialize this with the rest of the install-process message chain. In the 14051 // restore-at-install case, this Runnable will necessarily run before the 14052 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14053 // are coherent. In the non-restore case, the app has already completed install 14054 // and been launched through some other means, so it is not in a problematic 14055 // state for observers to see the FIRST_LAUNCH signal. 14056 mHandler.post(new Runnable() { 14057 @Override 14058 public void run() { 14059 for (int i = 0; i < mRunningInstalls.size(); i++) { 14060 final PostInstallData data = mRunningInstalls.valueAt(i); 14061 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14062 continue; 14063 } 14064 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14065 // right package; but is it for the right user? 14066 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14067 if (userId == data.res.newUsers[uIndex]) { 14068 if (DEBUG_BACKUP) { 14069 Slog.i(TAG, "Package " + pkgName 14070 + " being restored so deferring FIRST_LAUNCH"); 14071 } 14072 return; 14073 } 14074 } 14075 } 14076 } 14077 // didn't find it, so not being restored 14078 if (DEBUG_BACKUP) { 14079 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14080 } 14081 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14082 } 14083 }); 14084 } 14085 14086 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14087 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14088 installerPkg, null, userIds); 14089 } 14090 14091 private abstract class HandlerParams { 14092 private static final int MAX_RETRIES = 4; 14093 14094 /** 14095 * Number of times startCopy() has been attempted and had a non-fatal 14096 * error. 14097 */ 14098 private int mRetries = 0; 14099 14100 /** User handle for the user requesting the information or installation. */ 14101 private final UserHandle mUser; 14102 String traceMethod; 14103 int traceCookie; 14104 14105 HandlerParams(UserHandle user) { 14106 mUser = user; 14107 } 14108 14109 UserHandle getUser() { 14110 return mUser; 14111 } 14112 14113 HandlerParams setTraceMethod(String traceMethod) { 14114 this.traceMethod = traceMethod; 14115 return this; 14116 } 14117 14118 HandlerParams setTraceCookie(int traceCookie) { 14119 this.traceCookie = traceCookie; 14120 return this; 14121 } 14122 14123 final boolean startCopy() { 14124 boolean res; 14125 try { 14126 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14127 14128 if (++mRetries > MAX_RETRIES) { 14129 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14130 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14131 handleServiceError(); 14132 return false; 14133 } else { 14134 handleStartCopy(); 14135 res = true; 14136 } 14137 } catch (RemoteException e) { 14138 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14139 mHandler.sendEmptyMessage(MCS_RECONNECT); 14140 res = false; 14141 } 14142 handleReturnCode(); 14143 return res; 14144 } 14145 14146 final void serviceError() { 14147 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14148 handleServiceError(); 14149 handleReturnCode(); 14150 } 14151 14152 abstract void handleStartCopy() throws RemoteException; 14153 abstract void handleServiceError(); 14154 abstract void handleReturnCode(); 14155 } 14156 14157 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14158 for (File path : paths) { 14159 try { 14160 mcs.clearDirectory(path.getAbsolutePath()); 14161 } catch (RemoteException e) { 14162 } 14163 } 14164 } 14165 14166 static class OriginInfo { 14167 /** 14168 * Location where install is coming from, before it has been 14169 * copied/renamed into place. This could be a single monolithic APK 14170 * file, or a cluster directory. This location may be untrusted. 14171 */ 14172 final File file; 14173 final String cid; 14174 14175 /** 14176 * Flag indicating that {@link #file} or {@link #cid} has already been 14177 * staged, meaning downstream users don't need to defensively copy the 14178 * contents. 14179 */ 14180 final boolean staged; 14181 14182 /** 14183 * Flag indicating that {@link #file} or {@link #cid} is an already 14184 * installed app that is being moved. 14185 */ 14186 final boolean existing; 14187 14188 final String resolvedPath; 14189 final File resolvedFile; 14190 14191 static OriginInfo fromNothing() { 14192 return new OriginInfo(null, null, false, false); 14193 } 14194 14195 static OriginInfo fromUntrustedFile(File file) { 14196 return new OriginInfo(file, null, false, false); 14197 } 14198 14199 static OriginInfo fromExistingFile(File file) { 14200 return new OriginInfo(file, null, false, true); 14201 } 14202 14203 static OriginInfo fromStagedFile(File file) { 14204 return new OriginInfo(file, null, true, false); 14205 } 14206 14207 static OriginInfo fromStagedContainer(String cid) { 14208 return new OriginInfo(null, cid, true, false); 14209 } 14210 14211 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14212 this.file = file; 14213 this.cid = cid; 14214 this.staged = staged; 14215 this.existing = existing; 14216 14217 if (cid != null) { 14218 resolvedPath = PackageHelper.getSdDir(cid); 14219 resolvedFile = new File(resolvedPath); 14220 } else if (file != null) { 14221 resolvedPath = file.getAbsolutePath(); 14222 resolvedFile = file; 14223 } else { 14224 resolvedPath = null; 14225 resolvedFile = null; 14226 } 14227 } 14228 } 14229 14230 static class MoveInfo { 14231 final int moveId; 14232 final String fromUuid; 14233 final String toUuid; 14234 final String packageName; 14235 final String dataAppName; 14236 final int appId; 14237 final String seinfo; 14238 final int targetSdkVersion; 14239 14240 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14241 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14242 this.moveId = moveId; 14243 this.fromUuid = fromUuid; 14244 this.toUuid = toUuid; 14245 this.packageName = packageName; 14246 this.dataAppName = dataAppName; 14247 this.appId = appId; 14248 this.seinfo = seinfo; 14249 this.targetSdkVersion = targetSdkVersion; 14250 } 14251 } 14252 14253 static class VerificationInfo { 14254 /** A constant used to indicate that a uid value is not present. */ 14255 public static final int NO_UID = -1; 14256 14257 /** URI referencing where the package was downloaded from. */ 14258 final Uri originatingUri; 14259 14260 /** HTTP referrer URI associated with the originatingURI. */ 14261 final Uri referrer; 14262 14263 /** UID of the application that the install request originated from. */ 14264 final int originatingUid; 14265 14266 /** UID of application requesting the install */ 14267 final int installerUid; 14268 14269 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14270 this.originatingUri = originatingUri; 14271 this.referrer = referrer; 14272 this.originatingUid = originatingUid; 14273 this.installerUid = installerUid; 14274 } 14275 } 14276 14277 class InstallParams extends HandlerParams { 14278 final OriginInfo origin; 14279 final MoveInfo move; 14280 final IPackageInstallObserver2 observer; 14281 int installFlags; 14282 final String installerPackageName; 14283 final String volumeUuid; 14284 private InstallArgs mArgs; 14285 private int mRet; 14286 final String packageAbiOverride; 14287 final String[] grantedRuntimePermissions; 14288 final VerificationInfo verificationInfo; 14289 final Certificate[][] certificates; 14290 final int installReason; 14291 14292 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14293 int installFlags, String installerPackageName, String volumeUuid, 14294 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14295 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14296 super(user); 14297 this.origin = origin; 14298 this.move = move; 14299 this.observer = observer; 14300 this.installFlags = installFlags; 14301 this.installerPackageName = installerPackageName; 14302 this.volumeUuid = volumeUuid; 14303 this.verificationInfo = verificationInfo; 14304 this.packageAbiOverride = packageAbiOverride; 14305 this.grantedRuntimePermissions = grantedPermissions; 14306 this.certificates = certificates; 14307 this.installReason = installReason; 14308 } 14309 14310 @Override 14311 public String toString() { 14312 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14313 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14314 } 14315 14316 private int installLocationPolicy(PackageInfoLite pkgLite) { 14317 String packageName = pkgLite.packageName; 14318 int installLocation = pkgLite.installLocation; 14319 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14320 // reader 14321 synchronized (mPackages) { 14322 // Currently installed package which the new package is attempting to replace or 14323 // null if no such package is installed. 14324 PackageParser.Package installedPkg = mPackages.get(packageName); 14325 // Package which currently owns the data which the new package will own if installed. 14326 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14327 // will be null whereas dataOwnerPkg will contain information about the package 14328 // which was uninstalled while keeping its data. 14329 PackageParser.Package dataOwnerPkg = installedPkg; 14330 if (dataOwnerPkg == null) { 14331 PackageSetting ps = mSettings.mPackages.get(packageName); 14332 if (ps != null) { 14333 dataOwnerPkg = ps.pkg; 14334 } 14335 } 14336 14337 if (dataOwnerPkg != null) { 14338 // If installed, the package will get access to data left on the device by its 14339 // predecessor. As a security measure, this is permited only if this is not a 14340 // version downgrade or if the predecessor package is marked as debuggable and 14341 // a downgrade is explicitly requested. 14342 // 14343 // On debuggable platform builds, downgrades are permitted even for 14344 // non-debuggable packages to make testing easier. Debuggable platform builds do 14345 // not offer security guarantees and thus it's OK to disable some security 14346 // mechanisms to make debugging/testing easier on those builds. However, even on 14347 // debuggable builds downgrades of packages are permitted only if requested via 14348 // installFlags. This is because we aim to keep the behavior of debuggable 14349 // platform builds as close as possible to the behavior of non-debuggable 14350 // platform builds. 14351 final boolean downgradeRequested = 14352 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14353 final boolean packageDebuggable = 14354 (dataOwnerPkg.applicationInfo.flags 14355 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14356 final boolean downgradePermitted = 14357 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14358 if (!downgradePermitted) { 14359 try { 14360 checkDowngrade(dataOwnerPkg, pkgLite); 14361 } catch (PackageManagerException e) { 14362 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14363 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14364 } 14365 } 14366 } 14367 14368 if (installedPkg != null) { 14369 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14370 // Check for updated system application. 14371 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14372 if (onSd) { 14373 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14374 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14375 } 14376 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14377 } else { 14378 if (onSd) { 14379 // Install flag overrides everything. 14380 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14381 } 14382 // If current upgrade specifies particular preference 14383 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14384 // Application explicitly specified internal. 14385 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14386 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14387 // App explictly prefers external. Let policy decide 14388 } else { 14389 // Prefer previous location 14390 if (isExternal(installedPkg)) { 14391 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14392 } 14393 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14394 } 14395 } 14396 } else { 14397 // Invalid install. Return error code 14398 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14399 } 14400 } 14401 } 14402 // All the special cases have been taken care of. 14403 // Return result based on recommended install location. 14404 if (onSd) { 14405 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14406 } 14407 return pkgLite.recommendedInstallLocation; 14408 } 14409 14410 /* 14411 * Invoke remote method to get package information and install 14412 * location values. Override install location based on default 14413 * policy if needed and then create install arguments based 14414 * on the install location. 14415 */ 14416 public void handleStartCopy() throws RemoteException { 14417 int ret = PackageManager.INSTALL_SUCCEEDED; 14418 14419 // If we're already staged, we've firmly committed to an install location 14420 if (origin.staged) { 14421 if (origin.file != null) { 14422 installFlags |= PackageManager.INSTALL_INTERNAL; 14423 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14424 } else if (origin.cid != null) { 14425 installFlags |= PackageManager.INSTALL_EXTERNAL; 14426 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14427 } else { 14428 throw new IllegalStateException("Invalid stage location"); 14429 } 14430 } 14431 14432 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14433 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14434 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14435 PackageInfoLite pkgLite = null; 14436 14437 if (onInt && onSd) { 14438 // Check if both bits are set. 14439 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14440 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14441 } else if (onSd && ephemeral) { 14442 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14443 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14444 } else { 14445 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14446 packageAbiOverride); 14447 14448 if (DEBUG_EPHEMERAL && ephemeral) { 14449 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14450 } 14451 14452 /* 14453 * If we have too little free space, try to free cache 14454 * before giving up. 14455 */ 14456 if (!origin.staged && pkgLite.recommendedInstallLocation 14457 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14458 // TODO: focus freeing disk space on the target device 14459 final StorageManager storage = StorageManager.from(mContext); 14460 final long lowThreshold = storage.getStorageLowBytes( 14461 Environment.getDataDirectory()); 14462 14463 final long sizeBytes = mContainerService.calculateInstalledSize( 14464 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14465 14466 try { 14467 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14468 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14469 installFlags, packageAbiOverride); 14470 } catch (InstallerException e) { 14471 Slog.w(TAG, "Failed to free cache", e); 14472 } 14473 14474 /* 14475 * The cache free must have deleted the file we 14476 * downloaded to install. 14477 * 14478 * TODO: fix the "freeCache" call to not delete 14479 * the file we care about. 14480 */ 14481 if (pkgLite.recommendedInstallLocation 14482 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14483 pkgLite.recommendedInstallLocation 14484 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14485 } 14486 } 14487 } 14488 14489 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14490 int loc = pkgLite.recommendedInstallLocation; 14491 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14492 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14493 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14494 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14495 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14496 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14497 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14498 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14499 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14500 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14501 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14502 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14503 } else { 14504 // Override with defaults if needed. 14505 loc = installLocationPolicy(pkgLite); 14506 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14507 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14508 } else if (!onSd && !onInt) { 14509 // Override install location with flags 14510 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14511 // Set the flag to install on external media. 14512 installFlags |= PackageManager.INSTALL_EXTERNAL; 14513 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14514 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14515 if (DEBUG_EPHEMERAL) { 14516 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14517 } 14518 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14519 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14520 |PackageManager.INSTALL_INTERNAL); 14521 } else { 14522 // Make sure the flag for installing on external 14523 // media is unset 14524 installFlags |= PackageManager.INSTALL_INTERNAL; 14525 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14526 } 14527 } 14528 } 14529 } 14530 14531 final InstallArgs args = createInstallArgs(this); 14532 mArgs = args; 14533 14534 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14535 // TODO: http://b/22976637 14536 // Apps installed for "all" users use the device owner to verify the app 14537 UserHandle verifierUser = getUser(); 14538 if (verifierUser == UserHandle.ALL) { 14539 verifierUser = UserHandle.SYSTEM; 14540 } 14541 14542 /* 14543 * Determine if we have any installed package verifiers. If we 14544 * do, then we'll defer to them to verify the packages. 14545 */ 14546 final int requiredUid = mRequiredVerifierPackage == null ? -1 14547 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14548 verifierUser.getIdentifier()); 14549 if (!origin.existing && requiredUid != -1 14550 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14551 final Intent verification = new Intent( 14552 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14553 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14554 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14555 PACKAGE_MIME_TYPE); 14556 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14557 14558 // Query all live verifiers based on current user state 14559 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14560 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14561 14562 if (DEBUG_VERIFY) { 14563 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14564 + verification.toString() + " with " + pkgLite.verifiers.length 14565 + " optional verifiers"); 14566 } 14567 14568 final int verificationId = mPendingVerificationToken++; 14569 14570 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14571 14572 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14573 installerPackageName); 14574 14575 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14576 installFlags); 14577 14578 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14579 pkgLite.packageName); 14580 14581 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14582 pkgLite.versionCode); 14583 14584 if (verificationInfo != null) { 14585 if (verificationInfo.originatingUri != null) { 14586 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14587 verificationInfo.originatingUri); 14588 } 14589 if (verificationInfo.referrer != null) { 14590 verification.putExtra(Intent.EXTRA_REFERRER, 14591 verificationInfo.referrer); 14592 } 14593 if (verificationInfo.originatingUid >= 0) { 14594 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14595 verificationInfo.originatingUid); 14596 } 14597 if (verificationInfo.installerUid >= 0) { 14598 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14599 verificationInfo.installerUid); 14600 } 14601 } 14602 14603 final PackageVerificationState verificationState = new PackageVerificationState( 14604 requiredUid, args); 14605 14606 mPendingVerification.append(verificationId, verificationState); 14607 14608 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14609 receivers, verificationState); 14610 14611 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14612 final long idleDuration = getVerificationTimeout(); 14613 14614 /* 14615 * If any sufficient verifiers were listed in the package 14616 * manifest, attempt to ask them. 14617 */ 14618 if (sufficientVerifiers != null) { 14619 final int N = sufficientVerifiers.size(); 14620 if (N == 0) { 14621 Slog.i(TAG, "Additional verifiers required, but none installed."); 14622 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14623 } else { 14624 for (int i = 0; i < N; i++) { 14625 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14626 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14627 verifierComponent.getPackageName(), idleDuration, 14628 verifierUser.getIdentifier(), false, "package verifier"); 14629 14630 final Intent sufficientIntent = new Intent(verification); 14631 sufficientIntent.setComponent(verifierComponent); 14632 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14633 } 14634 } 14635 } 14636 14637 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14638 mRequiredVerifierPackage, receivers); 14639 if (ret == PackageManager.INSTALL_SUCCEEDED 14640 && mRequiredVerifierPackage != null) { 14641 Trace.asyncTraceBegin( 14642 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14643 /* 14644 * Send the intent to the required verification agent, 14645 * but only start the verification timeout after the 14646 * target BroadcastReceivers have run. 14647 */ 14648 verification.setComponent(requiredVerifierComponent); 14649 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14650 mRequiredVerifierPackage, idleDuration, 14651 verifierUser.getIdentifier(), false, "package verifier"); 14652 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14653 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14654 new BroadcastReceiver() { 14655 @Override 14656 public void onReceive(Context context, Intent intent) { 14657 final Message msg = mHandler 14658 .obtainMessage(CHECK_PENDING_VERIFICATION); 14659 msg.arg1 = verificationId; 14660 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14661 } 14662 }, null, 0, null, null); 14663 14664 /* 14665 * We don't want the copy to proceed until verification 14666 * succeeds, so null out this field. 14667 */ 14668 mArgs = null; 14669 } 14670 } else { 14671 /* 14672 * No package verification is enabled, so immediately start 14673 * the remote call to initiate copy using temporary file. 14674 */ 14675 ret = args.copyApk(mContainerService, true); 14676 } 14677 } 14678 14679 mRet = ret; 14680 } 14681 14682 @Override 14683 void handleReturnCode() { 14684 // If mArgs is null, then MCS couldn't be reached. When it 14685 // reconnects, it will try again to install. At that point, this 14686 // will succeed. 14687 if (mArgs != null) { 14688 processPendingInstall(mArgs, mRet); 14689 } 14690 } 14691 14692 @Override 14693 void handleServiceError() { 14694 mArgs = createInstallArgs(this); 14695 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14696 } 14697 14698 public boolean isForwardLocked() { 14699 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14700 } 14701 } 14702 14703 /** 14704 * Used during creation of InstallArgs 14705 * 14706 * @param installFlags package installation flags 14707 * @return true if should be installed on external storage 14708 */ 14709 private static boolean installOnExternalAsec(int installFlags) { 14710 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14711 return false; 14712 } 14713 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14714 return true; 14715 } 14716 return false; 14717 } 14718 14719 /** 14720 * Used during creation of InstallArgs 14721 * 14722 * @param installFlags package installation flags 14723 * @return true if should be installed as forward locked 14724 */ 14725 private static boolean installForwardLocked(int installFlags) { 14726 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14727 } 14728 14729 private InstallArgs createInstallArgs(InstallParams params) { 14730 if (params.move != null) { 14731 return new MoveInstallArgs(params); 14732 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14733 return new AsecInstallArgs(params); 14734 } else { 14735 return new FileInstallArgs(params); 14736 } 14737 } 14738 14739 /** 14740 * Create args that describe an existing installed package. Typically used 14741 * when cleaning up old installs, or used as a move source. 14742 */ 14743 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14744 String resourcePath, String[] instructionSets) { 14745 final boolean isInAsec; 14746 if (installOnExternalAsec(installFlags)) { 14747 /* Apps on SD card are always in ASEC containers. */ 14748 isInAsec = true; 14749 } else if (installForwardLocked(installFlags) 14750 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14751 /* 14752 * Forward-locked apps are only in ASEC containers if they're the 14753 * new style 14754 */ 14755 isInAsec = true; 14756 } else { 14757 isInAsec = false; 14758 } 14759 14760 if (isInAsec) { 14761 return new AsecInstallArgs(codePath, instructionSets, 14762 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14763 } else { 14764 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14765 } 14766 } 14767 14768 static abstract class InstallArgs { 14769 /** @see InstallParams#origin */ 14770 final OriginInfo origin; 14771 /** @see InstallParams#move */ 14772 final MoveInfo move; 14773 14774 final IPackageInstallObserver2 observer; 14775 // Always refers to PackageManager flags only 14776 final int installFlags; 14777 final String installerPackageName; 14778 final String volumeUuid; 14779 final UserHandle user; 14780 final String abiOverride; 14781 final String[] installGrantPermissions; 14782 /** If non-null, drop an async trace when the install completes */ 14783 final String traceMethod; 14784 final int traceCookie; 14785 final Certificate[][] certificates; 14786 final int installReason; 14787 14788 // The list of instruction sets supported by this app. This is currently 14789 // only used during the rmdex() phase to clean up resources. We can get rid of this 14790 // if we move dex files under the common app path. 14791 /* nullable */ String[] instructionSets; 14792 14793 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14794 int installFlags, String installerPackageName, String volumeUuid, 14795 UserHandle user, String[] instructionSets, 14796 String abiOverride, String[] installGrantPermissions, 14797 String traceMethod, int traceCookie, Certificate[][] certificates, 14798 int installReason) { 14799 this.origin = origin; 14800 this.move = move; 14801 this.installFlags = installFlags; 14802 this.observer = observer; 14803 this.installerPackageName = installerPackageName; 14804 this.volumeUuid = volumeUuid; 14805 this.user = user; 14806 this.instructionSets = instructionSets; 14807 this.abiOverride = abiOverride; 14808 this.installGrantPermissions = installGrantPermissions; 14809 this.traceMethod = traceMethod; 14810 this.traceCookie = traceCookie; 14811 this.certificates = certificates; 14812 this.installReason = installReason; 14813 } 14814 14815 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14816 abstract int doPreInstall(int status); 14817 14818 /** 14819 * Rename package into final resting place. All paths on the given 14820 * scanned package should be updated to reflect the rename. 14821 */ 14822 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14823 abstract int doPostInstall(int status, int uid); 14824 14825 /** @see PackageSettingBase#codePathString */ 14826 abstract String getCodePath(); 14827 /** @see PackageSettingBase#resourcePathString */ 14828 abstract String getResourcePath(); 14829 14830 // Need installer lock especially for dex file removal. 14831 abstract void cleanUpResourcesLI(); 14832 abstract boolean doPostDeleteLI(boolean delete); 14833 14834 /** 14835 * Called before the source arguments are copied. This is used mostly 14836 * for MoveParams when it needs to read the source file to put it in the 14837 * destination. 14838 */ 14839 int doPreCopy() { 14840 return PackageManager.INSTALL_SUCCEEDED; 14841 } 14842 14843 /** 14844 * Called after the source arguments are copied. This is used mostly for 14845 * MoveParams when it needs to read the source file to put it in the 14846 * destination. 14847 */ 14848 int doPostCopy(int uid) { 14849 return PackageManager.INSTALL_SUCCEEDED; 14850 } 14851 14852 protected boolean isFwdLocked() { 14853 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14854 } 14855 14856 protected boolean isExternalAsec() { 14857 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14858 } 14859 14860 protected boolean isEphemeral() { 14861 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14862 } 14863 14864 UserHandle getUser() { 14865 return user; 14866 } 14867 } 14868 14869 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 14870 if (!allCodePaths.isEmpty()) { 14871 if (instructionSets == null) { 14872 throw new IllegalStateException("instructionSet == null"); 14873 } 14874 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 14875 for (String codePath : allCodePaths) { 14876 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 14877 try { 14878 mInstaller.rmdex(codePath, dexCodeInstructionSet); 14879 } catch (InstallerException ignored) { 14880 } 14881 } 14882 } 14883 } 14884 } 14885 14886 /** 14887 * Logic to handle installation of non-ASEC applications, including copying 14888 * and renaming logic. 14889 */ 14890 class FileInstallArgs extends InstallArgs { 14891 private File codeFile; 14892 private File resourceFile; 14893 14894 // Example topology: 14895 // /data/app/com.example/base.apk 14896 // /data/app/com.example/split_foo.apk 14897 // /data/app/com.example/lib/arm/libfoo.so 14898 // /data/app/com.example/lib/arm64/libfoo.so 14899 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 14900 14901 /** New install */ 14902 FileInstallArgs(InstallParams params) { 14903 super(params.origin, params.move, params.observer, params.installFlags, 14904 params.installerPackageName, params.volumeUuid, 14905 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 14906 params.grantedRuntimePermissions, 14907 params.traceMethod, params.traceCookie, params.certificates, 14908 params.installReason); 14909 if (isFwdLocked()) { 14910 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 14911 } 14912 } 14913 14914 /** Existing install */ 14915 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 14916 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 14917 null, null, null, 0, null /*certificates*/, 14918 PackageManager.INSTALL_REASON_UNKNOWN); 14919 this.codeFile = (codePath != null) ? new File(codePath) : null; 14920 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 14921 } 14922 14923 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14924 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 14925 try { 14926 return doCopyApk(imcs, temp); 14927 } finally { 14928 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14929 } 14930 } 14931 14932 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14933 if (origin.staged) { 14934 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 14935 codeFile = origin.file; 14936 resourceFile = origin.file; 14937 return PackageManager.INSTALL_SUCCEEDED; 14938 } 14939 14940 try { 14941 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14942 final File tempDir = 14943 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 14944 codeFile = tempDir; 14945 resourceFile = tempDir; 14946 } catch (IOException e) { 14947 Slog.w(TAG, "Failed to create copy file: " + e); 14948 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14949 } 14950 14951 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 14952 @Override 14953 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 14954 if (!FileUtils.isValidExtFilename(name)) { 14955 throw new IllegalArgumentException("Invalid filename: " + name); 14956 } 14957 try { 14958 final File file = new File(codeFile, name); 14959 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 14960 O_RDWR | O_CREAT, 0644); 14961 Os.chmod(file.getAbsolutePath(), 0644); 14962 return new ParcelFileDescriptor(fd); 14963 } catch (ErrnoException e) { 14964 throw new RemoteException("Failed to open: " + e.getMessage()); 14965 } 14966 } 14967 }; 14968 14969 int ret = PackageManager.INSTALL_SUCCEEDED; 14970 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 14971 if (ret != PackageManager.INSTALL_SUCCEEDED) { 14972 Slog.e(TAG, "Failed to copy package"); 14973 return ret; 14974 } 14975 14976 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 14977 NativeLibraryHelper.Handle handle = null; 14978 try { 14979 handle = NativeLibraryHelper.Handle.create(codeFile); 14980 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 14981 abiOverride); 14982 } catch (IOException e) { 14983 Slog.e(TAG, "Copying native libraries failed", e); 14984 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14985 } finally { 14986 IoUtils.closeQuietly(handle); 14987 } 14988 14989 return ret; 14990 } 14991 14992 int doPreInstall(int status) { 14993 if (status != PackageManager.INSTALL_SUCCEEDED) { 14994 cleanUp(); 14995 } 14996 return status; 14997 } 14998 14999 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15000 if (status != PackageManager.INSTALL_SUCCEEDED) { 15001 cleanUp(); 15002 return false; 15003 } 15004 15005 final File targetDir = codeFile.getParentFile(); 15006 final File beforeCodeFile = codeFile; 15007 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15008 15009 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15010 try { 15011 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15012 } catch (ErrnoException e) { 15013 Slog.w(TAG, "Failed to rename", e); 15014 return false; 15015 } 15016 15017 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15018 Slog.w(TAG, "Failed to restorecon"); 15019 return false; 15020 } 15021 15022 // Reflect the rename internally 15023 codeFile = afterCodeFile; 15024 resourceFile = afterCodeFile; 15025 15026 // Reflect the rename in scanned details 15027 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15028 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15029 afterCodeFile, pkg.baseCodePath)); 15030 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15031 afterCodeFile, pkg.splitCodePaths)); 15032 15033 // Reflect the rename in app info 15034 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15035 pkg.setApplicationInfoCodePath(pkg.codePath); 15036 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15037 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15038 pkg.setApplicationInfoResourcePath(pkg.codePath); 15039 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15040 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15041 15042 return true; 15043 } 15044 15045 int doPostInstall(int status, int uid) { 15046 if (status != PackageManager.INSTALL_SUCCEEDED) { 15047 cleanUp(); 15048 } 15049 return status; 15050 } 15051 15052 @Override 15053 String getCodePath() { 15054 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15055 } 15056 15057 @Override 15058 String getResourcePath() { 15059 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15060 } 15061 15062 private boolean cleanUp() { 15063 if (codeFile == null || !codeFile.exists()) { 15064 return false; 15065 } 15066 15067 removeCodePathLI(codeFile); 15068 15069 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15070 resourceFile.delete(); 15071 } 15072 15073 return true; 15074 } 15075 15076 void cleanUpResourcesLI() { 15077 // Try enumerating all code paths before deleting 15078 List<String> allCodePaths = Collections.EMPTY_LIST; 15079 if (codeFile != null && codeFile.exists()) { 15080 try { 15081 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15082 allCodePaths = pkg.getAllCodePaths(); 15083 } catch (PackageParserException e) { 15084 // Ignored; we tried our best 15085 } 15086 } 15087 15088 cleanUp(); 15089 removeDexFiles(allCodePaths, instructionSets); 15090 } 15091 15092 boolean doPostDeleteLI(boolean delete) { 15093 // XXX err, shouldn't we respect the delete flag? 15094 cleanUpResourcesLI(); 15095 return true; 15096 } 15097 } 15098 15099 private boolean isAsecExternal(String cid) { 15100 final String asecPath = PackageHelper.getSdFilesystem(cid); 15101 return !asecPath.startsWith(mAsecInternalPath); 15102 } 15103 15104 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15105 PackageManagerException { 15106 if (copyRet < 0) { 15107 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15108 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15109 throw new PackageManagerException(copyRet, message); 15110 } 15111 } 15112 } 15113 15114 /** 15115 * Extract the StorageManagerService "container ID" from the full code path of an 15116 * .apk. 15117 */ 15118 static String cidFromCodePath(String fullCodePath) { 15119 int eidx = fullCodePath.lastIndexOf("/"); 15120 String subStr1 = fullCodePath.substring(0, eidx); 15121 int sidx = subStr1.lastIndexOf("/"); 15122 return subStr1.substring(sidx+1, eidx); 15123 } 15124 15125 /** 15126 * Logic to handle installation of ASEC applications, including copying and 15127 * renaming logic. 15128 */ 15129 class AsecInstallArgs extends InstallArgs { 15130 static final String RES_FILE_NAME = "pkg.apk"; 15131 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15132 15133 String cid; 15134 String packagePath; 15135 String resourcePath; 15136 15137 /** New install */ 15138 AsecInstallArgs(InstallParams params) { 15139 super(params.origin, params.move, params.observer, params.installFlags, 15140 params.installerPackageName, params.volumeUuid, 15141 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15142 params.grantedRuntimePermissions, 15143 params.traceMethod, params.traceCookie, params.certificates, 15144 params.installReason); 15145 } 15146 15147 /** Existing install */ 15148 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15149 boolean isExternal, boolean isForwardLocked) { 15150 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15151 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15152 instructionSets, null, null, null, 0, null /*certificates*/, 15153 PackageManager.INSTALL_REASON_UNKNOWN); 15154 // Hackily pretend we're still looking at a full code path 15155 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15156 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15157 } 15158 15159 // Extract cid from fullCodePath 15160 int eidx = fullCodePath.lastIndexOf("/"); 15161 String subStr1 = fullCodePath.substring(0, eidx); 15162 int sidx = subStr1.lastIndexOf("/"); 15163 cid = subStr1.substring(sidx+1, eidx); 15164 setMountPath(subStr1); 15165 } 15166 15167 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15168 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15169 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15170 instructionSets, null, null, null, 0, null /*certificates*/, 15171 PackageManager.INSTALL_REASON_UNKNOWN); 15172 this.cid = cid; 15173 setMountPath(PackageHelper.getSdDir(cid)); 15174 } 15175 15176 void createCopyFile() { 15177 cid = mInstallerService.allocateExternalStageCidLegacy(); 15178 } 15179 15180 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15181 if (origin.staged && origin.cid != null) { 15182 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15183 cid = origin.cid; 15184 setMountPath(PackageHelper.getSdDir(cid)); 15185 return PackageManager.INSTALL_SUCCEEDED; 15186 } 15187 15188 if (temp) { 15189 createCopyFile(); 15190 } else { 15191 /* 15192 * Pre-emptively destroy the container since it's destroyed if 15193 * copying fails due to it existing anyway. 15194 */ 15195 PackageHelper.destroySdDir(cid); 15196 } 15197 15198 final String newMountPath = imcs.copyPackageToContainer( 15199 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15200 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15201 15202 if (newMountPath != null) { 15203 setMountPath(newMountPath); 15204 return PackageManager.INSTALL_SUCCEEDED; 15205 } else { 15206 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15207 } 15208 } 15209 15210 @Override 15211 String getCodePath() { 15212 return packagePath; 15213 } 15214 15215 @Override 15216 String getResourcePath() { 15217 return resourcePath; 15218 } 15219 15220 int doPreInstall(int status) { 15221 if (status != PackageManager.INSTALL_SUCCEEDED) { 15222 // Destroy container 15223 PackageHelper.destroySdDir(cid); 15224 } else { 15225 boolean mounted = PackageHelper.isContainerMounted(cid); 15226 if (!mounted) { 15227 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15228 Process.SYSTEM_UID); 15229 if (newMountPath != null) { 15230 setMountPath(newMountPath); 15231 } else { 15232 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15233 } 15234 } 15235 } 15236 return status; 15237 } 15238 15239 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15240 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15241 String newMountPath = null; 15242 if (PackageHelper.isContainerMounted(cid)) { 15243 // Unmount the container 15244 if (!PackageHelper.unMountSdDir(cid)) { 15245 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15246 return false; 15247 } 15248 } 15249 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15250 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15251 " which might be stale. Will try to clean up."); 15252 // Clean up the stale container and proceed to recreate. 15253 if (!PackageHelper.destroySdDir(newCacheId)) { 15254 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15255 return false; 15256 } 15257 // Successfully cleaned up stale container. Try to rename again. 15258 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15259 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15260 + " inspite of cleaning it up."); 15261 return false; 15262 } 15263 } 15264 if (!PackageHelper.isContainerMounted(newCacheId)) { 15265 Slog.w(TAG, "Mounting container " + newCacheId); 15266 newMountPath = PackageHelper.mountSdDir(newCacheId, 15267 getEncryptKey(), Process.SYSTEM_UID); 15268 } else { 15269 newMountPath = PackageHelper.getSdDir(newCacheId); 15270 } 15271 if (newMountPath == null) { 15272 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15273 return false; 15274 } 15275 Log.i(TAG, "Succesfully renamed " + cid + 15276 " to " + newCacheId + 15277 " at new path: " + newMountPath); 15278 cid = newCacheId; 15279 15280 final File beforeCodeFile = new File(packagePath); 15281 setMountPath(newMountPath); 15282 final File afterCodeFile = new File(packagePath); 15283 15284 // Reflect the rename in scanned details 15285 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15286 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15287 afterCodeFile, pkg.baseCodePath)); 15288 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15289 afterCodeFile, pkg.splitCodePaths)); 15290 15291 // Reflect the rename in app info 15292 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15293 pkg.setApplicationInfoCodePath(pkg.codePath); 15294 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15295 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15296 pkg.setApplicationInfoResourcePath(pkg.codePath); 15297 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15298 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15299 15300 return true; 15301 } 15302 15303 private void setMountPath(String mountPath) { 15304 final File mountFile = new File(mountPath); 15305 15306 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15307 if (monolithicFile.exists()) { 15308 packagePath = monolithicFile.getAbsolutePath(); 15309 if (isFwdLocked()) { 15310 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15311 } else { 15312 resourcePath = packagePath; 15313 } 15314 } else { 15315 packagePath = mountFile.getAbsolutePath(); 15316 resourcePath = packagePath; 15317 } 15318 } 15319 15320 int doPostInstall(int status, int uid) { 15321 if (status != PackageManager.INSTALL_SUCCEEDED) { 15322 cleanUp(); 15323 } else { 15324 final int groupOwner; 15325 final String protectedFile; 15326 if (isFwdLocked()) { 15327 groupOwner = UserHandle.getSharedAppGid(uid); 15328 protectedFile = RES_FILE_NAME; 15329 } else { 15330 groupOwner = -1; 15331 protectedFile = null; 15332 } 15333 15334 if (uid < Process.FIRST_APPLICATION_UID 15335 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15336 Slog.e(TAG, "Failed to finalize " + cid); 15337 PackageHelper.destroySdDir(cid); 15338 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15339 } 15340 15341 boolean mounted = PackageHelper.isContainerMounted(cid); 15342 if (!mounted) { 15343 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15344 } 15345 } 15346 return status; 15347 } 15348 15349 private void cleanUp() { 15350 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15351 15352 // Destroy secure container 15353 PackageHelper.destroySdDir(cid); 15354 } 15355 15356 private List<String> getAllCodePaths() { 15357 final File codeFile = new File(getCodePath()); 15358 if (codeFile != null && codeFile.exists()) { 15359 try { 15360 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15361 return pkg.getAllCodePaths(); 15362 } catch (PackageParserException e) { 15363 // Ignored; we tried our best 15364 } 15365 } 15366 return Collections.EMPTY_LIST; 15367 } 15368 15369 void cleanUpResourcesLI() { 15370 // Enumerate all code paths before deleting 15371 cleanUpResourcesLI(getAllCodePaths()); 15372 } 15373 15374 private void cleanUpResourcesLI(List<String> allCodePaths) { 15375 cleanUp(); 15376 removeDexFiles(allCodePaths, instructionSets); 15377 } 15378 15379 String getPackageName() { 15380 return getAsecPackageName(cid); 15381 } 15382 15383 boolean doPostDeleteLI(boolean delete) { 15384 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15385 final List<String> allCodePaths = getAllCodePaths(); 15386 boolean mounted = PackageHelper.isContainerMounted(cid); 15387 if (mounted) { 15388 // Unmount first 15389 if (PackageHelper.unMountSdDir(cid)) { 15390 mounted = false; 15391 } 15392 } 15393 if (!mounted && delete) { 15394 cleanUpResourcesLI(allCodePaths); 15395 } 15396 return !mounted; 15397 } 15398 15399 @Override 15400 int doPreCopy() { 15401 if (isFwdLocked()) { 15402 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15403 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15404 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15405 } 15406 } 15407 15408 return PackageManager.INSTALL_SUCCEEDED; 15409 } 15410 15411 @Override 15412 int doPostCopy(int uid) { 15413 if (isFwdLocked()) { 15414 if (uid < Process.FIRST_APPLICATION_UID 15415 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15416 RES_FILE_NAME)) { 15417 Slog.e(TAG, "Failed to finalize " + cid); 15418 PackageHelper.destroySdDir(cid); 15419 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15420 } 15421 } 15422 15423 return PackageManager.INSTALL_SUCCEEDED; 15424 } 15425 } 15426 15427 /** 15428 * Logic to handle movement of existing installed applications. 15429 */ 15430 class MoveInstallArgs extends InstallArgs { 15431 private File codeFile; 15432 private File resourceFile; 15433 15434 /** New install */ 15435 MoveInstallArgs(InstallParams params) { 15436 super(params.origin, params.move, params.observer, params.installFlags, 15437 params.installerPackageName, params.volumeUuid, 15438 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15439 params.grantedRuntimePermissions, 15440 params.traceMethod, params.traceCookie, params.certificates, 15441 params.installReason); 15442 } 15443 15444 int copyApk(IMediaContainerService imcs, boolean temp) { 15445 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15446 + move.fromUuid + " to " + move.toUuid); 15447 synchronized (mInstaller) { 15448 try { 15449 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15450 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15451 } catch (InstallerException e) { 15452 Slog.w(TAG, "Failed to move app", e); 15453 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15454 } 15455 } 15456 15457 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15458 resourceFile = codeFile; 15459 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15460 15461 return PackageManager.INSTALL_SUCCEEDED; 15462 } 15463 15464 int doPreInstall(int status) { 15465 if (status != PackageManager.INSTALL_SUCCEEDED) { 15466 cleanUp(move.toUuid); 15467 } 15468 return status; 15469 } 15470 15471 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15472 if (status != PackageManager.INSTALL_SUCCEEDED) { 15473 cleanUp(move.toUuid); 15474 return false; 15475 } 15476 15477 // Reflect the move in app info 15478 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15479 pkg.setApplicationInfoCodePath(pkg.codePath); 15480 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15481 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15482 pkg.setApplicationInfoResourcePath(pkg.codePath); 15483 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15484 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15485 15486 return true; 15487 } 15488 15489 int doPostInstall(int status, int uid) { 15490 if (status == PackageManager.INSTALL_SUCCEEDED) { 15491 cleanUp(move.fromUuid); 15492 } else { 15493 cleanUp(move.toUuid); 15494 } 15495 return status; 15496 } 15497 15498 @Override 15499 String getCodePath() { 15500 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15501 } 15502 15503 @Override 15504 String getResourcePath() { 15505 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15506 } 15507 15508 private boolean cleanUp(String volumeUuid) { 15509 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15510 move.dataAppName); 15511 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15512 final int[] userIds = sUserManager.getUserIds(); 15513 synchronized (mInstallLock) { 15514 // Clean up both app data and code 15515 // All package moves are frozen until finished 15516 for (int userId : userIds) { 15517 try { 15518 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15519 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15520 } catch (InstallerException e) { 15521 Slog.w(TAG, String.valueOf(e)); 15522 } 15523 } 15524 removeCodePathLI(codeFile); 15525 } 15526 return true; 15527 } 15528 15529 void cleanUpResourcesLI() { 15530 throw new UnsupportedOperationException(); 15531 } 15532 15533 boolean doPostDeleteLI(boolean delete) { 15534 throw new UnsupportedOperationException(); 15535 } 15536 } 15537 15538 static String getAsecPackageName(String packageCid) { 15539 int idx = packageCid.lastIndexOf("-"); 15540 if (idx == -1) { 15541 return packageCid; 15542 } 15543 return packageCid.substring(0, idx); 15544 } 15545 15546 // Utility method used to create code paths based on package name and available index. 15547 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15548 String idxStr = ""; 15549 int idx = 1; 15550 // Fall back to default value of idx=1 if prefix is not 15551 // part of oldCodePath 15552 if (oldCodePath != null) { 15553 String subStr = oldCodePath; 15554 // Drop the suffix right away 15555 if (suffix != null && subStr.endsWith(suffix)) { 15556 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15557 } 15558 // If oldCodePath already contains prefix find out the 15559 // ending index to either increment or decrement. 15560 int sidx = subStr.lastIndexOf(prefix); 15561 if (sidx != -1) { 15562 subStr = subStr.substring(sidx + prefix.length()); 15563 if (subStr != null) { 15564 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15565 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15566 } 15567 try { 15568 idx = Integer.parseInt(subStr); 15569 if (idx <= 1) { 15570 idx++; 15571 } else { 15572 idx--; 15573 } 15574 } catch(NumberFormatException e) { 15575 } 15576 } 15577 } 15578 } 15579 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15580 return prefix + idxStr; 15581 } 15582 15583 private File getNextCodePath(File targetDir, String packageName) { 15584 File result; 15585 SecureRandom random = new SecureRandom(); 15586 byte[] bytes = new byte[16]; 15587 do { 15588 random.nextBytes(bytes); 15589 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15590 result = new File(targetDir, packageName + "-" + suffix); 15591 } while (result.exists()); 15592 return result; 15593 } 15594 15595 // Utility method that returns the relative package path with respect 15596 // to the installation directory. Like say for /data/data/com.test-1.apk 15597 // string com.test-1 is returned. 15598 static String deriveCodePathName(String codePath) { 15599 if (codePath == null) { 15600 return null; 15601 } 15602 final File codeFile = new File(codePath); 15603 final String name = codeFile.getName(); 15604 if (codeFile.isDirectory()) { 15605 return name; 15606 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15607 final int lastDot = name.lastIndexOf('.'); 15608 return name.substring(0, lastDot); 15609 } else { 15610 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15611 return null; 15612 } 15613 } 15614 15615 static class PackageInstalledInfo { 15616 String name; 15617 int uid; 15618 // The set of users that originally had this package installed. 15619 int[] origUsers; 15620 // The set of users that now have this package installed. 15621 int[] newUsers; 15622 PackageParser.Package pkg; 15623 int returnCode; 15624 String returnMsg; 15625 PackageRemovedInfo removedInfo; 15626 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15627 15628 public void setError(int code, String msg) { 15629 setReturnCode(code); 15630 setReturnMessage(msg); 15631 Slog.w(TAG, msg); 15632 } 15633 15634 public void setError(String msg, PackageParserException e) { 15635 setReturnCode(e.error); 15636 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15637 Slog.w(TAG, msg, e); 15638 } 15639 15640 public void setError(String msg, PackageManagerException e) { 15641 returnCode = e.error; 15642 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15643 Slog.w(TAG, msg, e); 15644 } 15645 15646 public void setReturnCode(int returnCode) { 15647 this.returnCode = returnCode; 15648 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15649 for (int i = 0; i < childCount; i++) { 15650 addedChildPackages.valueAt(i).returnCode = returnCode; 15651 } 15652 } 15653 15654 private void setReturnMessage(String returnMsg) { 15655 this.returnMsg = returnMsg; 15656 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15657 for (int i = 0; i < childCount; i++) { 15658 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15659 } 15660 } 15661 15662 // In some error cases we want to convey more info back to the observer 15663 String origPackage; 15664 String origPermission; 15665 } 15666 15667 /* 15668 * Install a non-existing package. 15669 */ 15670 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15671 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15672 PackageInstalledInfo res, int installReason) { 15673 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15674 15675 // Remember this for later, in case we need to rollback this install 15676 String pkgName = pkg.packageName; 15677 15678 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15679 15680 synchronized(mPackages) { 15681 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15682 if (renamedPackage != null) { 15683 // A package with the same name is already installed, though 15684 // it has been renamed to an older name. The package we 15685 // are trying to install should be installed as an update to 15686 // the existing one, but that has not been requested, so bail. 15687 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15688 + " without first uninstalling package running as " 15689 + renamedPackage); 15690 return; 15691 } 15692 if (mPackages.containsKey(pkgName)) { 15693 // Don't allow installation over an existing package with the same name. 15694 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15695 + " without first uninstalling."); 15696 return; 15697 } 15698 } 15699 15700 try { 15701 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15702 System.currentTimeMillis(), user); 15703 15704 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15705 15706 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15707 prepareAppDataAfterInstallLIF(newPackage); 15708 15709 } else { 15710 // Remove package from internal structures, but keep around any 15711 // data that might have already existed 15712 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15713 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15714 } 15715 } catch (PackageManagerException e) { 15716 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15717 } 15718 15719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15720 } 15721 15722 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15723 // Can't rotate keys during boot or if sharedUser. 15724 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15725 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15726 return false; 15727 } 15728 // app is using upgradeKeySets; make sure all are valid 15729 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15730 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15731 for (int i = 0; i < upgradeKeySets.length; i++) { 15732 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15733 Slog.wtf(TAG, "Package " 15734 + (oldPs.name != null ? oldPs.name : "<null>") 15735 + " contains upgrade-key-set reference to unknown key-set: " 15736 + upgradeKeySets[i] 15737 + " reverting to signatures check."); 15738 return false; 15739 } 15740 } 15741 return true; 15742 } 15743 15744 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15745 // Upgrade keysets are being used. Determine if new package has a superset of the 15746 // required keys. 15747 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15748 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15749 for (int i = 0; i < upgradeKeySets.length; i++) { 15750 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15751 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15752 return true; 15753 } 15754 } 15755 return false; 15756 } 15757 15758 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15759 try (DigestInputStream digestStream = 15760 new DigestInputStream(new FileInputStream(file), digest)) { 15761 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15762 } 15763 } 15764 15765 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15766 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15767 int installReason) { 15768 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15769 15770 final PackageParser.Package oldPackage; 15771 final String pkgName = pkg.packageName; 15772 final int[] allUsers; 15773 final int[] installedUsers; 15774 15775 synchronized(mPackages) { 15776 oldPackage = mPackages.get(pkgName); 15777 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15778 15779 // don't allow upgrade to target a release SDK from a pre-release SDK 15780 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15781 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15782 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15783 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15784 if (oldTargetsPreRelease 15785 && !newTargetsPreRelease 15786 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15787 Slog.w(TAG, "Can't install package targeting released sdk"); 15788 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15789 return; 15790 } 15791 15792 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15793 15794 // verify signatures are valid 15795 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15796 if (!checkUpgradeKeySetLP(ps, pkg)) { 15797 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15798 "New package not signed by keys specified by upgrade-keysets: " 15799 + pkgName); 15800 return; 15801 } 15802 } else { 15803 // default to original signature matching 15804 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15805 != PackageManager.SIGNATURE_MATCH) { 15806 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15807 "New package has a different signature: " + pkgName); 15808 return; 15809 } 15810 } 15811 15812 // don't allow a system upgrade unless the upgrade hash matches 15813 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15814 byte[] digestBytes = null; 15815 try { 15816 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15817 updateDigest(digest, new File(pkg.baseCodePath)); 15818 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15819 for (String path : pkg.splitCodePaths) { 15820 updateDigest(digest, new File(path)); 15821 } 15822 } 15823 digestBytes = digest.digest(); 15824 } catch (NoSuchAlgorithmException | IOException e) { 15825 res.setError(INSTALL_FAILED_INVALID_APK, 15826 "Could not compute hash: " + pkgName); 15827 return; 15828 } 15829 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15830 res.setError(INSTALL_FAILED_INVALID_APK, 15831 "New package fails restrict-update check: " + pkgName); 15832 return; 15833 } 15834 // retain upgrade restriction 15835 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15836 } 15837 15838 // Check for shared user id changes 15839 String invalidPackageName = 15840 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15841 if (invalidPackageName != null) { 15842 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15843 "Package " + invalidPackageName + " tried to change user " 15844 + oldPackage.mSharedUserId); 15845 return; 15846 } 15847 15848 // In case of rollback, remember per-user/profile install state 15849 allUsers = sUserManager.getUserIds(); 15850 installedUsers = ps.queryInstalledUsers(allUsers, true); 15851 15852 // don't allow an upgrade from full to ephemeral 15853 if (isInstantApp) { 15854 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15855 for (int currentUser : allUsers) { 15856 if (!ps.getInstantApp(currentUser)) { 15857 // can't downgrade from full to instant 15858 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15859 + " for user: " + currentUser); 15860 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15861 return; 15862 } 15863 } 15864 } else if (!ps.getInstantApp(user.getIdentifier())) { 15865 // can't downgrade from full to instant 15866 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15867 + " for user: " + user.getIdentifier()); 15868 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15869 return; 15870 } 15871 } 15872 } 15873 15874 // Update what is removed 15875 res.removedInfo = new PackageRemovedInfo(); 15876 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15877 res.removedInfo.removedPackage = oldPackage.packageName; 15878 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15879 res.removedInfo.isUpdate = true; 15880 res.removedInfo.origUsers = installedUsers; 15881 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 15882 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15883 for (int i = 0; i < installedUsers.length; i++) { 15884 final int userId = installedUsers[i]; 15885 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15886 } 15887 15888 final int childCount = (oldPackage.childPackages != null) 15889 ? oldPackage.childPackages.size() : 0; 15890 for (int i = 0; i < childCount; i++) { 15891 boolean childPackageUpdated = false; 15892 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15893 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15894 if (res.addedChildPackages != null) { 15895 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15896 if (childRes != null) { 15897 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15898 childRes.removedInfo.removedPackage = childPkg.packageName; 15899 childRes.removedInfo.isUpdate = true; 15900 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15901 childPackageUpdated = true; 15902 } 15903 } 15904 if (!childPackageUpdated) { 15905 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 15906 childRemovedRes.removedPackage = childPkg.packageName; 15907 childRemovedRes.isUpdate = false; 15908 childRemovedRes.dataRemoved = true; 15909 synchronized (mPackages) { 15910 if (childPs != null) { 15911 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15912 } 15913 } 15914 if (res.removedInfo.removedChildPackages == null) { 15915 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15916 } 15917 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15918 } 15919 } 15920 15921 boolean sysPkg = (isSystemApp(oldPackage)); 15922 if (sysPkg) { 15923 // Set the system/privileged flags as needed 15924 final boolean privileged = 15925 (oldPackage.applicationInfo.privateFlags 15926 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15927 final int systemPolicyFlags = policyFlags 15928 | PackageParser.PARSE_IS_SYSTEM 15929 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 15930 15931 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 15932 user, allUsers, installerPackageName, res, installReason); 15933 } else { 15934 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 15935 user, allUsers, installerPackageName, res, installReason); 15936 } 15937 } 15938 15939 public List<String> getPreviousCodePaths(String packageName) { 15940 final PackageSetting ps = mSettings.mPackages.get(packageName); 15941 final List<String> result = new ArrayList<String>(); 15942 if (ps != null && ps.oldCodePaths != null) { 15943 result.addAll(ps.oldCodePaths); 15944 } 15945 return result; 15946 } 15947 15948 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15949 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 15950 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 15951 int installReason) { 15952 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15953 + deletedPackage); 15954 15955 String pkgName = deletedPackage.packageName; 15956 boolean deletedPkg = true; 15957 boolean addedPkg = false; 15958 boolean updatedSettings = false; 15959 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15960 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15961 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15962 15963 final long origUpdateTime = (pkg.mExtras != null) 15964 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15965 15966 // First delete the existing package while retaining the data directory 15967 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15968 res.removedInfo, true, pkg)) { 15969 // If the existing package wasn't successfully deleted 15970 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15971 deletedPkg = false; 15972 } else { 15973 // Successfully deleted the old package; proceed with replace. 15974 15975 // If deleted package lived in a container, give users a chance to 15976 // relinquish resources before killing. 15977 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15978 if (DEBUG_INSTALL) { 15979 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15980 } 15981 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15982 final ArrayList<String> pkgList = new ArrayList<String>(1); 15983 pkgList.add(deletedPackage.applicationInfo.packageName); 15984 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15985 } 15986 15987 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15988 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15989 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15990 15991 try { 15992 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 15993 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15994 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15995 installReason); 15996 15997 // Update the in-memory copy of the previous code paths. 15998 PackageSetting ps = mSettings.mPackages.get(pkgName); 15999 if (!killApp) { 16000 if (ps.oldCodePaths == null) { 16001 ps.oldCodePaths = new ArraySet<>(); 16002 } 16003 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16004 if (deletedPackage.splitCodePaths != null) { 16005 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16006 } 16007 } else { 16008 ps.oldCodePaths = null; 16009 } 16010 if (ps.childPackageNames != null) { 16011 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16012 final String childPkgName = ps.childPackageNames.get(i); 16013 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16014 childPs.oldCodePaths = ps.oldCodePaths; 16015 } 16016 } 16017 // set instant app status, but, only if it's explicitly specified 16018 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16019 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16020 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16021 prepareAppDataAfterInstallLIF(newPackage); 16022 addedPkg = true; 16023 mDexManager.notifyPackageUpdated(newPackage.packageName, 16024 newPackage.baseCodePath, newPackage.splitCodePaths); 16025 } catch (PackageManagerException e) { 16026 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16027 } 16028 } 16029 16030 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16031 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16032 16033 // Revert all internal state mutations and added folders for the failed install 16034 if (addedPkg) { 16035 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16036 res.removedInfo, true, null); 16037 } 16038 16039 // Restore the old package 16040 if (deletedPkg) { 16041 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16042 File restoreFile = new File(deletedPackage.codePath); 16043 // Parse old package 16044 boolean oldExternal = isExternal(deletedPackage); 16045 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16046 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16047 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16048 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16049 try { 16050 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16051 null); 16052 } catch (PackageManagerException e) { 16053 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16054 + e.getMessage()); 16055 return; 16056 } 16057 16058 synchronized (mPackages) { 16059 // Ensure the installer package name up to date 16060 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16061 16062 // Update permissions for restored package 16063 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16064 16065 mSettings.writeLPr(); 16066 } 16067 16068 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16069 } 16070 } else { 16071 synchronized (mPackages) { 16072 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16073 if (ps != null) { 16074 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16075 if (res.removedInfo.removedChildPackages != null) { 16076 final int childCount = res.removedInfo.removedChildPackages.size(); 16077 // Iterate in reverse as we may modify the collection 16078 for (int i = childCount - 1; i >= 0; i--) { 16079 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16080 if (res.addedChildPackages.containsKey(childPackageName)) { 16081 res.removedInfo.removedChildPackages.removeAt(i); 16082 } else { 16083 PackageRemovedInfo childInfo = res.removedInfo 16084 .removedChildPackages.valueAt(i); 16085 childInfo.removedForAllUsers = mPackages.get( 16086 childInfo.removedPackage) == null; 16087 } 16088 } 16089 } 16090 } 16091 } 16092 } 16093 } 16094 16095 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16096 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16097 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16098 int installReason) { 16099 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16100 + ", old=" + deletedPackage); 16101 16102 final boolean disabledSystem; 16103 16104 // Remove existing system package 16105 removePackageLI(deletedPackage, true); 16106 16107 synchronized (mPackages) { 16108 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16109 } 16110 if (!disabledSystem) { 16111 // We didn't need to disable the .apk as a current system package, 16112 // which means we are replacing another update that is already 16113 // installed. We need to make sure to delete the older one's .apk. 16114 res.removedInfo.args = createInstallArgsForExisting(0, 16115 deletedPackage.applicationInfo.getCodePath(), 16116 deletedPackage.applicationInfo.getResourcePath(), 16117 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16118 } else { 16119 res.removedInfo.args = null; 16120 } 16121 16122 // Successfully disabled the old package. Now proceed with re-installation 16123 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16124 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16125 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16126 16127 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16128 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16129 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16130 16131 PackageParser.Package newPackage = null; 16132 try { 16133 // Add the package to the internal data structures 16134 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16135 16136 // Set the update and install times 16137 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16138 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16139 System.currentTimeMillis()); 16140 16141 // Update the package dynamic state if succeeded 16142 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16143 // Now that the install succeeded make sure we remove data 16144 // directories for any child package the update removed. 16145 final int deletedChildCount = (deletedPackage.childPackages != null) 16146 ? deletedPackage.childPackages.size() : 0; 16147 final int newChildCount = (newPackage.childPackages != null) 16148 ? newPackage.childPackages.size() : 0; 16149 for (int i = 0; i < deletedChildCount; i++) { 16150 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16151 boolean childPackageDeleted = true; 16152 for (int j = 0; j < newChildCount; j++) { 16153 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16154 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16155 childPackageDeleted = false; 16156 break; 16157 } 16158 } 16159 if (childPackageDeleted) { 16160 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16161 deletedChildPkg.packageName); 16162 if (ps != null && res.removedInfo.removedChildPackages != null) { 16163 PackageRemovedInfo removedChildRes = res.removedInfo 16164 .removedChildPackages.get(deletedChildPkg.packageName); 16165 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16166 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16167 } 16168 } 16169 } 16170 16171 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16172 installReason); 16173 prepareAppDataAfterInstallLIF(newPackage); 16174 16175 mDexManager.notifyPackageUpdated(newPackage.packageName, 16176 newPackage.baseCodePath, newPackage.splitCodePaths); 16177 } 16178 } catch (PackageManagerException e) { 16179 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16180 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16181 } 16182 16183 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16184 // Re installation failed. Restore old information 16185 // Remove new pkg information 16186 if (newPackage != null) { 16187 removeInstalledPackageLI(newPackage, true); 16188 } 16189 // Add back the old system package 16190 try { 16191 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16192 } catch (PackageManagerException e) { 16193 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16194 } 16195 16196 synchronized (mPackages) { 16197 if (disabledSystem) { 16198 enableSystemPackageLPw(deletedPackage); 16199 } 16200 16201 // Ensure the installer package name up to date 16202 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16203 16204 // Update permissions for restored package 16205 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16206 16207 mSettings.writeLPr(); 16208 } 16209 16210 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16211 + " after failed upgrade"); 16212 } 16213 } 16214 16215 /** 16216 * Checks whether the parent or any of the child packages have a change shared 16217 * user. For a package to be a valid update the shred users of the parent and 16218 * the children should match. We may later support changing child shared users. 16219 * @param oldPkg The updated package. 16220 * @param newPkg The update package. 16221 * @return The shared user that change between the versions. 16222 */ 16223 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16224 PackageParser.Package newPkg) { 16225 // Check parent shared user 16226 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16227 return newPkg.packageName; 16228 } 16229 // Check child shared users 16230 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16231 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16232 for (int i = 0; i < newChildCount; i++) { 16233 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16234 // If this child was present, did it have the same shared user? 16235 for (int j = 0; j < oldChildCount; j++) { 16236 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16237 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16238 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16239 return newChildPkg.packageName; 16240 } 16241 } 16242 } 16243 return null; 16244 } 16245 16246 private void removeNativeBinariesLI(PackageSetting ps) { 16247 // Remove the lib path for the parent package 16248 if (ps != null) { 16249 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16250 // Remove the lib path for the child packages 16251 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16252 for (int i = 0; i < childCount; i++) { 16253 PackageSetting childPs = null; 16254 synchronized (mPackages) { 16255 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16256 } 16257 if (childPs != null) { 16258 NativeLibraryHelper.removeNativeBinariesLI(childPs 16259 .legacyNativeLibraryPathString); 16260 } 16261 } 16262 } 16263 } 16264 16265 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16266 // Enable the parent package 16267 mSettings.enableSystemPackageLPw(pkg.packageName); 16268 // Enable the child packages 16269 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16270 for (int i = 0; i < childCount; i++) { 16271 PackageParser.Package childPkg = pkg.childPackages.get(i); 16272 mSettings.enableSystemPackageLPw(childPkg.packageName); 16273 } 16274 } 16275 16276 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16277 PackageParser.Package newPkg) { 16278 // Disable the parent package (parent always replaced) 16279 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16280 // Disable the child packages 16281 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16282 for (int i = 0; i < childCount; i++) { 16283 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16284 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16285 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16286 } 16287 return disabled; 16288 } 16289 16290 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16291 String installerPackageName) { 16292 // Enable the parent package 16293 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16294 // Enable the child packages 16295 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16296 for (int i = 0; i < childCount; i++) { 16297 PackageParser.Package childPkg = pkg.childPackages.get(i); 16298 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16299 } 16300 } 16301 16302 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16303 // Collect all used permissions in the UID 16304 ArraySet<String> usedPermissions = new ArraySet<>(); 16305 final int packageCount = su.packages.size(); 16306 for (int i = 0; i < packageCount; i++) { 16307 PackageSetting ps = su.packages.valueAt(i); 16308 if (ps.pkg == null) { 16309 continue; 16310 } 16311 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16312 for (int j = 0; j < requestedPermCount; j++) { 16313 String permission = ps.pkg.requestedPermissions.get(j); 16314 BasePermission bp = mSettings.mPermissions.get(permission); 16315 if (bp != null) { 16316 usedPermissions.add(permission); 16317 } 16318 } 16319 } 16320 16321 PermissionsState permissionsState = su.getPermissionsState(); 16322 // Prune install permissions 16323 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16324 final int installPermCount = installPermStates.size(); 16325 for (int i = installPermCount - 1; i >= 0; i--) { 16326 PermissionState permissionState = installPermStates.get(i); 16327 if (!usedPermissions.contains(permissionState.getName())) { 16328 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16329 if (bp != null) { 16330 permissionsState.revokeInstallPermission(bp); 16331 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16332 PackageManager.MASK_PERMISSION_FLAGS, 0); 16333 } 16334 } 16335 } 16336 16337 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16338 16339 // Prune runtime permissions 16340 for (int userId : allUserIds) { 16341 List<PermissionState> runtimePermStates = permissionsState 16342 .getRuntimePermissionStates(userId); 16343 final int runtimePermCount = runtimePermStates.size(); 16344 for (int i = runtimePermCount - 1; i >= 0; i--) { 16345 PermissionState permissionState = runtimePermStates.get(i); 16346 if (!usedPermissions.contains(permissionState.getName())) { 16347 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16348 if (bp != null) { 16349 permissionsState.revokeRuntimePermission(bp, userId); 16350 permissionsState.updatePermissionFlags(bp, userId, 16351 PackageManager.MASK_PERMISSION_FLAGS, 0); 16352 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16353 runtimePermissionChangedUserIds, userId); 16354 } 16355 } 16356 } 16357 } 16358 16359 return runtimePermissionChangedUserIds; 16360 } 16361 16362 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16363 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16364 // Update the parent package setting 16365 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16366 res, user, installReason); 16367 // Update the child packages setting 16368 final int childCount = (newPackage.childPackages != null) 16369 ? newPackage.childPackages.size() : 0; 16370 for (int i = 0; i < childCount; i++) { 16371 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16372 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16373 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16374 childRes.origUsers, childRes, user, installReason); 16375 } 16376 } 16377 16378 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16379 String installerPackageName, int[] allUsers, int[] installedForUsers, 16380 PackageInstalledInfo res, UserHandle user, int installReason) { 16381 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16382 16383 String pkgName = newPackage.packageName; 16384 synchronized (mPackages) { 16385 //write settings. the installStatus will be incomplete at this stage. 16386 //note that the new package setting would have already been 16387 //added to mPackages. It hasn't been persisted yet. 16388 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16389 // TODO: Remove this write? It's also written at the end of this method 16390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16391 mSettings.writeLPr(); 16392 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16393 } 16394 16395 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16396 synchronized (mPackages) { 16397 updatePermissionsLPw(newPackage.packageName, newPackage, 16398 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16399 ? UPDATE_PERMISSIONS_ALL : 0)); 16400 // For system-bundled packages, we assume that installing an upgraded version 16401 // of the package implies that the user actually wants to run that new code, 16402 // so we enable the package. 16403 PackageSetting ps = mSettings.mPackages.get(pkgName); 16404 final int userId = user.getIdentifier(); 16405 if (ps != null) { 16406 if (isSystemApp(newPackage)) { 16407 if (DEBUG_INSTALL) { 16408 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16409 } 16410 // Enable system package for requested users 16411 if (res.origUsers != null) { 16412 for (int origUserId : res.origUsers) { 16413 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16414 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16415 origUserId, installerPackageName); 16416 } 16417 } 16418 } 16419 // Also convey the prior install/uninstall state 16420 if (allUsers != null && installedForUsers != null) { 16421 for (int currentUserId : allUsers) { 16422 final boolean installed = ArrayUtils.contains( 16423 installedForUsers, currentUserId); 16424 if (DEBUG_INSTALL) { 16425 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16426 } 16427 ps.setInstalled(installed, currentUserId); 16428 } 16429 // these install state changes will be persisted in the 16430 // upcoming call to mSettings.writeLPr(). 16431 } 16432 } 16433 // It's implied that when a user requests installation, they want the app to be 16434 // installed and enabled. 16435 if (userId != UserHandle.USER_ALL) { 16436 ps.setInstalled(true, userId); 16437 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16438 } 16439 16440 // When replacing an existing package, preserve the original install reason for all 16441 // users that had the package installed before. 16442 final Set<Integer> previousUserIds = new ArraySet<>(); 16443 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16444 final int installReasonCount = res.removedInfo.installReasons.size(); 16445 for (int i = 0; i < installReasonCount; i++) { 16446 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16447 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16448 ps.setInstallReason(previousInstallReason, previousUserId); 16449 previousUserIds.add(previousUserId); 16450 } 16451 } 16452 16453 // Set install reason for users that are having the package newly installed. 16454 if (userId == UserHandle.USER_ALL) { 16455 for (int currentUserId : sUserManager.getUserIds()) { 16456 if (!previousUserIds.contains(currentUserId)) { 16457 ps.setInstallReason(installReason, currentUserId); 16458 } 16459 } 16460 } else if (!previousUserIds.contains(userId)) { 16461 ps.setInstallReason(installReason, userId); 16462 } 16463 mSettings.writeKernelMappingLPr(ps); 16464 } 16465 res.name = pkgName; 16466 res.uid = newPackage.applicationInfo.uid; 16467 res.pkg = newPackage; 16468 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16469 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16470 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16471 //to update install status 16472 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16473 mSettings.writeLPr(); 16474 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16475 } 16476 16477 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16478 } 16479 16480 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16481 try { 16482 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16483 installPackageLI(args, res); 16484 } finally { 16485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16486 } 16487 } 16488 16489 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16490 final int installFlags = args.installFlags; 16491 final String installerPackageName = args.installerPackageName; 16492 final String volumeUuid = args.volumeUuid; 16493 final File tmpPackageFile = new File(args.getCodePath()); 16494 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16495 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16496 || (args.volumeUuid != null)); 16497 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16498 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16499 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16500 boolean replace = false; 16501 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16502 if (args.move != null) { 16503 // moving a complete application; perform an initial scan on the new install location 16504 scanFlags |= SCAN_INITIAL; 16505 } 16506 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16507 scanFlags |= SCAN_DONT_KILL_APP; 16508 } 16509 if (instantApp) { 16510 scanFlags |= SCAN_AS_INSTANT_APP; 16511 } 16512 if (fullApp) { 16513 scanFlags |= SCAN_AS_FULL_APP; 16514 } 16515 16516 // Result object to be returned 16517 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16518 16519 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16520 16521 // Sanity check 16522 if (instantApp && (forwardLocked || onExternal)) { 16523 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16524 + " external=" + onExternal); 16525 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16526 return; 16527 } 16528 16529 // Retrieve PackageSettings and parse package 16530 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16531 | PackageParser.PARSE_ENFORCE_CODE 16532 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16533 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16534 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16535 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16536 PackageParser pp = new PackageParser(); 16537 pp.setSeparateProcesses(mSeparateProcesses); 16538 pp.setDisplayMetrics(mMetrics); 16539 pp.setCallback(mPackageParserCallback); 16540 16541 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16542 final PackageParser.Package pkg; 16543 try { 16544 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16545 } catch (PackageParserException e) { 16546 res.setError("Failed parse during installPackageLI", e); 16547 return; 16548 } finally { 16549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16550 } 16551 16552 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16553 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16554 Slog.w(TAG, "Instant app package " + pkg.packageName 16555 + " does not target O, this will be a fatal error."); 16556 // STOPSHIP: Make this a fatal error 16557 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16558 } 16559 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16560 Slog.w(TAG, "Instant app package " + pkg.packageName 16561 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16562 // STOPSHIP: Make this a fatal error 16563 pkg.applicationInfo.targetSandboxVersion = 2; 16564 } 16565 16566 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16567 // Static shared libraries have synthetic package names 16568 renameStaticSharedLibraryPackage(pkg); 16569 16570 // No static shared libs on external storage 16571 if (onExternal) { 16572 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16573 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16574 "Packages declaring static-shared libs cannot be updated"); 16575 return; 16576 } 16577 } 16578 16579 // If we are installing a clustered package add results for the children 16580 if (pkg.childPackages != null) { 16581 synchronized (mPackages) { 16582 final int childCount = pkg.childPackages.size(); 16583 for (int i = 0; i < childCount; i++) { 16584 PackageParser.Package childPkg = pkg.childPackages.get(i); 16585 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16586 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16587 childRes.pkg = childPkg; 16588 childRes.name = childPkg.packageName; 16589 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16590 if (childPs != null) { 16591 childRes.origUsers = childPs.queryInstalledUsers( 16592 sUserManager.getUserIds(), true); 16593 } 16594 if ((mPackages.containsKey(childPkg.packageName))) { 16595 childRes.removedInfo = new PackageRemovedInfo(); 16596 childRes.removedInfo.removedPackage = childPkg.packageName; 16597 } 16598 if (res.addedChildPackages == null) { 16599 res.addedChildPackages = new ArrayMap<>(); 16600 } 16601 res.addedChildPackages.put(childPkg.packageName, childRes); 16602 } 16603 } 16604 } 16605 16606 // If package doesn't declare API override, mark that we have an install 16607 // time CPU ABI override. 16608 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16609 pkg.cpuAbiOverride = args.abiOverride; 16610 } 16611 16612 String pkgName = res.name = pkg.packageName; 16613 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16614 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16615 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16616 return; 16617 } 16618 } 16619 16620 try { 16621 // either use what we've been given or parse directly from the APK 16622 if (args.certificates != null) { 16623 try { 16624 PackageParser.populateCertificates(pkg, args.certificates); 16625 } catch (PackageParserException e) { 16626 // there was something wrong with the certificates we were given; 16627 // try to pull them from the APK 16628 PackageParser.collectCertificates(pkg, parseFlags); 16629 } 16630 } else { 16631 PackageParser.collectCertificates(pkg, parseFlags); 16632 } 16633 } catch (PackageParserException e) { 16634 res.setError("Failed collect during installPackageLI", e); 16635 return; 16636 } 16637 16638 // Get rid of all references to package scan path via parser. 16639 pp = null; 16640 String oldCodePath = null; 16641 boolean systemApp = false; 16642 synchronized (mPackages) { 16643 // Check if installing already existing package 16644 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16645 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16646 if (pkg.mOriginalPackages != null 16647 && pkg.mOriginalPackages.contains(oldName) 16648 && mPackages.containsKey(oldName)) { 16649 // This package is derived from an original package, 16650 // and this device has been updating from that original 16651 // name. We must continue using the original name, so 16652 // rename the new package here. 16653 pkg.setPackageName(oldName); 16654 pkgName = pkg.packageName; 16655 replace = true; 16656 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16657 + oldName + " pkgName=" + pkgName); 16658 } else if (mPackages.containsKey(pkgName)) { 16659 // This package, under its official name, already exists 16660 // on the device; we should replace it. 16661 replace = true; 16662 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16663 } 16664 16665 // Child packages are installed through the parent package 16666 if (pkg.parentPackage != null) { 16667 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16668 "Package " + pkg.packageName + " is child of package " 16669 + pkg.parentPackage.parentPackage + ". Child packages " 16670 + "can be updated only through the parent package."); 16671 return; 16672 } 16673 16674 if (replace) { 16675 // Prevent apps opting out from runtime permissions 16676 PackageParser.Package oldPackage = mPackages.get(pkgName); 16677 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16678 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16679 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16680 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16681 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16682 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16683 + " doesn't support runtime permissions but the old" 16684 + " target SDK " + oldTargetSdk + " does."); 16685 return; 16686 } 16687 16688 // Prevent installing of child packages 16689 if (oldPackage.parentPackage != null) { 16690 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16691 "Package " + pkg.packageName + " is child of package " 16692 + oldPackage.parentPackage + ". Child packages " 16693 + "can be updated only through the parent package."); 16694 return; 16695 } 16696 } 16697 } 16698 16699 PackageSetting ps = mSettings.mPackages.get(pkgName); 16700 if (ps != null) { 16701 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16702 16703 // Static shared libs have same package with different versions where 16704 // we internally use a synthetic package name to allow multiple versions 16705 // of the same package, therefore we need to compare signatures against 16706 // the package setting for the latest library version. 16707 PackageSetting signatureCheckPs = ps; 16708 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16709 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16710 if (libraryEntry != null) { 16711 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16712 } 16713 } 16714 16715 // Quick sanity check that we're signed correctly if updating; 16716 // we'll check this again later when scanning, but we want to 16717 // bail early here before tripping over redefined permissions. 16718 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16719 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16720 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16721 + pkg.packageName + " upgrade keys do not match the " 16722 + "previously installed version"); 16723 return; 16724 } 16725 } else { 16726 try { 16727 verifySignaturesLP(signatureCheckPs, pkg); 16728 } catch (PackageManagerException e) { 16729 res.setError(e.error, e.getMessage()); 16730 return; 16731 } 16732 } 16733 16734 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16735 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16736 systemApp = (ps.pkg.applicationInfo.flags & 16737 ApplicationInfo.FLAG_SYSTEM) != 0; 16738 } 16739 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16740 } 16741 16742 int N = pkg.permissions.size(); 16743 for (int i = N-1; i >= 0; i--) { 16744 PackageParser.Permission perm = pkg.permissions.get(i); 16745 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16746 16747 // Don't allow anyone but the platform to define ephemeral permissions. 16748 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16749 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16750 Slog.w(TAG, "Package " + pkg.packageName 16751 + " attempting to delcare ephemeral permission " 16752 + perm.info.name + "; Removing ephemeral."); 16753 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16754 } 16755 // Check whether the newly-scanned package wants to define an already-defined perm 16756 if (bp != null) { 16757 // If the defining package is signed with our cert, it's okay. This 16758 // also includes the "updating the same package" case, of course. 16759 // "updating same package" could also involve key-rotation. 16760 final boolean sigsOk; 16761 if (bp.sourcePackage.equals(pkg.packageName) 16762 && (bp.packageSetting instanceof PackageSetting) 16763 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16764 scanFlags))) { 16765 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16766 } else { 16767 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16768 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16769 } 16770 if (!sigsOk) { 16771 // If the owning package is the system itself, we log but allow 16772 // install to proceed; we fail the install on all other permission 16773 // redefinitions. 16774 if (!bp.sourcePackage.equals("android")) { 16775 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16776 + pkg.packageName + " attempting to redeclare permission " 16777 + perm.info.name + " already owned by " + bp.sourcePackage); 16778 res.origPermission = perm.info.name; 16779 res.origPackage = bp.sourcePackage; 16780 return; 16781 } else { 16782 Slog.w(TAG, "Package " + pkg.packageName 16783 + " attempting to redeclare system permission " 16784 + perm.info.name + "; ignoring new declaration"); 16785 pkg.permissions.remove(i); 16786 } 16787 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16788 // Prevent apps to change protection level to dangerous from any other 16789 // type as this would allow a privilege escalation where an app adds a 16790 // normal/signature permission in other app's group and later redefines 16791 // it as dangerous leading to the group auto-grant. 16792 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16793 == PermissionInfo.PROTECTION_DANGEROUS) { 16794 if (bp != null && !bp.isRuntime()) { 16795 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16796 + "non-runtime permission " + perm.info.name 16797 + " to runtime; keeping old protection level"); 16798 perm.info.protectionLevel = bp.protectionLevel; 16799 } 16800 } 16801 } 16802 } 16803 } 16804 } 16805 16806 if (systemApp) { 16807 if (onExternal) { 16808 // Abort update; system app can't be replaced with app on sdcard 16809 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16810 "Cannot install updates to system apps on sdcard"); 16811 return; 16812 } else if (instantApp) { 16813 // Abort update; system app can't be replaced with an instant app 16814 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16815 "Cannot update a system app with an instant app"); 16816 return; 16817 } 16818 } 16819 16820 if (args.move != null) { 16821 // We did an in-place move, so dex is ready to roll 16822 scanFlags |= SCAN_NO_DEX; 16823 scanFlags |= SCAN_MOVE; 16824 16825 synchronized (mPackages) { 16826 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16827 if (ps == null) { 16828 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16829 "Missing settings for moved package " + pkgName); 16830 } 16831 16832 // We moved the entire application as-is, so bring over the 16833 // previously derived ABI information. 16834 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16835 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16836 } 16837 16838 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16839 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16840 scanFlags |= SCAN_NO_DEX; 16841 16842 try { 16843 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16844 args.abiOverride : pkg.cpuAbiOverride); 16845 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16846 true /*extractLibs*/, mAppLib32InstallDir); 16847 } catch (PackageManagerException pme) { 16848 Slog.e(TAG, "Error deriving application ABI", pme); 16849 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16850 return; 16851 } 16852 16853 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16854 // Do not run PackageDexOptimizer through the local performDexOpt 16855 // method because `pkg` may not be in `mPackages` yet. 16856 // 16857 // Also, don't fail application installs if the dexopt step fails. 16858 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16859 null /* instructionSets */, false /* checkProfiles */, 16860 getCompilerFilterForReason(REASON_INSTALL), 16861 getOrCreateCompilerPackageStats(pkg), 16862 mDexManager.isUsedByOtherApps(pkg.packageName)); 16863 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16864 16865 // Notify BackgroundDexOptService that the package has been changed. 16866 // If this is an update of a package which used to fail to compile, 16867 // BDOS will remove it from its blacklist. 16868 // TODO: Layering violation 16869 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16870 } 16871 16872 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16873 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16874 return; 16875 } 16876 16877 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16878 16879 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16880 "installPackageLI")) { 16881 if (replace) { 16882 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16883 // Static libs have a synthetic package name containing the version 16884 // and cannot be updated as an update would get a new package name, 16885 // unless this is the exact same version code which is useful for 16886 // development. 16887 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16888 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 16889 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16890 + "static-shared libs cannot be updated"); 16891 return; 16892 } 16893 } 16894 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 16895 installerPackageName, res, args.installReason); 16896 } else { 16897 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16898 args.user, installerPackageName, volumeUuid, res, args.installReason); 16899 } 16900 } 16901 synchronized (mPackages) { 16902 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16903 if (ps != null) { 16904 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16905 ps.setUpdateAvailable(false /*updateAvailable*/); 16906 } 16907 16908 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16909 for (int i = 0; i < childCount; i++) { 16910 PackageParser.Package childPkg = pkg.childPackages.get(i); 16911 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16912 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16913 if (childPs != null) { 16914 childRes.newUsers = childPs.queryInstalledUsers( 16915 sUserManager.getUserIds(), true); 16916 } 16917 } 16918 16919 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16920 updateSequenceNumberLP(pkgName, res.newUsers); 16921 } 16922 } 16923 } 16924 16925 private void startIntentFilterVerifications(int userId, boolean replacing, 16926 PackageParser.Package pkg) { 16927 if (mIntentFilterVerifierComponent == null) { 16928 Slog.w(TAG, "No IntentFilter verification will not be done as " 16929 + "there is no IntentFilterVerifier available!"); 16930 return; 16931 } 16932 16933 final int verifierUid = getPackageUid( 16934 mIntentFilterVerifierComponent.getPackageName(), 16935 MATCH_DEBUG_TRIAGED_MISSING, 16936 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16937 16938 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16939 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16940 mHandler.sendMessage(msg); 16941 16942 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16943 for (int i = 0; i < childCount; i++) { 16944 PackageParser.Package childPkg = pkg.childPackages.get(i); 16945 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16946 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16947 mHandler.sendMessage(msg); 16948 } 16949 } 16950 16951 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16952 PackageParser.Package pkg) { 16953 int size = pkg.activities.size(); 16954 if (size == 0) { 16955 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16956 "No activity, so no need to verify any IntentFilter!"); 16957 return; 16958 } 16959 16960 final boolean hasDomainURLs = hasDomainURLs(pkg); 16961 if (!hasDomainURLs) { 16962 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16963 "No domain URLs, so no need to verify any IntentFilter!"); 16964 return; 16965 } 16966 16967 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16968 + " if any IntentFilter from the " + size 16969 + " Activities needs verification ..."); 16970 16971 int count = 0; 16972 final String packageName = pkg.packageName; 16973 16974 synchronized (mPackages) { 16975 // If this is a new install and we see that we've already run verification for this 16976 // package, we have nothing to do: it means the state was restored from backup. 16977 if (!replacing) { 16978 IntentFilterVerificationInfo ivi = 16979 mSettings.getIntentFilterVerificationLPr(packageName); 16980 if (ivi != null) { 16981 if (DEBUG_DOMAIN_VERIFICATION) { 16982 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 16983 + ivi.getStatusString()); 16984 } 16985 return; 16986 } 16987 } 16988 16989 // If any filters need to be verified, then all need to be. 16990 boolean needToVerify = false; 16991 for (PackageParser.Activity a : pkg.activities) { 16992 for (ActivityIntentInfo filter : a.intents) { 16993 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 16994 if (DEBUG_DOMAIN_VERIFICATION) { 16995 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 16996 } 16997 needToVerify = true; 16998 break; 16999 } 17000 } 17001 } 17002 17003 if (needToVerify) { 17004 final int verificationId = mIntentFilterVerificationToken++; 17005 for (PackageParser.Activity a : pkg.activities) { 17006 for (ActivityIntentInfo filter : a.intents) { 17007 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17008 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17009 "Verification needed for IntentFilter:" + filter.toString()); 17010 mIntentFilterVerifier.addOneIntentFilterVerification( 17011 verifierUid, userId, verificationId, filter, packageName); 17012 count++; 17013 } 17014 } 17015 } 17016 } 17017 } 17018 17019 if (count > 0) { 17020 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17021 + " IntentFilter verification" + (count > 1 ? "s" : "") 17022 + " for userId:" + userId); 17023 mIntentFilterVerifier.startVerifications(userId); 17024 } else { 17025 if (DEBUG_DOMAIN_VERIFICATION) { 17026 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17027 } 17028 } 17029 } 17030 17031 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17032 final ComponentName cn = filter.activity.getComponentName(); 17033 final String packageName = cn.getPackageName(); 17034 17035 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17036 packageName); 17037 if (ivi == null) { 17038 return true; 17039 } 17040 int status = ivi.getStatus(); 17041 switch (status) { 17042 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17043 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17044 return true; 17045 17046 default: 17047 // Nothing to do 17048 return false; 17049 } 17050 } 17051 17052 private static boolean isMultiArch(ApplicationInfo info) { 17053 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17054 } 17055 17056 private static boolean isExternal(PackageParser.Package pkg) { 17057 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17058 } 17059 17060 private static boolean isExternal(PackageSetting ps) { 17061 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17062 } 17063 17064 private static boolean isSystemApp(PackageParser.Package pkg) { 17065 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17066 } 17067 17068 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17069 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17070 } 17071 17072 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17073 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17074 } 17075 17076 private static boolean isSystemApp(PackageSetting ps) { 17077 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17078 } 17079 17080 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17081 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17082 } 17083 17084 private int packageFlagsToInstallFlags(PackageSetting ps) { 17085 int installFlags = 0; 17086 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17087 // This existing package was an external ASEC install when we have 17088 // the external flag without a UUID 17089 installFlags |= PackageManager.INSTALL_EXTERNAL; 17090 } 17091 if (ps.isForwardLocked()) { 17092 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17093 } 17094 return installFlags; 17095 } 17096 17097 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17098 if (isExternal(pkg)) { 17099 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17100 return StorageManager.UUID_PRIMARY_PHYSICAL; 17101 } else { 17102 return pkg.volumeUuid; 17103 } 17104 } else { 17105 return StorageManager.UUID_PRIVATE_INTERNAL; 17106 } 17107 } 17108 17109 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17110 if (isExternal(pkg)) { 17111 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17112 return mSettings.getExternalVersion(); 17113 } else { 17114 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17115 } 17116 } else { 17117 return mSettings.getInternalVersion(); 17118 } 17119 } 17120 17121 private void deleteTempPackageFiles() { 17122 final FilenameFilter filter = new FilenameFilter() { 17123 public boolean accept(File dir, String name) { 17124 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17125 } 17126 }; 17127 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17128 file.delete(); 17129 } 17130 } 17131 17132 @Override 17133 public void deletePackageAsUser(String packageName, int versionCode, 17134 IPackageDeleteObserver observer, int userId, int flags) { 17135 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17136 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17137 } 17138 17139 @Override 17140 public void deletePackageVersioned(VersionedPackage versionedPackage, 17141 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17142 mContext.enforceCallingOrSelfPermission( 17143 android.Manifest.permission.DELETE_PACKAGES, null); 17144 Preconditions.checkNotNull(versionedPackage); 17145 Preconditions.checkNotNull(observer); 17146 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17147 PackageManager.VERSION_CODE_HIGHEST, 17148 Integer.MAX_VALUE, "versionCode must be >= -1"); 17149 17150 final String packageName = versionedPackage.getPackageName(); 17151 // TODO: We will change version code to long, so in the new API it is long 17152 final int versionCode = (int) versionedPackage.getVersionCode(); 17153 final String internalPackageName; 17154 synchronized (mPackages) { 17155 // Normalize package name to handle renamed packages and static libs 17156 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17157 // TODO: We will change version code to long, so in the new API it is long 17158 (int) versionedPackage.getVersionCode()); 17159 } 17160 17161 final int uid = Binder.getCallingUid(); 17162 if (!isOrphaned(internalPackageName) 17163 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17164 try { 17165 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17166 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17167 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17168 observer.onUserActionRequired(intent); 17169 } catch (RemoteException re) { 17170 } 17171 return; 17172 } 17173 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17174 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17175 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17176 mContext.enforceCallingOrSelfPermission( 17177 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17178 "deletePackage for user " + userId); 17179 } 17180 17181 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17182 try { 17183 observer.onPackageDeleted(packageName, 17184 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17185 } catch (RemoteException re) { 17186 } 17187 return; 17188 } 17189 17190 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17191 try { 17192 observer.onPackageDeleted(packageName, 17193 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17194 } catch (RemoteException re) { 17195 } 17196 return; 17197 } 17198 17199 if (DEBUG_REMOVE) { 17200 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17201 + " deleteAllUsers: " + deleteAllUsers + " version=" 17202 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17203 ? "VERSION_CODE_HIGHEST" : versionCode)); 17204 } 17205 // Queue up an async operation since the package deletion may take a little while. 17206 mHandler.post(new Runnable() { 17207 public void run() { 17208 mHandler.removeCallbacks(this); 17209 int returnCode; 17210 if (!deleteAllUsers) { 17211 returnCode = deletePackageX(internalPackageName, versionCode, 17212 userId, deleteFlags); 17213 } else { 17214 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17215 internalPackageName, users); 17216 // If nobody is blocking uninstall, proceed with delete for all users 17217 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17218 returnCode = deletePackageX(internalPackageName, versionCode, 17219 userId, deleteFlags); 17220 } else { 17221 // Otherwise uninstall individually for users with blockUninstalls=false 17222 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17223 for (int userId : users) { 17224 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17225 returnCode = deletePackageX(internalPackageName, versionCode, 17226 userId, userFlags); 17227 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17228 Slog.w(TAG, "Package delete failed for user " + userId 17229 + ", returnCode " + returnCode); 17230 } 17231 } 17232 } 17233 // The app has only been marked uninstalled for certain users. 17234 // We still need to report that delete was blocked 17235 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17236 } 17237 } 17238 try { 17239 observer.onPackageDeleted(packageName, returnCode, null); 17240 } catch (RemoteException e) { 17241 Log.i(TAG, "Observer no longer exists."); 17242 } //end catch 17243 } //end run 17244 }); 17245 } 17246 17247 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17248 if (pkg.staticSharedLibName != null) { 17249 return pkg.manifestPackageName; 17250 } 17251 return pkg.packageName; 17252 } 17253 17254 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17255 // Handle renamed packages 17256 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17257 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17258 17259 // Is this a static library? 17260 SparseArray<SharedLibraryEntry> versionedLib = 17261 mStaticLibsByDeclaringPackage.get(packageName); 17262 if (versionedLib == null || versionedLib.size() <= 0) { 17263 return packageName; 17264 } 17265 17266 // Figure out which lib versions the caller can see 17267 SparseIntArray versionsCallerCanSee = null; 17268 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17269 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17270 && callingAppId != Process.ROOT_UID) { 17271 versionsCallerCanSee = new SparseIntArray(); 17272 String libName = versionedLib.valueAt(0).info.getName(); 17273 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17274 if (uidPackages != null) { 17275 for (String uidPackage : uidPackages) { 17276 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17277 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17278 if (libIdx >= 0) { 17279 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17280 versionsCallerCanSee.append(libVersion, libVersion); 17281 } 17282 } 17283 } 17284 } 17285 17286 // Caller can see nothing - done 17287 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17288 return packageName; 17289 } 17290 17291 // Find the version the caller can see and the app version code 17292 SharedLibraryEntry highestVersion = null; 17293 final int versionCount = versionedLib.size(); 17294 for (int i = 0; i < versionCount; i++) { 17295 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17296 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17297 libEntry.info.getVersion()) < 0) { 17298 continue; 17299 } 17300 // TODO: We will change version code to long, so in the new API it is long 17301 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17302 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17303 if (libVersionCode == versionCode) { 17304 return libEntry.apk; 17305 } 17306 } else if (highestVersion == null) { 17307 highestVersion = libEntry; 17308 } else if (libVersionCode > highestVersion.info 17309 .getDeclaringPackage().getVersionCode()) { 17310 highestVersion = libEntry; 17311 } 17312 } 17313 17314 if (highestVersion != null) { 17315 return highestVersion.apk; 17316 } 17317 17318 return packageName; 17319 } 17320 17321 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17322 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17323 || callingUid == Process.SYSTEM_UID) { 17324 return true; 17325 } 17326 final int callingUserId = UserHandle.getUserId(callingUid); 17327 // If the caller installed the pkgName, then allow it to silently uninstall. 17328 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17329 return true; 17330 } 17331 17332 // Allow package verifier to silently uninstall. 17333 if (mRequiredVerifierPackage != null && 17334 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17335 return true; 17336 } 17337 17338 // Allow package uninstaller to silently uninstall. 17339 if (mRequiredUninstallerPackage != null && 17340 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17341 return true; 17342 } 17343 17344 // Allow storage manager to silently uninstall. 17345 if (mStorageManagerPackage != null && 17346 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17347 return true; 17348 } 17349 return false; 17350 } 17351 17352 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17353 int[] result = EMPTY_INT_ARRAY; 17354 for (int userId : userIds) { 17355 if (getBlockUninstallForUser(packageName, userId)) { 17356 result = ArrayUtils.appendInt(result, userId); 17357 } 17358 } 17359 return result; 17360 } 17361 17362 @Override 17363 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17364 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17365 } 17366 17367 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17368 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17369 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17370 try { 17371 if (dpm != null) { 17372 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17373 /* callingUserOnly =*/ false); 17374 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17375 : deviceOwnerComponentName.getPackageName(); 17376 // Does the package contains the device owner? 17377 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17378 // this check is probably not needed, since DO should be registered as a device 17379 // admin on some user too. (Original bug for this: b/17657954) 17380 if (packageName.equals(deviceOwnerPackageName)) { 17381 return true; 17382 } 17383 // Does it contain a device admin for any user? 17384 int[] users; 17385 if (userId == UserHandle.USER_ALL) { 17386 users = sUserManager.getUserIds(); 17387 } else { 17388 users = new int[]{userId}; 17389 } 17390 for (int i = 0; i < users.length; ++i) { 17391 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17392 return true; 17393 } 17394 } 17395 } 17396 } catch (RemoteException e) { 17397 } 17398 return false; 17399 } 17400 17401 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17402 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17403 } 17404 17405 /** 17406 * This method is an internal method that could be get invoked either 17407 * to delete an installed package or to clean up a failed installation. 17408 * After deleting an installed package, a broadcast is sent to notify any 17409 * listeners that the package has been removed. For cleaning up a failed 17410 * installation, the broadcast is not necessary since the package's 17411 * installation wouldn't have sent the initial broadcast either 17412 * The key steps in deleting a package are 17413 * deleting the package information in internal structures like mPackages, 17414 * deleting the packages base directories through installd 17415 * updating mSettings to reflect current status 17416 * persisting settings for later use 17417 * sending a broadcast if necessary 17418 */ 17419 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17420 final PackageRemovedInfo info = new PackageRemovedInfo(); 17421 final boolean res; 17422 17423 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17424 ? UserHandle.USER_ALL : userId; 17425 17426 if (isPackageDeviceAdmin(packageName, removeUser)) { 17427 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17428 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17429 } 17430 17431 PackageSetting uninstalledPs = null; 17432 PackageParser.Package pkg = null; 17433 17434 // for the uninstall-updates case and restricted profiles, remember the per- 17435 // user handle installed state 17436 int[] allUsers; 17437 synchronized (mPackages) { 17438 uninstalledPs = mSettings.mPackages.get(packageName); 17439 if (uninstalledPs == null) { 17440 Slog.w(TAG, "Not removing non-existent package " + packageName); 17441 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17442 } 17443 17444 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17445 && uninstalledPs.versionCode != versionCode) { 17446 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17447 + uninstalledPs.versionCode + " != " + versionCode); 17448 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17449 } 17450 17451 // Static shared libs can be declared by any package, so let us not 17452 // allow removing a package if it provides a lib others depend on. 17453 pkg = mPackages.get(packageName); 17454 if (pkg != null && pkg.staticSharedLibName != null) { 17455 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17456 pkg.staticSharedLibVersion); 17457 if (libEntry != null) { 17458 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17459 libEntry.info, 0, userId); 17460 if (!ArrayUtils.isEmpty(libClientPackages)) { 17461 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17462 + " hosting lib " + libEntry.info.getName() + " version " 17463 + libEntry.info.getVersion() + " used by " + libClientPackages); 17464 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17465 } 17466 } 17467 } 17468 17469 allUsers = sUserManager.getUserIds(); 17470 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17471 } 17472 17473 final int freezeUser; 17474 if (isUpdatedSystemApp(uninstalledPs) 17475 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17476 // We're downgrading a system app, which will apply to all users, so 17477 // freeze them all during the downgrade 17478 freezeUser = UserHandle.USER_ALL; 17479 } else { 17480 freezeUser = removeUser; 17481 } 17482 17483 synchronized (mInstallLock) { 17484 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17485 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17486 deleteFlags, "deletePackageX")) { 17487 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17488 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17489 } 17490 synchronized (mPackages) { 17491 if (res) { 17492 if (pkg != null) { 17493 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17494 } 17495 updateSequenceNumberLP(packageName, info.removedUsers); 17496 } 17497 } 17498 } 17499 17500 if (res) { 17501 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17502 info.sendPackageRemovedBroadcasts(killApp); 17503 info.sendSystemPackageUpdatedBroadcasts(); 17504 info.sendSystemPackageAppearedBroadcasts(); 17505 } 17506 // Force a gc here. 17507 Runtime.getRuntime().gc(); 17508 // Delete the resources here after sending the broadcast to let 17509 // other processes clean up before deleting resources. 17510 if (info.args != null) { 17511 synchronized (mInstallLock) { 17512 info.args.doPostDeleteLI(true); 17513 } 17514 } 17515 17516 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17517 } 17518 17519 class PackageRemovedInfo { 17520 String removedPackage; 17521 int uid = -1; 17522 int removedAppId = -1; 17523 int[] origUsers; 17524 int[] removedUsers = null; 17525 SparseArray<Integer> installReasons; 17526 boolean isRemovedPackageSystemUpdate = false; 17527 boolean isUpdate; 17528 boolean dataRemoved; 17529 boolean removedForAllUsers; 17530 boolean isStaticSharedLib; 17531 // Clean up resources deleted packages. 17532 InstallArgs args = null; 17533 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17534 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17535 17536 void sendPackageRemovedBroadcasts(boolean killApp) { 17537 sendPackageRemovedBroadcastInternal(killApp); 17538 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17539 for (int i = 0; i < childCount; i++) { 17540 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17541 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17542 } 17543 } 17544 17545 void sendSystemPackageUpdatedBroadcasts() { 17546 if (isRemovedPackageSystemUpdate) { 17547 sendSystemPackageUpdatedBroadcastsInternal(); 17548 final int childCount = (removedChildPackages != null) 17549 ? removedChildPackages.size() : 0; 17550 for (int i = 0; i < childCount; i++) { 17551 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17552 if (childInfo.isRemovedPackageSystemUpdate) { 17553 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17554 } 17555 } 17556 } 17557 } 17558 17559 void sendSystemPackageAppearedBroadcasts() { 17560 final int packageCount = (appearedChildPackages != null) 17561 ? appearedChildPackages.size() : 0; 17562 for (int i = 0; i < packageCount; i++) { 17563 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17564 sendPackageAddedForNewUsers(installedInfo.name, true, 17565 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17566 } 17567 } 17568 17569 private void sendSystemPackageUpdatedBroadcastsInternal() { 17570 Bundle extras = new Bundle(2); 17571 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17572 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17573 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17574 extras, 0, null, null, null); 17575 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17576 extras, 0, null, null, null); 17577 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17578 null, 0, removedPackage, null, null); 17579 } 17580 17581 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17582 // Don't send static shared library removal broadcasts as these 17583 // libs are visible only the the apps that depend on them an one 17584 // cannot remove the library if it has a dependency. 17585 if (isStaticSharedLib) { 17586 return; 17587 } 17588 Bundle extras = new Bundle(2); 17589 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17590 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17591 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17592 if (isUpdate || isRemovedPackageSystemUpdate) { 17593 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17594 } 17595 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17596 if (removedPackage != null) { 17597 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17598 extras, 0, null, null, removedUsers); 17599 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17600 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17601 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17602 null, null, removedUsers); 17603 } 17604 } 17605 if (removedAppId >= 0) { 17606 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17607 removedUsers); 17608 } 17609 } 17610 } 17611 17612 /* 17613 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17614 * flag is not set, the data directory is removed as well. 17615 * make sure this flag is set for partially installed apps. If not its meaningless to 17616 * delete a partially installed application. 17617 */ 17618 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17619 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17620 String packageName = ps.name; 17621 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17622 // Retrieve object to delete permissions for shared user later on 17623 final PackageParser.Package deletedPkg; 17624 final PackageSetting deletedPs; 17625 // reader 17626 synchronized (mPackages) { 17627 deletedPkg = mPackages.get(packageName); 17628 deletedPs = mSettings.mPackages.get(packageName); 17629 if (outInfo != null) { 17630 outInfo.removedPackage = packageName; 17631 outInfo.isStaticSharedLib = deletedPkg != null 17632 && deletedPkg.staticSharedLibName != null; 17633 outInfo.removedUsers = deletedPs != null 17634 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17635 : null; 17636 } 17637 } 17638 17639 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17640 17641 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17642 final PackageParser.Package resolvedPkg; 17643 if (deletedPkg != null) { 17644 resolvedPkg = deletedPkg; 17645 } else { 17646 // We don't have a parsed package when it lives on an ejected 17647 // adopted storage device, so fake something together 17648 resolvedPkg = new PackageParser.Package(ps.name); 17649 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17650 } 17651 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17652 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17653 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17654 if (outInfo != null) { 17655 outInfo.dataRemoved = true; 17656 } 17657 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17658 } 17659 17660 int removedAppId = -1; 17661 17662 // writer 17663 synchronized (mPackages) { 17664 boolean installedStateChanged = false; 17665 if (deletedPs != null) { 17666 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17667 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17668 clearDefaultBrowserIfNeeded(packageName); 17669 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17670 removedAppId = mSettings.removePackageLPw(packageName); 17671 if (outInfo != null) { 17672 outInfo.removedAppId = removedAppId; 17673 } 17674 updatePermissionsLPw(deletedPs.name, null, 0); 17675 if (deletedPs.sharedUser != null) { 17676 // Remove permissions associated with package. Since runtime 17677 // permissions are per user we have to kill the removed package 17678 // or packages running under the shared user of the removed 17679 // package if revoking the permissions requested only by the removed 17680 // package is successful and this causes a change in gids. 17681 for (int userId : UserManagerService.getInstance().getUserIds()) { 17682 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17683 userId); 17684 if (userIdToKill == UserHandle.USER_ALL 17685 || userIdToKill >= UserHandle.USER_SYSTEM) { 17686 // If gids changed for this user, kill all affected packages. 17687 mHandler.post(new Runnable() { 17688 @Override 17689 public void run() { 17690 // This has to happen with no lock held. 17691 killApplication(deletedPs.name, deletedPs.appId, 17692 KILL_APP_REASON_GIDS_CHANGED); 17693 } 17694 }); 17695 break; 17696 } 17697 } 17698 } 17699 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17700 } 17701 // make sure to preserve per-user disabled state if this removal was just 17702 // a downgrade of a system app to the factory package 17703 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17704 if (DEBUG_REMOVE) { 17705 Slog.d(TAG, "Propagating install state across downgrade"); 17706 } 17707 for (int userId : allUserHandles) { 17708 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17709 if (DEBUG_REMOVE) { 17710 Slog.d(TAG, " user " + userId + " => " + installed); 17711 } 17712 if (installed != ps.getInstalled(userId)) { 17713 installedStateChanged = true; 17714 } 17715 ps.setInstalled(installed, userId); 17716 } 17717 } 17718 } 17719 // can downgrade to reader 17720 if (writeSettings) { 17721 // Save settings now 17722 mSettings.writeLPr(); 17723 } 17724 if (installedStateChanged) { 17725 mSettings.writeKernelMappingLPr(ps); 17726 } 17727 } 17728 if (removedAppId != -1) { 17729 // A user ID was deleted here. Go through all users and remove it 17730 // from KeyStore. 17731 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17732 } 17733 } 17734 17735 static boolean locationIsPrivileged(File path) { 17736 try { 17737 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17738 .getCanonicalPath(); 17739 return path.getCanonicalPath().startsWith(privilegedAppDir); 17740 } catch (IOException e) { 17741 Slog.e(TAG, "Unable to access code path " + path); 17742 } 17743 return false; 17744 } 17745 17746 /* 17747 * Tries to delete system package. 17748 */ 17749 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17750 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17751 boolean writeSettings) { 17752 if (deletedPs.parentPackageName != null) { 17753 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17754 return false; 17755 } 17756 17757 final boolean applyUserRestrictions 17758 = (allUserHandles != null) && (outInfo.origUsers != null); 17759 final PackageSetting disabledPs; 17760 // Confirm if the system package has been updated 17761 // An updated system app can be deleted. This will also have to restore 17762 // the system pkg from system partition 17763 // reader 17764 synchronized (mPackages) { 17765 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17766 } 17767 17768 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17769 + " disabledPs=" + disabledPs); 17770 17771 if (disabledPs == null) { 17772 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17773 return false; 17774 } else if (DEBUG_REMOVE) { 17775 Slog.d(TAG, "Deleting system pkg from data partition"); 17776 } 17777 17778 if (DEBUG_REMOVE) { 17779 if (applyUserRestrictions) { 17780 Slog.d(TAG, "Remembering install states:"); 17781 for (int userId : allUserHandles) { 17782 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17783 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17784 } 17785 } 17786 } 17787 17788 // Delete the updated package 17789 outInfo.isRemovedPackageSystemUpdate = true; 17790 if (outInfo.removedChildPackages != null) { 17791 final int childCount = (deletedPs.childPackageNames != null) 17792 ? deletedPs.childPackageNames.size() : 0; 17793 for (int i = 0; i < childCount; i++) { 17794 String childPackageName = deletedPs.childPackageNames.get(i); 17795 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17796 .contains(childPackageName)) { 17797 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17798 childPackageName); 17799 if (childInfo != null) { 17800 childInfo.isRemovedPackageSystemUpdate = true; 17801 } 17802 } 17803 } 17804 } 17805 17806 if (disabledPs.versionCode < deletedPs.versionCode) { 17807 // Delete data for downgrades 17808 flags &= ~PackageManager.DELETE_KEEP_DATA; 17809 } else { 17810 // Preserve data by setting flag 17811 flags |= PackageManager.DELETE_KEEP_DATA; 17812 } 17813 17814 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17815 outInfo, writeSettings, disabledPs.pkg); 17816 if (!ret) { 17817 return false; 17818 } 17819 17820 // writer 17821 synchronized (mPackages) { 17822 // Reinstate the old system package 17823 enableSystemPackageLPw(disabledPs.pkg); 17824 // Remove any native libraries from the upgraded package. 17825 removeNativeBinariesLI(deletedPs); 17826 } 17827 17828 // Install the system package 17829 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17830 int parseFlags = mDefParseFlags 17831 | PackageParser.PARSE_MUST_BE_APK 17832 | PackageParser.PARSE_IS_SYSTEM 17833 | PackageParser.PARSE_IS_SYSTEM_DIR; 17834 if (locationIsPrivileged(disabledPs.codePath)) { 17835 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 17836 } 17837 17838 final PackageParser.Package newPkg; 17839 try { 17840 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 17841 0 /* currentTime */, null); 17842 } catch (PackageManagerException e) { 17843 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17844 + e.getMessage()); 17845 return false; 17846 } 17847 17848 try { 17849 // update shared libraries for the newly re-installed system package 17850 updateSharedLibrariesLPr(newPkg, null); 17851 } catch (PackageManagerException e) { 17852 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17853 } 17854 17855 prepareAppDataAfterInstallLIF(newPkg); 17856 17857 // writer 17858 synchronized (mPackages) { 17859 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 17860 17861 // Propagate the permissions state as we do not want to drop on the floor 17862 // runtime permissions. The update permissions method below will take 17863 // care of removing obsolete permissions and grant install permissions. 17864 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 17865 updatePermissionsLPw(newPkg.packageName, newPkg, 17866 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 17867 17868 if (applyUserRestrictions) { 17869 boolean installedStateChanged = false; 17870 if (DEBUG_REMOVE) { 17871 Slog.d(TAG, "Propagating install state across reinstall"); 17872 } 17873 for (int userId : allUserHandles) { 17874 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17875 if (DEBUG_REMOVE) { 17876 Slog.d(TAG, " user " + userId + " => " + installed); 17877 } 17878 if (installed != ps.getInstalled(userId)) { 17879 installedStateChanged = true; 17880 } 17881 ps.setInstalled(installed, userId); 17882 17883 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17884 } 17885 // Regardless of writeSettings we need to ensure that this restriction 17886 // state propagation is persisted 17887 mSettings.writeAllUsersPackageRestrictionsLPr(); 17888 if (installedStateChanged) { 17889 mSettings.writeKernelMappingLPr(ps); 17890 } 17891 } 17892 // can downgrade to reader here 17893 if (writeSettings) { 17894 mSettings.writeLPr(); 17895 } 17896 } 17897 return true; 17898 } 17899 17900 private boolean deleteInstalledPackageLIF(PackageSetting ps, 17901 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 17902 PackageRemovedInfo outInfo, boolean writeSettings, 17903 PackageParser.Package replacingPackage) { 17904 synchronized (mPackages) { 17905 if (outInfo != null) { 17906 outInfo.uid = ps.appId; 17907 } 17908 17909 if (outInfo != null && outInfo.removedChildPackages != null) { 17910 final int childCount = (ps.childPackageNames != null) 17911 ? ps.childPackageNames.size() : 0; 17912 for (int i = 0; i < childCount; i++) { 17913 String childPackageName = ps.childPackageNames.get(i); 17914 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 17915 if (childPs == null) { 17916 return false; 17917 } 17918 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17919 childPackageName); 17920 if (childInfo != null) { 17921 childInfo.uid = childPs.appId; 17922 } 17923 } 17924 } 17925 } 17926 17927 // Delete package data from internal structures and also remove data if flag is set 17928 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 17929 17930 // Delete the child packages data 17931 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 17932 for (int i = 0; i < childCount; i++) { 17933 PackageSetting childPs; 17934 synchronized (mPackages) { 17935 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 17936 } 17937 if (childPs != null) { 17938 PackageRemovedInfo childOutInfo = (outInfo != null 17939 && outInfo.removedChildPackages != null) 17940 ? outInfo.removedChildPackages.get(childPs.name) : null; 17941 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 17942 && (replacingPackage != null 17943 && !replacingPackage.hasChildPackage(childPs.name)) 17944 ? flags & ~DELETE_KEEP_DATA : flags; 17945 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 17946 deleteFlags, writeSettings); 17947 } 17948 } 17949 17950 // Delete application code and resources only for parent packages 17951 if (ps.parentPackageName == null) { 17952 if (deleteCodeAndResources && (outInfo != null)) { 17953 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 17954 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 17955 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 17956 } 17957 } 17958 17959 return true; 17960 } 17961 17962 @Override 17963 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 17964 int userId) { 17965 mContext.enforceCallingOrSelfPermission( 17966 android.Manifest.permission.DELETE_PACKAGES, null); 17967 synchronized (mPackages) { 17968 PackageSetting ps = mSettings.mPackages.get(packageName); 17969 if (ps == null) { 17970 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 17971 return false; 17972 } 17973 // Cannot block uninstall of static shared libs as they are 17974 // considered a part of the using app (emulating static linking). 17975 // Also static libs are installed always on internal storage. 17976 PackageParser.Package pkg = mPackages.get(packageName); 17977 if (pkg != null && pkg.staticSharedLibName != null) { 17978 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 17979 + " providing static shared library: " + pkg.staticSharedLibName); 17980 return false; 17981 } 17982 if (!ps.getInstalled(userId)) { 17983 // Can't block uninstall for an app that is not installed or enabled. 17984 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 17985 return false; 17986 } 17987 ps.setBlockUninstall(blockUninstall, userId); 17988 mSettings.writePackageRestrictionsLPr(userId); 17989 } 17990 return true; 17991 } 17992 17993 @Override 17994 public boolean getBlockUninstallForUser(String packageName, int userId) { 17995 synchronized (mPackages) { 17996 PackageSetting ps = mSettings.mPackages.get(packageName); 17997 if (ps == null) { 17998 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 17999 return false; 18000 } 18001 return ps.getBlockUninstall(userId); 18002 } 18003 } 18004 18005 @Override 18006 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18007 int callingUid = Binder.getCallingUid(); 18008 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18009 throw new SecurityException( 18010 "setRequiredForSystemUser can only be run by the system or root"); 18011 } 18012 synchronized (mPackages) { 18013 PackageSetting ps = mSettings.mPackages.get(packageName); 18014 if (ps == null) { 18015 Log.w(TAG, "Package doesn't exist: " + packageName); 18016 return false; 18017 } 18018 if (systemUserApp) { 18019 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18020 } else { 18021 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18022 } 18023 mSettings.writeLPr(); 18024 } 18025 return true; 18026 } 18027 18028 /* 18029 * This method handles package deletion in general 18030 */ 18031 private boolean deletePackageLIF(String packageName, UserHandle user, 18032 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18033 PackageRemovedInfo outInfo, boolean writeSettings, 18034 PackageParser.Package replacingPackage) { 18035 if (packageName == null) { 18036 Slog.w(TAG, "Attempt to delete null packageName."); 18037 return false; 18038 } 18039 18040 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18041 18042 PackageSetting ps; 18043 synchronized (mPackages) { 18044 ps = mSettings.mPackages.get(packageName); 18045 if (ps == null) { 18046 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18047 return false; 18048 } 18049 18050 if (ps.parentPackageName != null && (!isSystemApp(ps) 18051 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18052 if (DEBUG_REMOVE) { 18053 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18054 + ((user == null) ? UserHandle.USER_ALL : user)); 18055 } 18056 final int removedUserId = (user != null) ? user.getIdentifier() 18057 : UserHandle.USER_ALL; 18058 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18059 return false; 18060 } 18061 markPackageUninstalledForUserLPw(ps, user); 18062 scheduleWritePackageRestrictionsLocked(user); 18063 return true; 18064 } 18065 } 18066 18067 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18068 && user.getIdentifier() != UserHandle.USER_ALL)) { 18069 // The caller is asking that the package only be deleted for a single 18070 // user. To do this, we just mark its uninstalled state and delete 18071 // its data. If this is a system app, we only allow this to happen if 18072 // they have set the special DELETE_SYSTEM_APP which requests different 18073 // semantics than normal for uninstalling system apps. 18074 markPackageUninstalledForUserLPw(ps, user); 18075 18076 if (!isSystemApp(ps)) { 18077 // Do not uninstall the APK if an app should be cached 18078 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18079 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18080 // Other user still have this package installed, so all 18081 // we need to do is clear this user's data and save that 18082 // it is uninstalled. 18083 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18084 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18085 return false; 18086 } 18087 scheduleWritePackageRestrictionsLocked(user); 18088 return true; 18089 } else { 18090 // We need to set it back to 'installed' so the uninstall 18091 // broadcasts will be sent correctly. 18092 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18093 ps.setInstalled(true, user.getIdentifier()); 18094 mSettings.writeKernelMappingLPr(ps); 18095 } 18096 } else { 18097 // This is a system app, so we assume that the 18098 // other users still have this package installed, so all 18099 // we need to do is clear this user's data and save that 18100 // it is uninstalled. 18101 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18102 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18103 return false; 18104 } 18105 scheduleWritePackageRestrictionsLocked(user); 18106 return true; 18107 } 18108 } 18109 18110 // If we are deleting a composite package for all users, keep track 18111 // of result for each child. 18112 if (ps.childPackageNames != null && outInfo != null) { 18113 synchronized (mPackages) { 18114 final int childCount = ps.childPackageNames.size(); 18115 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18116 for (int i = 0; i < childCount; i++) { 18117 String childPackageName = ps.childPackageNames.get(i); 18118 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18119 childInfo.removedPackage = childPackageName; 18120 outInfo.removedChildPackages.put(childPackageName, childInfo); 18121 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18122 if (childPs != null) { 18123 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18124 } 18125 } 18126 } 18127 } 18128 18129 boolean ret = false; 18130 if (isSystemApp(ps)) { 18131 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18132 // When an updated system application is deleted we delete the existing resources 18133 // as well and fall back to existing code in system partition 18134 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18135 } else { 18136 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18137 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18138 outInfo, writeSettings, replacingPackage); 18139 } 18140 18141 // Take a note whether we deleted the package for all users 18142 if (outInfo != null) { 18143 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18144 if (outInfo.removedChildPackages != null) { 18145 synchronized (mPackages) { 18146 final int childCount = outInfo.removedChildPackages.size(); 18147 for (int i = 0; i < childCount; i++) { 18148 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18149 if (childInfo != null) { 18150 childInfo.removedForAllUsers = mPackages.get( 18151 childInfo.removedPackage) == null; 18152 } 18153 } 18154 } 18155 } 18156 // If we uninstalled an update to a system app there may be some 18157 // child packages that appeared as they are declared in the system 18158 // app but were not declared in the update. 18159 if (isSystemApp(ps)) { 18160 synchronized (mPackages) { 18161 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18162 final int childCount = (updatedPs.childPackageNames != null) 18163 ? updatedPs.childPackageNames.size() : 0; 18164 for (int i = 0; i < childCount; i++) { 18165 String childPackageName = updatedPs.childPackageNames.get(i); 18166 if (outInfo.removedChildPackages == null 18167 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18168 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18169 if (childPs == null) { 18170 continue; 18171 } 18172 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18173 installRes.name = childPackageName; 18174 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18175 installRes.pkg = mPackages.get(childPackageName); 18176 installRes.uid = childPs.pkg.applicationInfo.uid; 18177 if (outInfo.appearedChildPackages == null) { 18178 outInfo.appearedChildPackages = new ArrayMap<>(); 18179 } 18180 outInfo.appearedChildPackages.put(childPackageName, installRes); 18181 } 18182 } 18183 } 18184 } 18185 } 18186 18187 return ret; 18188 } 18189 18190 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18191 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18192 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18193 for (int nextUserId : userIds) { 18194 if (DEBUG_REMOVE) { 18195 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18196 } 18197 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18198 false /*installed*/, 18199 true /*stopped*/, 18200 true /*notLaunched*/, 18201 false /*hidden*/, 18202 false /*suspended*/, 18203 false /*instantApp*/, 18204 null /*lastDisableAppCaller*/, 18205 null /*enabledComponents*/, 18206 null /*disabledComponents*/, 18207 false /*blockUninstall*/, 18208 ps.readUserState(nextUserId).domainVerificationStatus, 18209 0, PackageManager.INSTALL_REASON_UNKNOWN); 18210 } 18211 mSettings.writeKernelMappingLPr(ps); 18212 } 18213 18214 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18215 PackageRemovedInfo outInfo) { 18216 final PackageParser.Package pkg; 18217 synchronized (mPackages) { 18218 pkg = mPackages.get(ps.name); 18219 } 18220 18221 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18222 : new int[] {userId}; 18223 for (int nextUserId : userIds) { 18224 if (DEBUG_REMOVE) { 18225 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18226 + nextUserId); 18227 } 18228 18229 destroyAppDataLIF(pkg, userId, 18230 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18231 destroyAppProfilesLIF(pkg, userId); 18232 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18233 schedulePackageCleaning(ps.name, nextUserId, false); 18234 synchronized (mPackages) { 18235 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18236 scheduleWritePackageRestrictionsLocked(nextUserId); 18237 } 18238 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18239 } 18240 } 18241 18242 if (outInfo != null) { 18243 outInfo.removedPackage = ps.name; 18244 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18245 outInfo.removedAppId = ps.appId; 18246 outInfo.removedUsers = userIds; 18247 } 18248 18249 return true; 18250 } 18251 18252 private final class ClearStorageConnection implements ServiceConnection { 18253 IMediaContainerService mContainerService; 18254 18255 @Override 18256 public void onServiceConnected(ComponentName name, IBinder service) { 18257 synchronized (this) { 18258 mContainerService = IMediaContainerService.Stub 18259 .asInterface(Binder.allowBlocking(service)); 18260 notifyAll(); 18261 } 18262 } 18263 18264 @Override 18265 public void onServiceDisconnected(ComponentName name) { 18266 } 18267 } 18268 18269 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18270 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18271 18272 final boolean mounted; 18273 if (Environment.isExternalStorageEmulated()) { 18274 mounted = true; 18275 } else { 18276 final String status = Environment.getExternalStorageState(); 18277 18278 mounted = status.equals(Environment.MEDIA_MOUNTED) 18279 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18280 } 18281 18282 if (!mounted) { 18283 return; 18284 } 18285 18286 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18287 int[] users; 18288 if (userId == UserHandle.USER_ALL) { 18289 users = sUserManager.getUserIds(); 18290 } else { 18291 users = new int[] { userId }; 18292 } 18293 final ClearStorageConnection conn = new ClearStorageConnection(); 18294 if (mContext.bindServiceAsUser( 18295 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18296 try { 18297 for (int curUser : users) { 18298 long timeout = SystemClock.uptimeMillis() + 5000; 18299 synchronized (conn) { 18300 long now; 18301 while (conn.mContainerService == null && 18302 (now = SystemClock.uptimeMillis()) < timeout) { 18303 try { 18304 conn.wait(timeout - now); 18305 } catch (InterruptedException e) { 18306 } 18307 } 18308 } 18309 if (conn.mContainerService == null) { 18310 return; 18311 } 18312 18313 final UserEnvironment userEnv = new UserEnvironment(curUser); 18314 clearDirectory(conn.mContainerService, 18315 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18316 if (allData) { 18317 clearDirectory(conn.mContainerService, 18318 userEnv.buildExternalStorageAppDataDirs(packageName)); 18319 clearDirectory(conn.mContainerService, 18320 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18321 } 18322 } 18323 } finally { 18324 mContext.unbindService(conn); 18325 } 18326 } 18327 } 18328 18329 @Override 18330 public void clearApplicationProfileData(String packageName) { 18331 enforceSystemOrRoot("Only the system can clear all profile data"); 18332 18333 final PackageParser.Package pkg; 18334 synchronized (mPackages) { 18335 pkg = mPackages.get(packageName); 18336 } 18337 18338 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18339 synchronized (mInstallLock) { 18340 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18341 } 18342 } 18343 } 18344 18345 @Override 18346 public void clearApplicationUserData(final String packageName, 18347 final IPackageDataObserver observer, final int userId) { 18348 mContext.enforceCallingOrSelfPermission( 18349 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18350 18351 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18352 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18353 18354 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18355 throw new SecurityException("Cannot clear data for a protected package: " 18356 + packageName); 18357 } 18358 // Queue up an async operation since the package deletion may take a little while. 18359 mHandler.post(new Runnable() { 18360 public void run() { 18361 mHandler.removeCallbacks(this); 18362 final boolean succeeded; 18363 try (PackageFreezer freezer = freezePackage(packageName, 18364 "clearApplicationUserData")) { 18365 synchronized (mInstallLock) { 18366 succeeded = clearApplicationUserDataLIF(packageName, userId); 18367 } 18368 clearExternalStorageDataSync(packageName, userId, true); 18369 synchronized (mPackages) { 18370 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18371 packageName, userId); 18372 } 18373 } 18374 if (succeeded) { 18375 // invoke DeviceStorageMonitor's update method to clear any notifications 18376 DeviceStorageMonitorInternal dsm = LocalServices 18377 .getService(DeviceStorageMonitorInternal.class); 18378 if (dsm != null) { 18379 dsm.checkMemory(); 18380 } 18381 } 18382 if(observer != null) { 18383 try { 18384 observer.onRemoveCompleted(packageName, succeeded); 18385 } catch (RemoteException e) { 18386 Log.i(TAG, "Observer no longer exists."); 18387 } 18388 } //end if observer 18389 } //end run 18390 }); 18391 } 18392 18393 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18394 if (packageName == null) { 18395 Slog.w(TAG, "Attempt to delete null packageName."); 18396 return false; 18397 } 18398 18399 // Try finding details about the requested package 18400 PackageParser.Package pkg; 18401 synchronized (mPackages) { 18402 pkg = mPackages.get(packageName); 18403 if (pkg == null) { 18404 final PackageSetting ps = mSettings.mPackages.get(packageName); 18405 if (ps != null) { 18406 pkg = ps.pkg; 18407 } 18408 } 18409 18410 if (pkg == null) { 18411 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18412 return false; 18413 } 18414 18415 PackageSetting ps = (PackageSetting) pkg.mExtras; 18416 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18417 } 18418 18419 clearAppDataLIF(pkg, userId, 18420 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18421 18422 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18423 removeKeystoreDataIfNeeded(userId, appId); 18424 18425 UserManagerInternal umInternal = getUserManagerInternal(); 18426 final int flags; 18427 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18428 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18429 } else if (umInternal.isUserRunning(userId)) { 18430 flags = StorageManager.FLAG_STORAGE_DE; 18431 } else { 18432 flags = 0; 18433 } 18434 prepareAppDataContentsLIF(pkg, userId, flags); 18435 18436 return true; 18437 } 18438 18439 /** 18440 * Reverts user permission state changes (permissions and flags) in 18441 * all packages for a given user. 18442 * 18443 * @param userId The device user for which to do a reset. 18444 */ 18445 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18446 final int packageCount = mPackages.size(); 18447 for (int i = 0; i < packageCount; i++) { 18448 PackageParser.Package pkg = mPackages.valueAt(i); 18449 PackageSetting ps = (PackageSetting) pkg.mExtras; 18450 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18451 } 18452 } 18453 18454 private void resetNetworkPolicies(int userId) { 18455 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18456 } 18457 18458 /** 18459 * Reverts user permission state changes (permissions and flags). 18460 * 18461 * @param ps The package for which to reset. 18462 * @param userId The device user for which to do a reset. 18463 */ 18464 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18465 final PackageSetting ps, final int userId) { 18466 if (ps.pkg == null) { 18467 return; 18468 } 18469 18470 // These are flags that can change base on user actions. 18471 final int userSettableMask = FLAG_PERMISSION_USER_SET 18472 | FLAG_PERMISSION_USER_FIXED 18473 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18474 | FLAG_PERMISSION_REVIEW_REQUIRED; 18475 18476 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18477 | FLAG_PERMISSION_POLICY_FIXED; 18478 18479 boolean writeInstallPermissions = false; 18480 boolean writeRuntimePermissions = false; 18481 18482 final int permissionCount = ps.pkg.requestedPermissions.size(); 18483 for (int i = 0; i < permissionCount; i++) { 18484 String permission = ps.pkg.requestedPermissions.get(i); 18485 18486 BasePermission bp = mSettings.mPermissions.get(permission); 18487 if (bp == null) { 18488 continue; 18489 } 18490 18491 // If shared user we just reset the state to which only this app contributed. 18492 if (ps.sharedUser != null) { 18493 boolean used = false; 18494 final int packageCount = ps.sharedUser.packages.size(); 18495 for (int j = 0; j < packageCount; j++) { 18496 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18497 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18498 && pkg.pkg.requestedPermissions.contains(permission)) { 18499 used = true; 18500 break; 18501 } 18502 } 18503 if (used) { 18504 continue; 18505 } 18506 } 18507 18508 PermissionsState permissionsState = ps.getPermissionsState(); 18509 18510 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18511 18512 // Always clear the user settable flags. 18513 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18514 bp.name) != null; 18515 // If permission review is enabled and this is a legacy app, mark the 18516 // permission as requiring a review as this is the initial state. 18517 int flags = 0; 18518 if (mPermissionReviewRequired 18519 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18520 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18521 } 18522 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18523 if (hasInstallState) { 18524 writeInstallPermissions = true; 18525 } else { 18526 writeRuntimePermissions = true; 18527 } 18528 } 18529 18530 // Below is only runtime permission handling. 18531 if (!bp.isRuntime()) { 18532 continue; 18533 } 18534 18535 // Never clobber system or policy. 18536 if ((oldFlags & policyOrSystemFlags) != 0) { 18537 continue; 18538 } 18539 18540 // If this permission was granted by default, make sure it is. 18541 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18542 if (permissionsState.grantRuntimePermission(bp, userId) 18543 != PERMISSION_OPERATION_FAILURE) { 18544 writeRuntimePermissions = true; 18545 } 18546 // If permission review is enabled the permissions for a legacy apps 18547 // are represented as constantly granted runtime ones, so don't revoke. 18548 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18549 // Otherwise, reset the permission. 18550 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18551 switch (revokeResult) { 18552 case PERMISSION_OPERATION_SUCCESS: 18553 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18554 writeRuntimePermissions = true; 18555 final int appId = ps.appId; 18556 mHandler.post(new Runnable() { 18557 @Override 18558 public void run() { 18559 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18560 } 18561 }); 18562 } break; 18563 } 18564 } 18565 } 18566 18567 // Synchronously write as we are taking permissions away. 18568 if (writeRuntimePermissions) { 18569 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18570 } 18571 18572 // Synchronously write as we are taking permissions away. 18573 if (writeInstallPermissions) { 18574 mSettings.writeLPr(); 18575 } 18576 } 18577 18578 /** 18579 * Remove entries from the keystore daemon. Will only remove it if the 18580 * {@code appId} is valid. 18581 */ 18582 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18583 if (appId < 0) { 18584 return; 18585 } 18586 18587 final KeyStore keyStore = KeyStore.getInstance(); 18588 if (keyStore != null) { 18589 if (userId == UserHandle.USER_ALL) { 18590 for (final int individual : sUserManager.getUserIds()) { 18591 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18592 } 18593 } else { 18594 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18595 } 18596 } else { 18597 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18598 } 18599 } 18600 18601 @Override 18602 public void deleteApplicationCacheFiles(final String packageName, 18603 final IPackageDataObserver observer) { 18604 final int userId = UserHandle.getCallingUserId(); 18605 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18606 } 18607 18608 @Override 18609 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18610 final IPackageDataObserver observer) { 18611 mContext.enforceCallingOrSelfPermission( 18612 android.Manifest.permission.DELETE_CACHE_FILES, null); 18613 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18614 /* requireFullPermission= */ true, /* checkShell= */ false, 18615 "delete application cache files"); 18616 18617 final PackageParser.Package pkg; 18618 synchronized (mPackages) { 18619 pkg = mPackages.get(packageName); 18620 } 18621 18622 // Queue up an async operation since the package deletion may take a little while. 18623 mHandler.post(new Runnable() { 18624 public void run() { 18625 synchronized (mInstallLock) { 18626 final int flags = StorageManager.FLAG_STORAGE_DE 18627 | StorageManager.FLAG_STORAGE_CE; 18628 // We're only clearing cache files, so we don't care if the 18629 // app is unfrozen and still able to run 18630 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18631 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18632 } 18633 clearExternalStorageDataSync(packageName, userId, false); 18634 if (observer != null) { 18635 try { 18636 observer.onRemoveCompleted(packageName, true); 18637 } catch (RemoteException e) { 18638 Log.i(TAG, "Observer no longer exists."); 18639 } 18640 } 18641 } 18642 }); 18643 } 18644 18645 @Override 18646 public void getPackageSizeInfo(final String packageName, int userHandle, 18647 final IPackageStatsObserver observer) { 18648 throw new UnsupportedOperationException( 18649 "Shame on you for calling a hidden API. Shame!"); 18650 } 18651 18652 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18653 final PackageSetting ps; 18654 synchronized (mPackages) { 18655 ps = mSettings.mPackages.get(packageName); 18656 if (ps == null) { 18657 Slog.w(TAG, "Failed to find settings for " + packageName); 18658 return false; 18659 } 18660 } 18661 18662 final String[] packageNames = { packageName }; 18663 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18664 final String[] codePaths = { ps.codePathString }; 18665 18666 try { 18667 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18668 ps.appId, ceDataInodes, codePaths, stats); 18669 18670 // For now, ignore code size of packages on system partition 18671 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18672 stats.codeSize = 0; 18673 } 18674 18675 // External clients expect these to be tracked separately 18676 stats.dataSize -= stats.cacheSize; 18677 18678 } catch (InstallerException e) { 18679 Slog.w(TAG, String.valueOf(e)); 18680 return false; 18681 } 18682 18683 return true; 18684 } 18685 18686 private int getUidTargetSdkVersionLockedLPr(int uid) { 18687 Object obj = mSettings.getUserIdLPr(uid); 18688 if (obj instanceof SharedUserSetting) { 18689 final SharedUserSetting sus = (SharedUserSetting) obj; 18690 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18691 final Iterator<PackageSetting> it = sus.packages.iterator(); 18692 while (it.hasNext()) { 18693 final PackageSetting ps = it.next(); 18694 if (ps.pkg != null) { 18695 int v = ps.pkg.applicationInfo.targetSdkVersion; 18696 if (v < vers) vers = v; 18697 } 18698 } 18699 return vers; 18700 } else if (obj instanceof PackageSetting) { 18701 final PackageSetting ps = (PackageSetting) obj; 18702 if (ps.pkg != null) { 18703 return ps.pkg.applicationInfo.targetSdkVersion; 18704 } 18705 } 18706 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18707 } 18708 18709 @Override 18710 public void addPreferredActivity(IntentFilter filter, int match, 18711 ComponentName[] set, ComponentName activity, int userId) { 18712 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18713 "Adding preferred"); 18714 } 18715 18716 private void addPreferredActivityInternal(IntentFilter filter, int match, 18717 ComponentName[] set, ComponentName activity, boolean always, int userId, 18718 String opname) { 18719 // writer 18720 int callingUid = Binder.getCallingUid(); 18721 enforceCrossUserPermission(callingUid, userId, 18722 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18723 if (filter.countActions() == 0) { 18724 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18725 return; 18726 } 18727 synchronized (mPackages) { 18728 if (mContext.checkCallingOrSelfPermission( 18729 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18730 != PackageManager.PERMISSION_GRANTED) { 18731 if (getUidTargetSdkVersionLockedLPr(callingUid) 18732 < Build.VERSION_CODES.FROYO) { 18733 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18734 + callingUid); 18735 return; 18736 } 18737 mContext.enforceCallingOrSelfPermission( 18738 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18739 } 18740 18741 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18742 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18743 + userId + ":"); 18744 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18745 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18746 scheduleWritePackageRestrictionsLocked(userId); 18747 postPreferredActivityChangedBroadcast(userId); 18748 } 18749 } 18750 18751 private void postPreferredActivityChangedBroadcast(int userId) { 18752 mHandler.post(() -> { 18753 final IActivityManager am = ActivityManager.getService(); 18754 if (am == null) { 18755 return; 18756 } 18757 18758 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18759 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18760 try { 18761 am.broadcastIntent(null, intent, null, null, 18762 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18763 null, false, false, userId); 18764 } catch (RemoteException e) { 18765 } 18766 }); 18767 } 18768 18769 @Override 18770 public void replacePreferredActivity(IntentFilter filter, int match, 18771 ComponentName[] set, ComponentName activity, int userId) { 18772 if (filter.countActions() != 1) { 18773 throw new IllegalArgumentException( 18774 "replacePreferredActivity expects filter to have only 1 action."); 18775 } 18776 if (filter.countDataAuthorities() != 0 18777 || filter.countDataPaths() != 0 18778 || filter.countDataSchemes() > 1 18779 || filter.countDataTypes() != 0) { 18780 throw new IllegalArgumentException( 18781 "replacePreferredActivity expects filter to have no data authorities, " + 18782 "paths, or types; and at most one scheme."); 18783 } 18784 18785 final int callingUid = Binder.getCallingUid(); 18786 enforceCrossUserPermission(callingUid, userId, 18787 true /* requireFullPermission */, false /* checkShell */, 18788 "replace preferred activity"); 18789 synchronized (mPackages) { 18790 if (mContext.checkCallingOrSelfPermission( 18791 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18792 != PackageManager.PERMISSION_GRANTED) { 18793 if (getUidTargetSdkVersionLockedLPr(callingUid) 18794 < Build.VERSION_CODES.FROYO) { 18795 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18796 + Binder.getCallingUid()); 18797 return; 18798 } 18799 mContext.enforceCallingOrSelfPermission( 18800 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18801 } 18802 18803 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18804 if (pir != null) { 18805 // Get all of the existing entries that exactly match this filter. 18806 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18807 if (existing != null && existing.size() == 1) { 18808 PreferredActivity cur = existing.get(0); 18809 if (DEBUG_PREFERRED) { 18810 Slog.i(TAG, "Checking replace of preferred:"); 18811 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18812 if (!cur.mPref.mAlways) { 18813 Slog.i(TAG, " -- CUR; not mAlways!"); 18814 } else { 18815 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18816 Slog.i(TAG, " -- CUR: mSet=" 18817 + Arrays.toString(cur.mPref.mSetComponents)); 18818 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18819 Slog.i(TAG, " -- NEW: mMatch=" 18820 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18821 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18822 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18823 } 18824 } 18825 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18826 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18827 && cur.mPref.sameSet(set)) { 18828 // Setting the preferred activity to what it happens to be already 18829 if (DEBUG_PREFERRED) { 18830 Slog.i(TAG, "Replacing with same preferred activity " 18831 + cur.mPref.mShortComponent + " for user " 18832 + userId + ":"); 18833 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18834 } 18835 return; 18836 } 18837 } 18838 18839 if (existing != null) { 18840 if (DEBUG_PREFERRED) { 18841 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 18842 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18843 } 18844 for (int i = 0; i < existing.size(); i++) { 18845 PreferredActivity pa = existing.get(i); 18846 if (DEBUG_PREFERRED) { 18847 Slog.i(TAG, "Removing existing preferred activity " 18848 + pa.mPref.mComponent + ":"); 18849 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 18850 } 18851 pir.removeFilter(pa); 18852 } 18853 } 18854 } 18855 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18856 "Replacing preferred"); 18857 } 18858 } 18859 18860 @Override 18861 public void clearPackagePreferredActivities(String packageName) { 18862 final int uid = Binder.getCallingUid(); 18863 // writer 18864 synchronized (mPackages) { 18865 PackageParser.Package pkg = mPackages.get(packageName); 18866 if (pkg == null || pkg.applicationInfo.uid != uid) { 18867 if (mContext.checkCallingOrSelfPermission( 18868 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18869 != PackageManager.PERMISSION_GRANTED) { 18870 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 18871 < Build.VERSION_CODES.FROYO) { 18872 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 18873 + Binder.getCallingUid()); 18874 return; 18875 } 18876 mContext.enforceCallingOrSelfPermission( 18877 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18878 } 18879 } 18880 18881 int user = UserHandle.getCallingUserId(); 18882 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 18883 scheduleWritePackageRestrictionsLocked(user); 18884 } 18885 } 18886 } 18887 18888 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18889 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 18890 ArrayList<PreferredActivity> removed = null; 18891 boolean changed = false; 18892 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18893 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 18894 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18895 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 18896 continue; 18897 } 18898 Iterator<PreferredActivity> it = pir.filterIterator(); 18899 while (it.hasNext()) { 18900 PreferredActivity pa = it.next(); 18901 // Mark entry for removal only if it matches the package name 18902 // and the entry is of type "always". 18903 if (packageName == null || 18904 (pa.mPref.mComponent.getPackageName().equals(packageName) 18905 && pa.mPref.mAlways)) { 18906 if (removed == null) { 18907 removed = new ArrayList<PreferredActivity>(); 18908 } 18909 removed.add(pa); 18910 } 18911 } 18912 if (removed != null) { 18913 for (int j=0; j<removed.size(); j++) { 18914 PreferredActivity pa = removed.get(j); 18915 pir.removeFilter(pa); 18916 } 18917 changed = true; 18918 } 18919 } 18920 if (changed) { 18921 postPreferredActivityChangedBroadcast(userId); 18922 } 18923 return changed; 18924 } 18925 18926 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18927 private void clearIntentFilterVerificationsLPw(int userId) { 18928 final int packageCount = mPackages.size(); 18929 for (int i = 0; i < packageCount; i++) { 18930 PackageParser.Package pkg = mPackages.valueAt(i); 18931 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 18932 } 18933 } 18934 18935 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 18936 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 18937 if (userId == UserHandle.USER_ALL) { 18938 if (mSettings.removeIntentFilterVerificationLPw(packageName, 18939 sUserManager.getUserIds())) { 18940 for (int oneUserId : sUserManager.getUserIds()) { 18941 scheduleWritePackageRestrictionsLocked(oneUserId); 18942 } 18943 } 18944 } else { 18945 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 18946 scheduleWritePackageRestrictionsLocked(userId); 18947 } 18948 } 18949 } 18950 18951 void clearDefaultBrowserIfNeeded(String packageName) { 18952 for (int oneUserId : sUserManager.getUserIds()) { 18953 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 18954 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 18955 if (packageName.equals(defaultBrowserPackageName)) { 18956 setDefaultBrowserPackageName(null, oneUserId); 18957 } 18958 } 18959 } 18960 18961 @Override 18962 public void resetApplicationPreferences(int userId) { 18963 mContext.enforceCallingOrSelfPermission( 18964 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18965 final long identity = Binder.clearCallingIdentity(); 18966 // writer 18967 try { 18968 synchronized (mPackages) { 18969 clearPackagePreferredActivitiesLPw(null, userId); 18970 mSettings.applyDefaultPreferredAppsLPw(this, userId); 18971 // TODO: We have to reset the default SMS and Phone. This requires 18972 // significant refactoring to keep all default apps in the package 18973 // manager (cleaner but more work) or have the services provide 18974 // callbacks to the package manager to request a default app reset. 18975 applyFactoryDefaultBrowserLPw(userId); 18976 clearIntentFilterVerificationsLPw(userId); 18977 primeDomainVerificationsLPw(userId); 18978 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 18979 scheduleWritePackageRestrictionsLocked(userId); 18980 } 18981 resetNetworkPolicies(userId); 18982 } finally { 18983 Binder.restoreCallingIdentity(identity); 18984 } 18985 } 18986 18987 @Override 18988 public int getPreferredActivities(List<IntentFilter> outFilters, 18989 List<ComponentName> outActivities, String packageName) { 18990 18991 int num = 0; 18992 final int userId = UserHandle.getCallingUserId(); 18993 // reader 18994 synchronized (mPackages) { 18995 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18996 if (pir != null) { 18997 final Iterator<PreferredActivity> it = pir.filterIterator(); 18998 while (it.hasNext()) { 18999 final PreferredActivity pa = it.next(); 19000 if (packageName == null 19001 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19002 && pa.mPref.mAlways)) { 19003 if (outFilters != null) { 19004 outFilters.add(new IntentFilter(pa)); 19005 } 19006 if (outActivities != null) { 19007 outActivities.add(pa.mPref.mComponent); 19008 } 19009 } 19010 } 19011 } 19012 } 19013 19014 return num; 19015 } 19016 19017 @Override 19018 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19019 int userId) { 19020 int callingUid = Binder.getCallingUid(); 19021 if (callingUid != Process.SYSTEM_UID) { 19022 throw new SecurityException( 19023 "addPersistentPreferredActivity can only be run by the system"); 19024 } 19025 if (filter.countActions() == 0) { 19026 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19027 return; 19028 } 19029 synchronized (mPackages) { 19030 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19031 ":"); 19032 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19033 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19034 new PersistentPreferredActivity(filter, activity)); 19035 scheduleWritePackageRestrictionsLocked(userId); 19036 postPreferredActivityChangedBroadcast(userId); 19037 } 19038 } 19039 19040 @Override 19041 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19042 int callingUid = Binder.getCallingUid(); 19043 if (callingUid != Process.SYSTEM_UID) { 19044 throw new SecurityException( 19045 "clearPackagePersistentPreferredActivities can only be run by the system"); 19046 } 19047 ArrayList<PersistentPreferredActivity> removed = null; 19048 boolean changed = false; 19049 synchronized (mPackages) { 19050 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19051 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19052 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19053 .valueAt(i); 19054 if (userId != thisUserId) { 19055 continue; 19056 } 19057 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19058 while (it.hasNext()) { 19059 PersistentPreferredActivity ppa = it.next(); 19060 // Mark entry for removal only if it matches the package name. 19061 if (ppa.mComponent.getPackageName().equals(packageName)) { 19062 if (removed == null) { 19063 removed = new ArrayList<PersistentPreferredActivity>(); 19064 } 19065 removed.add(ppa); 19066 } 19067 } 19068 if (removed != null) { 19069 for (int j=0; j<removed.size(); j++) { 19070 PersistentPreferredActivity ppa = removed.get(j); 19071 ppir.removeFilter(ppa); 19072 } 19073 changed = true; 19074 } 19075 } 19076 19077 if (changed) { 19078 scheduleWritePackageRestrictionsLocked(userId); 19079 postPreferredActivityChangedBroadcast(userId); 19080 } 19081 } 19082 } 19083 19084 /** 19085 * Common machinery for picking apart a restored XML blob and passing 19086 * it to a caller-supplied functor to be applied to the running system. 19087 */ 19088 private void restoreFromXml(XmlPullParser parser, int userId, 19089 String expectedStartTag, BlobXmlRestorer functor) 19090 throws IOException, XmlPullParserException { 19091 int type; 19092 while ((type = parser.next()) != XmlPullParser.START_TAG 19093 && type != XmlPullParser.END_DOCUMENT) { 19094 } 19095 if (type != XmlPullParser.START_TAG) { 19096 // oops didn't find a start tag?! 19097 if (DEBUG_BACKUP) { 19098 Slog.e(TAG, "Didn't find start tag during restore"); 19099 } 19100 return; 19101 } 19102Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19103 // this is supposed to be TAG_PREFERRED_BACKUP 19104 if (!expectedStartTag.equals(parser.getName())) { 19105 if (DEBUG_BACKUP) { 19106 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19107 } 19108 return; 19109 } 19110 19111 // skip interfering stuff, then we're aligned with the backing implementation 19112 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19113Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19114 functor.apply(parser, userId); 19115 } 19116 19117 private interface BlobXmlRestorer { 19118 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19119 } 19120 19121 /** 19122 * Non-Binder method, support for the backup/restore mechanism: write the 19123 * full set of preferred activities in its canonical XML format. Returns the 19124 * XML output as a byte array, or null if there is none. 19125 */ 19126 @Override 19127 public byte[] getPreferredActivityBackup(int userId) { 19128 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19129 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19130 } 19131 19132 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19133 try { 19134 final XmlSerializer serializer = new FastXmlSerializer(); 19135 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19136 serializer.startDocument(null, true); 19137 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19138 19139 synchronized (mPackages) { 19140 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19141 } 19142 19143 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19144 serializer.endDocument(); 19145 serializer.flush(); 19146 } catch (Exception e) { 19147 if (DEBUG_BACKUP) { 19148 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19149 } 19150 return null; 19151 } 19152 19153 return dataStream.toByteArray(); 19154 } 19155 19156 @Override 19157 public void restorePreferredActivities(byte[] backup, int userId) { 19158 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19159 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19160 } 19161 19162 try { 19163 final XmlPullParser parser = Xml.newPullParser(); 19164 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19165 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19166 new BlobXmlRestorer() { 19167 @Override 19168 public void apply(XmlPullParser parser, int userId) 19169 throws XmlPullParserException, IOException { 19170 synchronized (mPackages) { 19171 mSettings.readPreferredActivitiesLPw(parser, userId); 19172 } 19173 } 19174 } ); 19175 } catch (Exception e) { 19176 if (DEBUG_BACKUP) { 19177 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19178 } 19179 } 19180 } 19181 19182 /** 19183 * Non-Binder method, support for the backup/restore mechanism: write the 19184 * default browser (etc) settings in its canonical XML format. Returns the default 19185 * browser XML representation as a byte array, or null if there is none. 19186 */ 19187 @Override 19188 public byte[] getDefaultAppsBackup(int userId) { 19189 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19190 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19191 } 19192 19193 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19194 try { 19195 final XmlSerializer serializer = new FastXmlSerializer(); 19196 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19197 serializer.startDocument(null, true); 19198 serializer.startTag(null, TAG_DEFAULT_APPS); 19199 19200 synchronized (mPackages) { 19201 mSettings.writeDefaultAppsLPr(serializer, userId); 19202 } 19203 19204 serializer.endTag(null, TAG_DEFAULT_APPS); 19205 serializer.endDocument(); 19206 serializer.flush(); 19207 } catch (Exception e) { 19208 if (DEBUG_BACKUP) { 19209 Slog.e(TAG, "Unable to write default apps for backup", e); 19210 } 19211 return null; 19212 } 19213 19214 return dataStream.toByteArray(); 19215 } 19216 19217 @Override 19218 public void restoreDefaultApps(byte[] backup, int userId) { 19219 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19220 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19221 } 19222 19223 try { 19224 final XmlPullParser parser = Xml.newPullParser(); 19225 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19226 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19227 new BlobXmlRestorer() { 19228 @Override 19229 public void apply(XmlPullParser parser, int userId) 19230 throws XmlPullParserException, IOException { 19231 synchronized (mPackages) { 19232 mSettings.readDefaultAppsLPw(parser, userId); 19233 } 19234 } 19235 } ); 19236 } catch (Exception e) { 19237 if (DEBUG_BACKUP) { 19238 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19239 } 19240 } 19241 } 19242 19243 @Override 19244 public byte[] getIntentFilterVerificationBackup(int userId) { 19245 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19246 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19247 } 19248 19249 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19250 try { 19251 final XmlSerializer serializer = new FastXmlSerializer(); 19252 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19253 serializer.startDocument(null, true); 19254 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19255 19256 synchronized (mPackages) { 19257 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19258 } 19259 19260 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19261 serializer.endDocument(); 19262 serializer.flush(); 19263 } catch (Exception e) { 19264 if (DEBUG_BACKUP) { 19265 Slog.e(TAG, "Unable to write default apps for backup", e); 19266 } 19267 return null; 19268 } 19269 19270 return dataStream.toByteArray(); 19271 } 19272 19273 @Override 19274 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19275 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19276 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19277 } 19278 19279 try { 19280 final XmlPullParser parser = Xml.newPullParser(); 19281 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19282 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19283 new BlobXmlRestorer() { 19284 @Override 19285 public void apply(XmlPullParser parser, int userId) 19286 throws XmlPullParserException, IOException { 19287 synchronized (mPackages) { 19288 mSettings.readAllDomainVerificationsLPr(parser, userId); 19289 mSettings.writeLPr(); 19290 } 19291 } 19292 } ); 19293 } catch (Exception e) { 19294 if (DEBUG_BACKUP) { 19295 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19296 } 19297 } 19298 } 19299 19300 @Override 19301 public byte[] getPermissionGrantBackup(int userId) { 19302 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19303 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19304 } 19305 19306 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19307 try { 19308 final XmlSerializer serializer = new FastXmlSerializer(); 19309 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19310 serializer.startDocument(null, true); 19311 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19312 19313 synchronized (mPackages) { 19314 serializeRuntimePermissionGrantsLPr(serializer, userId); 19315 } 19316 19317 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19318 serializer.endDocument(); 19319 serializer.flush(); 19320 } catch (Exception e) { 19321 if (DEBUG_BACKUP) { 19322 Slog.e(TAG, "Unable to write default apps for backup", e); 19323 } 19324 return null; 19325 } 19326 19327 return dataStream.toByteArray(); 19328 } 19329 19330 @Override 19331 public void restorePermissionGrants(byte[] backup, int userId) { 19332 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19333 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19334 } 19335 19336 try { 19337 final XmlPullParser parser = Xml.newPullParser(); 19338 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19339 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19340 new BlobXmlRestorer() { 19341 @Override 19342 public void apply(XmlPullParser parser, int userId) 19343 throws XmlPullParserException, IOException { 19344 synchronized (mPackages) { 19345 processRestoredPermissionGrantsLPr(parser, userId); 19346 } 19347 } 19348 } ); 19349 } catch (Exception e) { 19350 if (DEBUG_BACKUP) { 19351 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19352 } 19353 } 19354 } 19355 19356 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19357 throws IOException { 19358 serializer.startTag(null, TAG_ALL_GRANTS); 19359 19360 final int N = mSettings.mPackages.size(); 19361 for (int i = 0; i < N; i++) { 19362 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19363 boolean pkgGrantsKnown = false; 19364 19365 PermissionsState packagePerms = ps.getPermissionsState(); 19366 19367 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19368 final int grantFlags = state.getFlags(); 19369 // only look at grants that are not system/policy fixed 19370 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19371 final boolean isGranted = state.isGranted(); 19372 // And only back up the user-twiddled state bits 19373 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19374 final String packageName = mSettings.mPackages.keyAt(i); 19375 if (!pkgGrantsKnown) { 19376 serializer.startTag(null, TAG_GRANT); 19377 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19378 pkgGrantsKnown = true; 19379 } 19380 19381 final boolean userSet = 19382 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19383 final boolean userFixed = 19384 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19385 final boolean revoke = 19386 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19387 19388 serializer.startTag(null, TAG_PERMISSION); 19389 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19390 if (isGranted) { 19391 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19392 } 19393 if (userSet) { 19394 serializer.attribute(null, ATTR_USER_SET, "true"); 19395 } 19396 if (userFixed) { 19397 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19398 } 19399 if (revoke) { 19400 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19401 } 19402 serializer.endTag(null, TAG_PERMISSION); 19403 } 19404 } 19405 } 19406 19407 if (pkgGrantsKnown) { 19408 serializer.endTag(null, TAG_GRANT); 19409 } 19410 } 19411 19412 serializer.endTag(null, TAG_ALL_GRANTS); 19413 } 19414 19415 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19416 throws XmlPullParserException, IOException { 19417 String pkgName = null; 19418 int outerDepth = parser.getDepth(); 19419 int type; 19420 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19421 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19422 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19423 continue; 19424 } 19425 19426 final String tagName = parser.getName(); 19427 if (tagName.equals(TAG_GRANT)) { 19428 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19429 if (DEBUG_BACKUP) { 19430 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19431 } 19432 } else if (tagName.equals(TAG_PERMISSION)) { 19433 19434 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19435 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19436 19437 int newFlagSet = 0; 19438 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19439 newFlagSet |= FLAG_PERMISSION_USER_SET; 19440 } 19441 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19442 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19443 } 19444 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19445 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19446 } 19447 if (DEBUG_BACKUP) { 19448 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19449 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19450 } 19451 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19452 if (ps != null) { 19453 // Already installed so we apply the grant immediately 19454 if (DEBUG_BACKUP) { 19455 Slog.v(TAG, " + already installed; applying"); 19456 } 19457 PermissionsState perms = ps.getPermissionsState(); 19458 BasePermission bp = mSettings.mPermissions.get(permName); 19459 if (bp != null) { 19460 if (isGranted) { 19461 perms.grantRuntimePermission(bp, userId); 19462 } 19463 if (newFlagSet != 0) { 19464 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19465 } 19466 } 19467 } else { 19468 // Need to wait for post-restore install to apply the grant 19469 if (DEBUG_BACKUP) { 19470 Slog.v(TAG, " - not yet installed; saving for later"); 19471 } 19472 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19473 isGranted, newFlagSet, userId); 19474 } 19475 } else { 19476 PackageManagerService.reportSettingsProblem(Log.WARN, 19477 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19478 XmlUtils.skipCurrentTag(parser); 19479 } 19480 } 19481 19482 scheduleWriteSettingsLocked(); 19483 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19484 } 19485 19486 @Override 19487 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19488 int sourceUserId, int targetUserId, int flags) { 19489 mContext.enforceCallingOrSelfPermission( 19490 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19491 int callingUid = Binder.getCallingUid(); 19492 enforceOwnerRights(ownerPackage, callingUid); 19493 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19494 if (intentFilter.countActions() == 0) { 19495 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19496 return; 19497 } 19498 synchronized (mPackages) { 19499 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19500 ownerPackage, targetUserId, flags); 19501 CrossProfileIntentResolver resolver = 19502 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19503 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19504 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19505 if (existing != null) { 19506 int size = existing.size(); 19507 for (int i = 0; i < size; i++) { 19508 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19509 return; 19510 } 19511 } 19512 } 19513 resolver.addFilter(newFilter); 19514 scheduleWritePackageRestrictionsLocked(sourceUserId); 19515 } 19516 } 19517 19518 @Override 19519 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19520 mContext.enforceCallingOrSelfPermission( 19521 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19522 int callingUid = Binder.getCallingUid(); 19523 enforceOwnerRights(ownerPackage, callingUid); 19524 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19525 synchronized (mPackages) { 19526 CrossProfileIntentResolver resolver = 19527 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19528 ArraySet<CrossProfileIntentFilter> set = 19529 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19530 for (CrossProfileIntentFilter filter : set) { 19531 if (filter.getOwnerPackage().equals(ownerPackage)) { 19532 resolver.removeFilter(filter); 19533 } 19534 } 19535 scheduleWritePackageRestrictionsLocked(sourceUserId); 19536 } 19537 } 19538 19539 // Enforcing that callingUid is owning pkg on userId 19540 private void enforceOwnerRights(String pkg, int callingUid) { 19541 // The system owns everything. 19542 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19543 return; 19544 } 19545 int callingUserId = UserHandle.getUserId(callingUid); 19546 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19547 if (pi == null) { 19548 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19549 + callingUserId); 19550 } 19551 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19552 throw new SecurityException("Calling uid " + callingUid 19553 + " does not own package " + pkg); 19554 } 19555 } 19556 19557 @Override 19558 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19559 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19560 } 19561 19562 /** 19563 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19564 * then reports the most likely home activity or null if there are more than one. 19565 */ 19566 public ComponentName getDefaultHomeActivity(int userId) { 19567 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19568 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19569 if (cn != null) { 19570 return cn; 19571 } 19572 19573 // Find the launcher with the highest priority and return that component if there are no 19574 // other home activity with the same priority. 19575 int lastPriority = Integer.MIN_VALUE; 19576 ComponentName lastComponent = null; 19577 final int size = allHomeCandidates.size(); 19578 for (int i = 0; i < size; i++) { 19579 final ResolveInfo ri = allHomeCandidates.get(i); 19580 if (ri.priority > lastPriority) { 19581 lastComponent = ri.activityInfo.getComponentName(); 19582 lastPriority = ri.priority; 19583 } else if (ri.priority == lastPriority) { 19584 // Two components found with same priority. 19585 lastComponent = null; 19586 } 19587 } 19588 return lastComponent; 19589 } 19590 19591 private Intent getHomeIntent() { 19592 Intent intent = new Intent(Intent.ACTION_MAIN); 19593 intent.addCategory(Intent.CATEGORY_HOME); 19594 intent.addCategory(Intent.CATEGORY_DEFAULT); 19595 return intent; 19596 } 19597 19598 private IntentFilter getHomeFilter() { 19599 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19600 filter.addCategory(Intent.CATEGORY_HOME); 19601 filter.addCategory(Intent.CATEGORY_DEFAULT); 19602 return filter; 19603 } 19604 19605 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19606 int userId) { 19607 Intent intent = getHomeIntent(); 19608 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19609 PackageManager.GET_META_DATA, userId); 19610 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19611 true, false, false, userId); 19612 19613 allHomeCandidates.clear(); 19614 if (list != null) { 19615 for (ResolveInfo ri : list) { 19616 allHomeCandidates.add(ri); 19617 } 19618 } 19619 return (preferred == null || preferred.activityInfo == null) 19620 ? null 19621 : new ComponentName(preferred.activityInfo.packageName, 19622 preferred.activityInfo.name); 19623 } 19624 19625 @Override 19626 public void setHomeActivity(ComponentName comp, int userId) { 19627 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19628 getHomeActivitiesAsUser(homeActivities, userId); 19629 19630 boolean found = false; 19631 19632 final int size = homeActivities.size(); 19633 final ComponentName[] set = new ComponentName[size]; 19634 for (int i = 0; i < size; i++) { 19635 final ResolveInfo candidate = homeActivities.get(i); 19636 final ActivityInfo info = candidate.activityInfo; 19637 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19638 set[i] = activityName; 19639 if (!found && activityName.equals(comp)) { 19640 found = true; 19641 } 19642 } 19643 if (!found) { 19644 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19645 + userId); 19646 } 19647 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19648 set, comp, userId); 19649 } 19650 19651 private @Nullable String getSetupWizardPackageName() { 19652 final Intent intent = new Intent(Intent.ACTION_MAIN); 19653 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19654 19655 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19656 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19657 | MATCH_DISABLED_COMPONENTS, 19658 UserHandle.myUserId()); 19659 if (matches.size() == 1) { 19660 return matches.get(0).getComponentInfo().packageName; 19661 } else { 19662 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19663 + ": matches=" + matches); 19664 return null; 19665 } 19666 } 19667 19668 private @Nullable String getStorageManagerPackageName() { 19669 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19670 19671 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19672 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19673 | MATCH_DISABLED_COMPONENTS, 19674 UserHandle.myUserId()); 19675 if (matches.size() == 1) { 19676 return matches.get(0).getComponentInfo().packageName; 19677 } else { 19678 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19679 + matches.size() + ": matches=" + matches); 19680 return null; 19681 } 19682 } 19683 19684 @Override 19685 public void setApplicationEnabledSetting(String appPackageName, 19686 int newState, int flags, int userId, String callingPackage) { 19687 if (!sUserManager.exists(userId)) return; 19688 if (callingPackage == null) { 19689 callingPackage = Integer.toString(Binder.getCallingUid()); 19690 } 19691 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19692 } 19693 19694 @Override 19695 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19696 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19697 synchronized (mPackages) { 19698 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19699 if (pkgSetting != null) { 19700 pkgSetting.setUpdateAvailable(updateAvailable); 19701 } 19702 } 19703 } 19704 19705 @Override 19706 public void setComponentEnabledSetting(ComponentName componentName, 19707 int newState, int flags, int userId) { 19708 if (!sUserManager.exists(userId)) return; 19709 setEnabledSetting(componentName.getPackageName(), 19710 componentName.getClassName(), newState, flags, userId, null); 19711 } 19712 19713 private void setEnabledSetting(final String packageName, String className, int newState, 19714 final int flags, int userId, String callingPackage) { 19715 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19716 || newState == COMPONENT_ENABLED_STATE_ENABLED 19717 || newState == COMPONENT_ENABLED_STATE_DISABLED 19718 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19719 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19720 throw new IllegalArgumentException("Invalid new component state: " 19721 + newState); 19722 } 19723 PackageSetting pkgSetting; 19724 final int uid = Binder.getCallingUid(); 19725 final int permission; 19726 if (uid == Process.SYSTEM_UID) { 19727 permission = PackageManager.PERMISSION_GRANTED; 19728 } else { 19729 permission = mContext.checkCallingOrSelfPermission( 19730 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19731 } 19732 enforceCrossUserPermission(uid, userId, 19733 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19734 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19735 boolean sendNow = false; 19736 boolean isApp = (className == null); 19737 String componentName = isApp ? packageName : className; 19738 int packageUid = -1; 19739 ArrayList<String> components; 19740 19741 // writer 19742 synchronized (mPackages) { 19743 pkgSetting = mSettings.mPackages.get(packageName); 19744 if (pkgSetting == null) { 19745 if (className == null) { 19746 throw new IllegalArgumentException("Unknown package: " + packageName); 19747 } 19748 throw new IllegalArgumentException( 19749 "Unknown component: " + packageName + "/" + className); 19750 } 19751 } 19752 19753 // Limit who can change which apps 19754 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19755 // Don't allow apps that don't have permission to modify other apps 19756 if (!allowedByPermission) { 19757 throw new SecurityException( 19758 "Permission Denial: attempt to change component state from pid=" 19759 + Binder.getCallingPid() 19760 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19761 } 19762 // Don't allow changing protected packages. 19763 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19764 throw new SecurityException("Cannot disable a protected package: " + packageName); 19765 } 19766 } 19767 19768 synchronized (mPackages) { 19769 if (uid == Process.SHELL_UID 19770 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19771 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19772 // unless it is a test package. 19773 int oldState = pkgSetting.getEnabled(userId); 19774 if (className == null 19775 && 19776 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19777 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19778 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19779 && 19780 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19781 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19782 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19783 // ok 19784 } else { 19785 throw new SecurityException( 19786 "Shell cannot change component state for " + packageName + "/" 19787 + className + " to " + newState); 19788 } 19789 } 19790 if (className == null) { 19791 // We're dealing with an application/package level state change 19792 if (pkgSetting.getEnabled(userId) == newState) { 19793 // Nothing to do 19794 return; 19795 } 19796 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19797 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19798 // Don't care about who enables an app. 19799 callingPackage = null; 19800 } 19801 pkgSetting.setEnabled(newState, userId, callingPackage); 19802 // pkgSetting.pkg.mSetEnabled = newState; 19803 } else { 19804 // We're dealing with a component level state change 19805 // First, verify that this is a valid class name. 19806 PackageParser.Package pkg = pkgSetting.pkg; 19807 if (pkg == null || !pkg.hasComponentClassName(className)) { 19808 if (pkg != null && 19809 pkg.applicationInfo.targetSdkVersion >= 19810 Build.VERSION_CODES.JELLY_BEAN) { 19811 throw new IllegalArgumentException("Component class " + className 19812 + " does not exist in " + packageName); 19813 } else { 19814 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19815 + className + " does not exist in " + packageName); 19816 } 19817 } 19818 switch (newState) { 19819 case COMPONENT_ENABLED_STATE_ENABLED: 19820 if (!pkgSetting.enableComponentLPw(className, userId)) { 19821 return; 19822 } 19823 break; 19824 case COMPONENT_ENABLED_STATE_DISABLED: 19825 if (!pkgSetting.disableComponentLPw(className, userId)) { 19826 return; 19827 } 19828 break; 19829 case COMPONENT_ENABLED_STATE_DEFAULT: 19830 if (!pkgSetting.restoreComponentLPw(className, userId)) { 19831 return; 19832 } 19833 break; 19834 default: 19835 Slog.e(TAG, "Invalid new component state: " + newState); 19836 return; 19837 } 19838 } 19839 scheduleWritePackageRestrictionsLocked(userId); 19840 updateSequenceNumberLP(packageName, new int[] { userId }); 19841 components = mPendingBroadcasts.get(userId, packageName); 19842 final boolean newPackage = components == null; 19843 if (newPackage) { 19844 components = new ArrayList<String>(); 19845 } 19846 if (!components.contains(componentName)) { 19847 components.add(componentName); 19848 } 19849 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 19850 sendNow = true; 19851 // Purge entry from pending broadcast list if another one exists already 19852 // since we are sending one right away. 19853 mPendingBroadcasts.remove(userId, packageName); 19854 } else { 19855 if (newPackage) { 19856 mPendingBroadcasts.put(userId, packageName, components); 19857 } 19858 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 19859 // Schedule a message 19860 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 19861 } 19862 } 19863 } 19864 19865 long callingId = Binder.clearCallingIdentity(); 19866 try { 19867 if (sendNow) { 19868 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 19869 sendPackageChangedBroadcast(packageName, 19870 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 19871 } 19872 } finally { 19873 Binder.restoreCallingIdentity(callingId); 19874 } 19875 } 19876 19877 @Override 19878 public void flushPackageRestrictionsAsUser(int userId) { 19879 if (!sUserManager.exists(userId)) { 19880 return; 19881 } 19882 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 19883 false /* checkShell */, "flushPackageRestrictions"); 19884 synchronized (mPackages) { 19885 mSettings.writePackageRestrictionsLPr(userId); 19886 mDirtyUsers.remove(userId); 19887 if (mDirtyUsers.isEmpty()) { 19888 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 19889 } 19890 } 19891 } 19892 19893 private void sendPackageChangedBroadcast(String packageName, 19894 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 19895 if (DEBUG_INSTALL) 19896 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 19897 + componentNames); 19898 Bundle extras = new Bundle(4); 19899 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 19900 String nameList[] = new String[componentNames.size()]; 19901 componentNames.toArray(nameList); 19902 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 19903 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 19904 extras.putInt(Intent.EXTRA_UID, packageUid); 19905 // If this is not reporting a change of the overall package, then only send it 19906 // to registered receivers. We don't want to launch a swath of apps for every 19907 // little component state change. 19908 final int flags = !componentNames.contains(packageName) 19909 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 19910 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 19911 new int[] {UserHandle.getUserId(packageUid)}); 19912 } 19913 19914 @Override 19915 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 19916 if (!sUserManager.exists(userId)) return; 19917 final int uid = Binder.getCallingUid(); 19918 final int permission = mContext.checkCallingOrSelfPermission( 19919 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19920 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19921 enforceCrossUserPermission(uid, userId, 19922 true /* requireFullPermission */, true /* checkShell */, "stop package"); 19923 // writer 19924 synchronized (mPackages) { 19925 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 19926 allowedByPermission, uid, userId)) { 19927 scheduleWritePackageRestrictionsLocked(userId); 19928 } 19929 } 19930 } 19931 19932 @Override 19933 public String getInstallerPackageName(String packageName) { 19934 // reader 19935 synchronized (mPackages) { 19936 return mSettings.getInstallerPackageNameLPr(packageName); 19937 } 19938 } 19939 19940 public boolean isOrphaned(String packageName) { 19941 // reader 19942 synchronized (mPackages) { 19943 return mSettings.isOrphaned(packageName); 19944 } 19945 } 19946 19947 @Override 19948 public int getApplicationEnabledSetting(String packageName, int userId) { 19949 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19950 int uid = Binder.getCallingUid(); 19951 enforceCrossUserPermission(uid, userId, 19952 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 19953 // reader 19954 synchronized (mPackages) { 19955 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 19956 } 19957 } 19958 19959 @Override 19960 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 19961 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 19962 int uid = Binder.getCallingUid(); 19963 enforceCrossUserPermission(uid, userId, 19964 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 19965 // reader 19966 synchronized (mPackages) { 19967 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 19968 } 19969 } 19970 19971 @Override 19972 public void enterSafeMode() { 19973 enforceSystemOrRoot("Only the system can request entering safe mode"); 19974 19975 if (!mSystemReady) { 19976 mSafeMode = true; 19977 } 19978 } 19979 19980 @Override 19981 public void systemReady() { 19982 mSystemReady = true; 19983 19984 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 19985 // disabled after already being started. 19986 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 19987 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 19988 19989 // Read the compatibilty setting when the system is ready. 19990 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 19991 mContext.getContentResolver(), 19992 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 19993 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 19994 if (DEBUG_SETTINGS) { 19995 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 19996 } 19997 19998 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 19999 20000 synchronized (mPackages) { 20001 // Verify that all of the preferred activity components actually 20002 // exist. It is possible for applications to be updated and at 20003 // that point remove a previously declared activity component that 20004 // had been set as a preferred activity. We try to clean this up 20005 // the next time we encounter that preferred activity, but it is 20006 // possible for the user flow to never be able to return to that 20007 // situation so here we do a sanity check to make sure we haven't 20008 // left any junk around. 20009 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20010 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20011 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20012 removed.clear(); 20013 for (PreferredActivity pa : pir.filterSet()) { 20014 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20015 removed.add(pa); 20016 } 20017 } 20018 if (removed.size() > 0) { 20019 for (int r=0; r<removed.size(); r++) { 20020 PreferredActivity pa = removed.get(r); 20021 Slog.w(TAG, "Removing dangling preferred activity: " 20022 + pa.mPref.mComponent); 20023 pir.removeFilter(pa); 20024 } 20025 mSettings.writePackageRestrictionsLPr( 20026 mSettings.mPreferredActivities.keyAt(i)); 20027 } 20028 } 20029 20030 for (int userId : UserManagerService.getInstance().getUserIds()) { 20031 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20032 grantPermissionsUserIds = ArrayUtils.appendInt( 20033 grantPermissionsUserIds, userId); 20034 } 20035 } 20036 } 20037 sUserManager.systemReady(); 20038 20039 // If we upgraded grant all default permissions before kicking off. 20040 for (int userId : grantPermissionsUserIds) { 20041 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20042 } 20043 20044 // If we did not grant default permissions, we preload from this the 20045 // default permission exceptions lazily to ensure we don't hit the 20046 // disk on a new user creation. 20047 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20048 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20049 } 20050 20051 // Kick off any messages waiting for system ready 20052 if (mPostSystemReadyMessages != null) { 20053 for (Message msg : mPostSystemReadyMessages) { 20054 msg.sendToTarget(); 20055 } 20056 mPostSystemReadyMessages = null; 20057 } 20058 20059 // Watch for external volumes that come and go over time 20060 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20061 storage.registerListener(mStorageListener); 20062 20063 mInstallerService.systemReady(); 20064 mPackageDexOptimizer.systemReady(); 20065 20066 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20067 StorageManagerInternal.class); 20068 StorageManagerInternal.addExternalStoragePolicy( 20069 new StorageManagerInternal.ExternalStorageMountPolicy() { 20070 @Override 20071 public int getMountMode(int uid, String packageName) { 20072 if (Process.isIsolated(uid)) { 20073 return Zygote.MOUNT_EXTERNAL_NONE; 20074 } 20075 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20076 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20077 } 20078 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20079 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20080 } 20081 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20082 return Zygote.MOUNT_EXTERNAL_READ; 20083 } 20084 return Zygote.MOUNT_EXTERNAL_WRITE; 20085 } 20086 20087 @Override 20088 public boolean hasExternalStorage(int uid, String packageName) { 20089 return true; 20090 } 20091 }); 20092 20093 // Now that we're mostly running, clean up stale users and apps 20094 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20095 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20096 20097 if (mPrivappPermissionsViolations != null) { 20098 Slog.wtf(TAG,"Signature|privileged permissions not in " 20099 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20100 mPrivappPermissionsViolations = null; 20101 } 20102 } 20103 20104 public void waitForAppDataPrepared() { 20105 if (mPrepareAppDataFuture == null) { 20106 return; 20107 } 20108 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20109 mPrepareAppDataFuture = null; 20110 } 20111 20112 @Override 20113 public boolean isSafeMode() { 20114 return mSafeMode; 20115 } 20116 20117 @Override 20118 public boolean hasSystemUidErrors() { 20119 return mHasSystemUidErrors; 20120 } 20121 20122 static String arrayToString(int[] array) { 20123 StringBuffer buf = new StringBuffer(128); 20124 buf.append('['); 20125 if (array != null) { 20126 for (int i=0; i<array.length; i++) { 20127 if (i > 0) buf.append(", "); 20128 buf.append(array[i]); 20129 } 20130 } 20131 buf.append(']'); 20132 return buf.toString(); 20133 } 20134 20135 static class DumpState { 20136 public static final int DUMP_LIBS = 1 << 0; 20137 public static final int DUMP_FEATURES = 1 << 1; 20138 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20139 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20140 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20141 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20142 public static final int DUMP_PERMISSIONS = 1 << 6; 20143 public static final int DUMP_PACKAGES = 1 << 7; 20144 public static final int DUMP_SHARED_USERS = 1 << 8; 20145 public static final int DUMP_MESSAGES = 1 << 9; 20146 public static final int DUMP_PROVIDERS = 1 << 10; 20147 public static final int DUMP_VERIFIERS = 1 << 11; 20148 public static final int DUMP_PREFERRED = 1 << 12; 20149 public static final int DUMP_PREFERRED_XML = 1 << 13; 20150 public static final int DUMP_KEYSETS = 1 << 14; 20151 public static final int DUMP_VERSION = 1 << 15; 20152 public static final int DUMP_INSTALLS = 1 << 16; 20153 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20154 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20155 public static final int DUMP_FROZEN = 1 << 19; 20156 public static final int DUMP_DEXOPT = 1 << 20; 20157 public static final int DUMP_COMPILER_STATS = 1 << 21; 20158 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20159 20160 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20161 20162 private int mTypes; 20163 20164 private int mOptions; 20165 20166 private boolean mTitlePrinted; 20167 20168 private SharedUserSetting mSharedUser; 20169 20170 public boolean isDumping(int type) { 20171 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20172 return true; 20173 } 20174 20175 return (mTypes & type) != 0; 20176 } 20177 20178 public void setDump(int type) { 20179 mTypes |= type; 20180 } 20181 20182 public boolean isOptionEnabled(int option) { 20183 return (mOptions & option) != 0; 20184 } 20185 20186 public void setOptionEnabled(int option) { 20187 mOptions |= option; 20188 } 20189 20190 public boolean onTitlePrinted() { 20191 final boolean printed = mTitlePrinted; 20192 mTitlePrinted = true; 20193 return printed; 20194 } 20195 20196 public boolean getTitlePrinted() { 20197 return mTitlePrinted; 20198 } 20199 20200 public void setTitlePrinted(boolean enabled) { 20201 mTitlePrinted = enabled; 20202 } 20203 20204 public SharedUserSetting getSharedUser() { 20205 return mSharedUser; 20206 } 20207 20208 public void setSharedUser(SharedUserSetting user) { 20209 mSharedUser = user; 20210 } 20211 } 20212 20213 @Override 20214 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20215 FileDescriptor err, String[] args, ShellCallback callback, 20216 ResultReceiver resultReceiver) { 20217 (new PackageManagerShellCommand(this)).exec( 20218 this, in, out, err, args, callback, resultReceiver); 20219 } 20220 20221 @Override 20222 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20223 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 20224 != PackageManager.PERMISSION_GRANTED) { 20225 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 20226 + Binder.getCallingPid() 20227 + ", uid=" + Binder.getCallingUid() 20228 + " without permission " 20229 + android.Manifest.permission.DUMP); 20230 return; 20231 } 20232 20233 DumpState dumpState = new DumpState(); 20234 boolean fullPreferred = false; 20235 boolean checkin = false; 20236 20237 String packageName = null; 20238 ArraySet<String> permissionNames = null; 20239 20240 int opti = 0; 20241 while (opti < args.length) { 20242 String opt = args[opti]; 20243 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20244 break; 20245 } 20246 opti++; 20247 20248 if ("-a".equals(opt)) { 20249 // Right now we only know how to print all. 20250 } else if ("-h".equals(opt)) { 20251 pw.println("Package manager dump options:"); 20252 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20253 pw.println(" --checkin: dump for a checkin"); 20254 pw.println(" -f: print details of intent filters"); 20255 pw.println(" -h: print this help"); 20256 pw.println(" cmd may be one of:"); 20257 pw.println(" l[ibraries]: list known shared libraries"); 20258 pw.println(" f[eatures]: list device features"); 20259 pw.println(" k[eysets]: print known keysets"); 20260 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20261 pw.println(" perm[issions]: dump permissions"); 20262 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20263 pw.println(" pref[erred]: print preferred package settings"); 20264 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20265 pw.println(" prov[iders]: dump content providers"); 20266 pw.println(" p[ackages]: dump installed packages"); 20267 pw.println(" s[hared-users]: dump shared user IDs"); 20268 pw.println(" m[essages]: print collected runtime messages"); 20269 pw.println(" v[erifiers]: print package verifier info"); 20270 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20271 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20272 pw.println(" version: print database version info"); 20273 pw.println(" write: write current settings now"); 20274 pw.println(" installs: details about install sessions"); 20275 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20276 pw.println(" dexopt: dump dexopt state"); 20277 pw.println(" compiler-stats: dump compiler statistics"); 20278 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20279 pw.println(" <package.name>: info about given package"); 20280 return; 20281 } else if ("--checkin".equals(opt)) { 20282 checkin = true; 20283 } else if ("-f".equals(opt)) { 20284 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20285 } else if ("--proto".equals(opt)) { 20286 dumpProto(fd); 20287 return; 20288 } else { 20289 pw.println("Unknown argument: " + opt + "; use -h for help"); 20290 } 20291 } 20292 20293 // Is the caller requesting to dump a particular piece of data? 20294 if (opti < args.length) { 20295 String cmd = args[opti]; 20296 opti++; 20297 // Is this a package name? 20298 if ("android".equals(cmd) || cmd.contains(".")) { 20299 packageName = cmd; 20300 // When dumping a single package, we always dump all of its 20301 // filter information since the amount of data will be reasonable. 20302 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20303 } else if ("check-permission".equals(cmd)) { 20304 if (opti >= args.length) { 20305 pw.println("Error: check-permission missing permission argument"); 20306 return; 20307 } 20308 String perm = args[opti]; 20309 opti++; 20310 if (opti >= args.length) { 20311 pw.println("Error: check-permission missing package argument"); 20312 return; 20313 } 20314 20315 String pkg = args[opti]; 20316 opti++; 20317 int user = UserHandle.getUserId(Binder.getCallingUid()); 20318 if (opti < args.length) { 20319 try { 20320 user = Integer.parseInt(args[opti]); 20321 } catch (NumberFormatException e) { 20322 pw.println("Error: check-permission user argument is not a number: " 20323 + args[opti]); 20324 return; 20325 } 20326 } 20327 20328 // Normalize package name to handle renamed packages and static libs 20329 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20330 20331 pw.println(checkPermission(perm, pkg, user)); 20332 return; 20333 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20334 dumpState.setDump(DumpState.DUMP_LIBS); 20335 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20336 dumpState.setDump(DumpState.DUMP_FEATURES); 20337 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20338 if (opti >= args.length) { 20339 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20340 | DumpState.DUMP_SERVICE_RESOLVERS 20341 | DumpState.DUMP_RECEIVER_RESOLVERS 20342 | DumpState.DUMP_CONTENT_RESOLVERS); 20343 } else { 20344 while (opti < args.length) { 20345 String name = args[opti]; 20346 if ("a".equals(name) || "activity".equals(name)) { 20347 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20348 } else if ("s".equals(name) || "service".equals(name)) { 20349 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20350 } else if ("r".equals(name) || "receiver".equals(name)) { 20351 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20352 } else if ("c".equals(name) || "content".equals(name)) { 20353 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20354 } else { 20355 pw.println("Error: unknown resolver table type: " + name); 20356 return; 20357 } 20358 opti++; 20359 } 20360 } 20361 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20362 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20363 } else if ("permission".equals(cmd)) { 20364 if (opti >= args.length) { 20365 pw.println("Error: permission requires permission name"); 20366 return; 20367 } 20368 permissionNames = new ArraySet<>(); 20369 while (opti < args.length) { 20370 permissionNames.add(args[opti]); 20371 opti++; 20372 } 20373 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20374 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20375 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20376 dumpState.setDump(DumpState.DUMP_PREFERRED); 20377 } else if ("preferred-xml".equals(cmd)) { 20378 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20379 if (opti < args.length && "--full".equals(args[opti])) { 20380 fullPreferred = true; 20381 opti++; 20382 } 20383 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20384 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20385 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20386 dumpState.setDump(DumpState.DUMP_PACKAGES); 20387 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20388 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20389 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20390 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20391 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20392 dumpState.setDump(DumpState.DUMP_MESSAGES); 20393 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20394 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20395 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20396 || "intent-filter-verifiers".equals(cmd)) { 20397 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20398 } else if ("version".equals(cmd)) { 20399 dumpState.setDump(DumpState.DUMP_VERSION); 20400 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20401 dumpState.setDump(DumpState.DUMP_KEYSETS); 20402 } else if ("installs".equals(cmd)) { 20403 dumpState.setDump(DumpState.DUMP_INSTALLS); 20404 } else if ("frozen".equals(cmd)) { 20405 dumpState.setDump(DumpState.DUMP_FROZEN); 20406 } else if ("dexopt".equals(cmd)) { 20407 dumpState.setDump(DumpState.DUMP_DEXOPT); 20408 } else if ("compiler-stats".equals(cmd)) { 20409 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20410 } else if ("enabled-overlays".equals(cmd)) { 20411 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20412 } else if ("write".equals(cmd)) { 20413 synchronized (mPackages) { 20414 mSettings.writeLPr(); 20415 pw.println("Settings written."); 20416 return; 20417 } 20418 } 20419 } 20420 20421 if (checkin) { 20422 pw.println("vers,1"); 20423 } 20424 20425 // reader 20426 synchronized (mPackages) { 20427 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20428 if (!checkin) { 20429 if (dumpState.onTitlePrinted()) 20430 pw.println(); 20431 pw.println("Database versions:"); 20432 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20433 } 20434 } 20435 20436 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20437 if (!checkin) { 20438 if (dumpState.onTitlePrinted()) 20439 pw.println(); 20440 pw.println("Verifiers:"); 20441 pw.print(" Required: "); 20442 pw.print(mRequiredVerifierPackage); 20443 pw.print(" (uid="); 20444 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20445 UserHandle.USER_SYSTEM)); 20446 pw.println(")"); 20447 } else if (mRequiredVerifierPackage != null) { 20448 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20449 pw.print(","); 20450 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20451 UserHandle.USER_SYSTEM)); 20452 } 20453 } 20454 20455 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20456 packageName == null) { 20457 if (mIntentFilterVerifierComponent != null) { 20458 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20459 if (!checkin) { 20460 if (dumpState.onTitlePrinted()) 20461 pw.println(); 20462 pw.println("Intent Filter Verifier:"); 20463 pw.print(" Using: "); 20464 pw.print(verifierPackageName); 20465 pw.print(" (uid="); 20466 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20467 UserHandle.USER_SYSTEM)); 20468 pw.println(")"); 20469 } else if (verifierPackageName != null) { 20470 pw.print("ifv,"); pw.print(verifierPackageName); 20471 pw.print(","); 20472 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20473 UserHandle.USER_SYSTEM)); 20474 } 20475 } else { 20476 pw.println(); 20477 pw.println("No Intent Filter Verifier available!"); 20478 } 20479 } 20480 20481 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20482 boolean printedHeader = false; 20483 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20484 while (it.hasNext()) { 20485 String libName = it.next(); 20486 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20487 if (versionedLib == null) { 20488 continue; 20489 } 20490 final int versionCount = versionedLib.size(); 20491 for (int i = 0; i < versionCount; i++) { 20492 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20493 if (!checkin) { 20494 if (!printedHeader) { 20495 if (dumpState.onTitlePrinted()) 20496 pw.println(); 20497 pw.println("Libraries:"); 20498 printedHeader = true; 20499 } 20500 pw.print(" "); 20501 } else { 20502 pw.print("lib,"); 20503 } 20504 pw.print(libEntry.info.getName()); 20505 if (libEntry.info.isStatic()) { 20506 pw.print(" version=" + libEntry.info.getVersion()); 20507 } 20508 if (!checkin) { 20509 pw.print(" -> "); 20510 } 20511 if (libEntry.path != null) { 20512 pw.print(" (jar) "); 20513 pw.print(libEntry.path); 20514 } else { 20515 pw.print(" (apk) "); 20516 pw.print(libEntry.apk); 20517 } 20518 pw.println(); 20519 } 20520 } 20521 } 20522 20523 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20524 if (dumpState.onTitlePrinted()) 20525 pw.println(); 20526 if (!checkin) { 20527 pw.println("Features:"); 20528 } 20529 20530 synchronized (mAvailableFeatures) { 20531 for (FeatureInfo feat : mAvailableFeatures.values()) { 20532 if (checkin) { 20533 pw.print("feat,"); 20534 pw.print(feat.name); 20535 pw.print(","); 20536 pw.println(feat.version); 20537 } else { 20538 pw.print(" "); 20539 pw.print(feat.name); 20540 if (feat.version > 0) { 20541 pw.print(" version="); 20542 pw.print(feat.version); 20543 } 20544 pw.println(); 20545 } 20546 } 20547 } 20548 } 20549 20550 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20551 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20552 : "Activity Resolver Table:", " ", packageName, 20553 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20554 dumpState.setTitlePrinted(true); 20555 } 20556 } 20557 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20558 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20559 : "Receiver Resolver Table:", " ", packageName, 20560 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20561 dumpState.setTitlePrinted(true); 20562 } 20563 } 20564 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20565 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20566 : "Service Resolver Table:", " ", packageName, 20567 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20568 dumpState.setTitlePrinted(true); 20569 } 20570 } 20571 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20572 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20573 : "Provider Resolver Table:", " ", packageName, 20574 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20575 dumpState.setTitlePrinted(true); 20576 } 20577 } 20578 20579 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20580 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20581 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20582 int user = mSettings.mPreferredActivities.keyAt(i); 20583 if (pir.dump(pw, 20584 dumpState.getTitlePrinted() 20585 ? "\nPreferred Activities User " + user + ":" 20586 : "Preferred Activities User " + user + ":", " ", 20587 packageName, true, false)) { 20588 dumpState.setTitlePrinted(true); 20589 } 20590 } 20591 } 20592 20593 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20594 pw.flush(); 20595 FileOutputStream fout = new FileOutputStream(fd); 20596 BufferedOutputStream str = new BufferedOutputStream(fout); 20597 XmlSerializer serializer = new FastXmlSerializer(); 20598 try { 20599 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20600 serializer.startDocument(null, true); 20601 serializer.setFeature( 20602 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20603 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20604 serializer.endDocument(); 20605 serializer.flush(); 20606 } catch (IllegalArgumentException e) { 20607 pw.println("Failed writing: " + e); 20608 } catch (IllegalStateException e) { 20609 pw.println("Failed writing: " + e); 20610 } catch (IOException e) { 20611 pw.println("Failed writing: " + e); 20612 } 20613 } 20614 20615 if (!checkin 20616 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20617 && packageName == null) { 20618 pw.println(); 20619 int count = mSettings.mPackages.size(); 20620 if (count == 0) { 20621 pw.println("No applications!"); 20622 pw.println(); 20623 } else { 20624 final String prefix = " "; 20625 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20626 if (allPackageSettings.size() == 0) { 20627 pw.println("No domain preferred apps!"); 20628 pw.println(); 20629 } else { 20630 pw.println("App verification status:"); 20631 pw.println(); 20632 count = 0; 20633 for (PackageSetting ps : allPackageSettings) { 20634 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20635 if (ivi == null || ivi.getPackageName() == null) continue; 20636 pw.println(prefix + "Package: " + ivi.getPackageName()); 20637 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20638 pw.println(prefix + "Status: " + ivi.getStatusString()); 20639 pw.println(); 20640 count++; 20641 } 20642 if (count == 0) { 20643 pw.println(prefix + "No app verification established."); 20644 pw.println(); 20645 } 20646 for (int userId : sUserManager.getUserIds()) { 20647 pw.println("App linkages for user " + userId + ":"); 20648 pw.println(); 20649 count = 0; 20650 for (PackageSetting ps : allPackageSettings) { 20651 final long status = ps.getDomainVerificationStatusForUser(userId); 20652 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20653 && !DEBUG_DOMAIN_VERIFICATION) { 20654 continue; 20655 } 20656 pw.println(prefix + "Package: " + ps.name); 20657 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20658 String statusStr = IntentFilterVerificationInfo. 20659 getStatusStringFromValue(status); 20660 pw.println(prefix + "Status: " + statusStr); 20661 pw.println(); 20662 count++; 20663 } 20664 if (count == 0) { 20665 pw.println(prefix + "No configured app linkages."); 20666 pw.println(); 20667 } 20668 } 20669 } 20670 } 20671 } 20672 20673 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20674 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20675 if (packageName == null && permissionNames == null) { 20676 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20677 if (iperm == 0) { 20678 if (dumpState.onTitlePrinted()) 20679 pw.println(); 20680 pw.println("AppOp Permissions:"); 20681 } 20682 pw.print(" AppOp Permission "); 20683 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20684 pw.println(":"); 20685 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20686 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20687 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20688 } 20689 } 20690 } 20691 } 20692 20693 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20694 boolean printedSomething = false; 20695 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20696 if (packageName != null && !packageName.equals(p.info.packageName)) { 20697 continue; 20698 } 20699 if (!printedSomething) { 20700 if (dumpState.onTitlePrinted()) 20701 pw.println(); 20702 pw.println("Registered ContentProviders:"); 20703 printedSomething = true; 20704 } 20705 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20706 pw.print(" "); pw.println(p.toString()); 20707 } 20708 printedSomething = false; 20709 for (Map.Entry<String, PackageParser.Provider> entry : 20710 mProvidersByAuthority.entrySet()) { 20711 PackageParser.Provider p = entry.getValue(); 20712 if (packageName != null && !packageName.equals(p.info.packageName)) { 20713 continue; 20714 } 20715 if (!printedSomething) { 20716 if (dumpState.onTitlePrinted()) 20717 pw.println(); 20718 pw.println("ContentProvider Authorities:"); 20719 printedSomething = true; 20720 } 20721 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20722 pw.print(" "); pw.println(p.toString()); 20723 if (p.info != null && p.info.applicationInfo != null) { 20724 final String appInfo = p.info.applicationInfo.toString(); 20725 pw.print(" applicationInfo="); pw.println(appInfo); 20726 } 20727 } 20728 } 20729 20730 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20731 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20732 } 20733 20734 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20735 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20736 } 20737 20738 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20739 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20740 } 20741 20742 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20743 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20744 } 20745 20746 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 20747 // XXX should handle packageName != null by dumping only install data that 20748 // the given package is involved with. 20749 if (dumpState.onTitlePrinted()) pw.println(); 20750 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 20751 } 20752 20753 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20754 // XXX should handle packageName != null by dumping only install data that 20755 // the given package is involved with. 20756 if (dumpState.onTitlePrinted()) pw.println(); 20757 20758 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20759 ipw.println(); 20760 ipw.println("Frozen packages:"); 20761 ipw.increaseIndent(); 20762 if (mFrozenPackages.size() == 0) { 20763 ipw.println("(none)"); 20764 } else { 20765 for (int i = 0; i < mFrozenPackages.size(); i++) { 20766 ipw.println(mFrozenPackages.valueAt(i)); 20767 } 20768 } 20769 ipw.decreaseIndent(); 20770 } 20771 20772 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20773 if (dumpState.onTitlePrinted()) pw.println(); 20774 dumpDexoptStateLPr(pw, packageName); 20775 } 20776 20777 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20778 if (dumpState.onTitlePrinted()) pw.println(); 20779 dumpCompilerStatsLPr(pw, packageName); 20780 } 20781 20782 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20783 if (dumpState.onTitlePrinted()) pw.println(); 20784 dumpEnabledOverlaysLPr(pw); 20785 } 20786 20787 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20788 if (dumpState.onTitlePrinted()) pw.println(); 20789 mSettings.dumpReadMessagesLPr(pw, dumpState); 20790 20791 pw.println(); 20792 pw.println("Package warning messages:"); 20793 BufferedReader in = null; 20794 String line = null; 20795 try { 20796 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20797 while ((line = in.readLine()) != null) { 20798 if (line.contains("ignored: updated version")) continue; 20799 pw.println(line); 20800 } 20801 } catch (IOException ignored) { 20802 } finally { 20803 IoUtils.closeQuietly(in); 20804 } 20805 } 20806 20807 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20808 BufferedReader in = null; 20809 String line = null; 20810 try { 20811 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20812 while ((line = in.readLine()) != null) { 20813 if (line.contains("ignored: updated version")) continue; 20814 pw.print("msg,"); 20815 pw.println(line); 20816 } 20817 } catch (IOException ignored) { 20818 } finally { 20819 IoUtils.closeQuietly(in); 20820 } 20821 } 20822 } 20823 } 20824 20825 private void dumpProto(FileDescriptor fd) { 20826 final ProtoOutputStream proto = new ProtoOutputStream(fd); 20827 20828 synchronized (mPackages) { 20829 final long requiredVerifierPackageToken = 20830 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 20831 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 20832 proto.write( 20833 PackageServiceDumpProto.PackageShortProto.UID, 20834 getPackageUid( 20835 mRequiredVerifierPackage, 20836 MATCH_DEBUG_TRIAGED_MISSING, 20837 UserHandle.USER_SYSTEM)); 20838 proto.end(requiredVerifierPackageToken); 20839 20840 if (mIntentFilterVerifierComponent != null) { 20841 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20842 final long verifierPackageToken = 20843 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 20844 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 20845 proto.write( 20846 PackageServiceDumpProto.PackageShortProto.UID, 20847 getPackageUid( 20848 verifierPackageName, 20849 MATCH_DEBUG_TRIAGED_MISSING, 20850 UserHandle.USER_SYSTEM)); 20851 proto.end(verifierPackageToken); 20852 } 20853 20854 dumpSharedLibrariesProto(proto); 20855 dumpFeaturesProto(proto); 20856 mSettings.dumpPackagesProto(proto); 20857 mSettings.dumpSharedUsersProto(proto); 20858 dumpMessagesProto(proto); 20859 } 20860 proto.flush(); 20861 } 20862 20863 private void dumpMessagesProto(ProtoOutputStream proto) { 20864 BufferedReader in = null; 20865 String line = null; 20866 try { 20867 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20868 while ((line = in.readLine()) != null) { 20869 if (line.contains("ignored: updated version")) continue; 20870 proto.write(PackageServiceDumpProto.MESSAGES, line); 20871 } 20872 } catch (IOException ignored) { 20873 } finally { 20874 IoUtils.closeQuietly(in); 20875 } 20876 } 20877 20878 private void dumpFeaturesProto(ProtoOutputStream proto) { 20879 synchronized (mAvailableFeatures) { 20880 final int count = mAvailableFeatures.size(); 20881 for (int i = 0; i < count; i++) { 20882 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 20883 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 20884 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 20885 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 20886 proto.end(featureToken); 20887 } 20888 } 20889 } 20890 20891 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 20892 final int count = mSharedLibraries.size(); 20893 for (int i = 0; i < count; i++) { 20894 final String libName = mSharedLibraries.keyAt(i); 20895 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20896 if (versionedLib == null) { 20897 continue; 20898 } 20899 final int versionCount = versionedLib.size(); 20900 for (int j = 0; j < versionCount; j++) { 20901 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 20902 final long sharedLibraryToken = 20903 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 20904 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 20905 final boolean isJar = (libEntry.path != null); 20906 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 20907 if (isJar) { 20908 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 20909 } else { 20910 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 20911 } 20912 proto.end(sharedLibraryToken); 20913 } 20914 } 20915 } 20916 20917 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 20918 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20919 ipw.println(); 20920 ipw.println("Dexopt state:"); 20921 ipw.increaseIndent(); 20922 Collection<PackageParser.Package> packages = null; 20923 if (packageName != null) { 20924 PackageParser.Package targetPackage = mPackages.get(packageName); 20925 if (targetPackage != null) { 20926 packages = Collections.singletonList(targetPackage); 20927 } else { 20928 ipw.println("Unable to find package: " + packageName); 20929 return; 20930 } 20931 } else { 20932 packages = mPackages.values(); 20933 } 20934 20935 for (PackageParser.Package pkg : packages) { 20936 ipw.println("[" + pkg.packageName + "]"); 20937 ipw.increaseIndent(); 20938 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 20939 ipw.decreaseIndent(); 20940 } 20941 } 20942 20943 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 20944 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20945 ipw.println(); 20946 ipw.println("Compiler stats:"); 20947 ipw.increaseIndent(); 20948 Collection<PackageParser.Package> packages = null; 20949 if (packageName != null) { 20950 PackageParser.Package targetPackage = mPackages.get(packageName); 20951 if (targetPackage != null) { 20952 packages = Collections.singletonList(targetPackage); 20953 } else { 20954 ipw.println("Unable to find package: " + packageName); 20955 return; 20956 } 20957 } else { 20958 packages = mPackages.values(); 20959 } 20960 20961 for (PackageParser.Package pkg : packages) { 20962 ipw.println("[" + pkg.packageName + "]"); 20963 ipw.increaseIndent(); 20964 20965 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 20966 if (stats == null) { 20967 ipw.println("(No recorded stats)"); 20968 } else { 20969 stats.dump(ipw); 20970 } 20971 ipw.decreaseIndent(); 20972 } 20973 } 20974 20975 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 20976 pw.println("Enabled overlay paths:"); 20977 final int N = mEnabledOverlayPaths.size(); 20978 for (int i = 0; i < N; i++) { 20979 final int userId = mEnabledOverlayPaths.keyAt(i); 20980 pw.println(String.format(" User %d:", userId)); 20981 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 20982 mEnabledOverlayPaths.valueAt(i); 20983 final int M = userSpecificOverlays.size(); 20984 for (int j = 0; j < M; j++) { 20985 final String targetPackageName = userSpecificOverlays.keyAt(j); 20986 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 20987 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 20988 } 20989 } 20990 } 20991 20992 private String dumpDomainString(String packageName) { 20993 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 20994 .getList(); 20995 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 20996 20997 ArraySet<String> result = new ArraySet<>(); 20998 if (iviList.size() > 0) { 20999 for (IntentFilterVerificationInfo ivi : iviList) { 21000 for (String host : ivi.getDomains()) { 21001 result.add(host); 21002 } 21003 } 21004 } 21005 if (filters != null && filters.size() > 0) { 21006 for (IntentFilter filter : filters) { 21007 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21008 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21009 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21010 result.addAll(filter.getHostsList()); 21011 } 21012 } 21013 } 21014 21015 StringBuilder sb = new StringBuilder(result.size() * 16); 21016 for (String domain : result) { 21017 if (sb.length() > 0) sb.append(" "); 21018 sb.append(domain); 21019 } 21020 return sb.toString(); 21021 } 21022 21023 // ------- apps on sdcard specific code ------- 21024 static final boolean DEBUG_SD_INSTALL = false; 21025 21026 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21027 21028 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21029 21030 private boolean mMediaMounted = false; 21031 21032 static String getEncryptKey() { 21033 try { 21034 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21035 SD_ENCRYPTION_KEYSTORE_NAME); 21036 if (sdEncKey == null) { 21037 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21038 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21039 if (sdEncKey == null) { 21040 Slog.e(TAG, "Failed to create encryption keys"); 21041 return null; 21042 } 21043 } 21044 return sdEncKey; 21045 } catch (NoSuchAlgorithmException nsae) { 21046 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21047 return null; 21048 } catch (IOException ioe) { 21049 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21050 return null; 21051 } 21052 } 21053 21054 /* 21055 * Update media status on PackageManager. 21056 */ 21057 @Override 21058 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21059 int callingUid = Binder.getCallingUid(); 21060 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21061 throw new SecurityException("Media status can only be updated by the system"); 21062 } 21063 // reader; this apparently protects mMediaMounted, but should probably 21064 // be a different lock in that case. 21065 synchronized (mPackages) { 21066 Log.i(TAG, "Updating external media status from " 21067 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21068 + (mediaStatus ? "mounted" : "unmounted")); 21069 if (DEBUG_SD_INSTALL) 21070 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21071 + ", mMediaMounted=" + mMediaMounted); 21072 if (mediaStatus == mMediaMounted) { 21073 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21074 : 0, -1); 21075 mHandler.sendMessage(msg); 21076 return; 21077 } 21078 mMediaMounted = mediaStatus; 21079 } 21080 // Queue up an async operation since the package installation may take a 21081 // little while. 21082 mHandler.post(new Runnable() { 21083 public void run() { 21084 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21085 } 21086 }); 21087 } 21088 21089 /** 21090 * Called by StorageManagerService when the initial ASECs to scan are available. 21091 * Should block until all the ASEC containers are finished being scanned. 21092 */ 21093 public void scanAvailableAsecs() { 21094 updateExternalMediaStatusInner(true, false, false); 21095 } 21096 21097 /* 21098 * Collect information of applications on external media, map them against 21099 * existing containers and update information based on current mount status. 21100 * Please note that we always have to report status if reportStatus has been 21101 * set to true especially when unloading packages. 21102 */ 21103 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21104 boolean externalStorage) { 21105 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21106 int[] uidArr = EmptyArray.INT; 21107 21108 final String[] list = PackageHelper.getSecureContainerList(); 21109 if (ArrayUtils.isEmpty(list)) { 21110 Log.i(TAG, "No secure containers found"); 21111 } else { 21112 // Process list of secure containers and categorize them 21113 // as active or stale based on their package internal state. 21114 21115 // reader 21116 synchronized (mPackages) { 21117 for (String cid : list) { 21118 // Leave stages untouched for now; installer service owns them 21119 if (PackageInstallerService.isStageName(cid)) continue; 21120 21121 if (DEBUG_SD_INSTALL) 21122 Log.i(TAG, "Processing container " + cid); 21123 String pkgName = getAsecPackageName(cid); 21124 if (pkgName == null) { 21125 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21126 continue; 21127 } 21128 if (DEBUG_SD_INSTALL) 21129 Log.i(TAG, "Looking for pkg : " + pkgName); 21130 21131 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21132 if (ps == null) { 21133 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21134 continue; 21135 } 21136 21137 /* 21138 * Skip packages that are not external if we're unmounting 21139 * external storage. 21140 */ 21141 if (externalStorage && !isMounted && !isExternal(ps)) { 21142 continue; 21143 } 21144 21145 final AsecInstallArgs args = new AsecInstallArgs(cid, 21146 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21147 // The package status is changed only if the code path 21148 // matches between settings and the container id. 21149 if (ps.codePathString != null 21150 && ps.codePathString.startsWith(args.getCodePath())) { 21151 if (DEBUG_SD_INSTALL) { 21152 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21153 + " at code path: " + ps.codePathString); 21154 } 21155 21156 // We do have a valid package installed on sdcard 21157 processCids.put(args, ps.codePathString); 21158 final int uid = ps.appId; 21159 if (uid != -1) { 21160 uidArr = ArrayUtils.appendInt(uidArr, uid); 21161 } 21162 } else { 21163 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21164 + ps.codePathString); 21165 } 21166 } 21167 } 21168 21169 Arrays.sort(uidArr); 21170 } 21171 21172 // Process packages with valid entries. 21173 if (isMounted) { 21174 if (DEBUG_SD_INSTALL) 21175 Log.i(TAG, "Loading packages"); 21176 loadMediaPackages(processCids, uidArr, externalStorage); 21177 startCleaningPackages(); 21178 mInstallerService.onSecureContainersAvailable(); 21179 } else { 21180 if (DEBUG_SD_INSTALL) 21181 Log.i(TAG, "Unloading packages"); 21182 unloadMediaPackages(processCids, uidArr, reportStatus); 21183 } 21184 } 21185 21186 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21187 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21188 final int size = infos.size(); 21189 final String[] packageNames = new String[size]; 21190 final int[] packageUids = new int[size]; 21191 for (int i = 0; i < size; i++) { 21192 final ApplicationInfo info = infos.get(i); 21193 packageNames[i] = info.packageName; 21194 packageUids[i] = info.uid; 21195 } 21196 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21197 finishedReceiver); 21198 } 21199 21200 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21201 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21202 sendResourcesChangedBroadcast(mediaStatus, replacing, 21203 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21204 } 21205 21206 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21207 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21208 int size = pkgList.length; 21209 if (size > 0) { 21210 // Send broadcasts here 21211 Bundle extras = new Bundle(); 21212 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21213 if (uidArr != null) { 21214 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21215 } 21216 if (replacing) { 21217 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21218 } 21219 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21220 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21221 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21222 } 21223 } 21224 21225 /* 21226 * Look at potentially valid container ids from processCids If package 21227 * information doesn't match the one on record or package scanning fails, 21228 * the cid is added to list of removeCids. We currently don't delete stale 21229 * containers. 21230 */ 21231 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21232 boolean externalStorage) { 21233 ArrayList<String> pkgList = new ArrayList<String>(); 21234 Set<AsecInstallArgs> keys = processCids.keySet(); 21235 21236 for (AsecInstallArgs args : keys) { 21237 String codePath = processCids.get(args); 21238 if (DEBUG_SD_INSTALL) 21239 Log.i(TAG, "Loading container : " + args.cid); 21240 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21241 try { 21242 // Make sure there are no container errors first. 21243 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21244 Slog.e(TAG, "Failed to mount cid : " + args.cid 21245 + " when installing from sdcard"); 21246 continue; 21247 } 21248 // Check code path here. 21249 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21250 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21251 + " does not match one in settings " + codePath); 21252 continue; 21253 } 21254 // Parse package 21255 int parseFlags = mDefParseFlags; 21256 if (args.isExternalAsec()) { 21257 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21258 } 21259 if (args.isFwdLocked()) { 21260 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21261 } 21262 21263 synchronized (mInstallLock) { 21264 PackageParser.Package pkg = null; 21265 try { 21266 // Sadly we don't know the package name yet to freeze it 21267 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21268 SCAN_IGNORE_FROZEN, 0, null); 21269 } catch (PackageManagerException e) { 21270 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21271 } 21272 // Scan the package 21273 if (pkg != null) { 21274 /* 21275 * TODO why is the lock being held? doPostInstall is 21276 * called in other places without the lock. This needs 21277 * to be straightened out. 21278 */ 21279 // writer 21280 synchronized (mPackages) { 21281 retCode = PackageManager.INSTALL_SUCCEEDED; 21282 pkgList.add(pkg.packageName); 21283 // Post process args 21284 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21285 pkg.applicationInfo.uid); 21286 } 21287 } else { 21288 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21289 } 21290 } 21291 21292 } finally { 21293 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21294 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21295 } 21296 } 21297 } 21298 // writer 21299 synchronized (mPackages) { 21300 // If the platform SDK has changed since the last time we booted, 21301 // we need to re-grant app permission to catch any new ones that 21302 // appear. This is really a hack, and means that apps can in some 21303 // cases get permissions that the user didn't initially explicitly 21304 // allow... it would be nice to have some better way to handle 21305 // this situation. 21306 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21307 : mSettings.getInternalVersion(); 21308 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21309 : StorageManager.UUID_PRIVATE_INTERNAL; 21310 21311 int updateFlags = UPDATE_PERMISSIONS_ALL; 21312 if (ver.sdkVersion != mSdkVersion) { 21313 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21314 + mSdkVersion + "; regranting permissions for external"); 21315 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21316 } 21317 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21318 21319 // Yay, everything is now upgraded 21320 ver.forceCurrent(); 21321 21322 // can downgrade to reader 21323 // Persist settings 21324 mSettings.writeLPr(); 21325 } 21326 // Send a broadcast to let everyone know we are done processing 21327 if (pkgList.size() > 0) { 21328 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21329 } 21330 } 21331 21332 /* 21333 * Utility method to unload a list of specified containers 21334 */ 21335 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21336 // Just unmount all valid containers. 21337 for (AsecInstallArgs arg : cidArgs) { 21338 synchronized (mInstallLock) { 21339 arg.doPostDeleteLI(false); 21340 } 21341 } 21342 } 21343 21344 /* 21345 * Unload packages mounted on external media. This involves deleting package 21346 * data from internal structures, sending broadcasts about disabled packages, 21347 * gc'ing to free up references, unmounting all secure containers 21348 * corresponding to packages on external media, and posting a 21349 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21350 * that we always have to post this message if status has been requested no 21351 * matter what. 21352 */ 21353 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21354 final boolean reportStatus) { 21355 if (DEBUG_SD_INSTALL) 21356 Log.i(TAG, "unloading media packages"); 21357 ArrayList<String> pkgList = new ArrayList<String>(); 21358 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21359 final Set<AsecInstallArgs> keys = processCids.keySet(); 21360 for (AsecInstallArgs args : keys) { 21361 String pkgName = args.getPackageName(); 21362 if (DEBUG_SD_INSTALL) 21363 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21364 // Delete package internally 21365 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21366 synchronized (mInstallLock) { 21367 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21368 final boolean res; 21369 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21370 "unloadMediaPackages")) { 21371 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21372 null); 21373 } 21374 if (res) { 21375 pkgList.add(pkgName); 21376 } else { 21377 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21378 failedList.add(args); 21379 } 21380 } 21381 } 21382 21383 // reader 21384 synchronized (mPackages) { 21385 // We didn't update the settings after removing each package; 21386 // write them now for all packages. 21387 mSettings.writeLPr(); 21388 } 21389 21390 // We have to absolutely send UPDATED_MEDIA_STATUS only 21391 // after confirming that all the receivers processed the ordered 21392 // broadcast when packages get disabled, force a gc to clean things up. 21393 // and unload all the containers. 21394 if (pkgList.size() > 0) { 21395 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21396 new IIntentReceiver.Stub() { 21397 public void performReceive(Intent intent, int resultCode, String data, 21398 Bundle extras, boolean ordered, boolean sticky, 21399 int sendingUser) throws RemoteException { 21400 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21401 reportStatus ? 1 : 0, 1, keys); 21402 mHandler.sendMessage(msg); 21403 } 21404 }); 21405 } else { 21406 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21407 keys); 21408 mHandler.sendMessage(msg); 21409 } 21410 } 21411 21412 private void loadPrivatePackages(final VolumeInfo vol) { 21413 mHandler.post(new Runnable() { 21414 @Override 21415 public void run() { 21416 loadPrivatePackagesInner(vol); 21417 } 21418 }); 21419 } 21420 21421 private void loadPrivatePackagesInner(VolumeInfo vol) { 21422 final String volumeUuid = vol.fsUuid; 21423 if (TextUtils.isEmpty(volumeUuid)) { 21424 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21425 return; 21426 } 21427 21428 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21429 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21430 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21431 21432 final VersionInfo ver; 21433 final List<PackageSetting> packages; 21434 synchronized (mPackages) { 21435 ver = mSettings.findOrCreateVersion(volumeUuid); 21436 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21437 } 21438 21439 for (PackageSetting ps : packages) { 21440 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21441 synchronized (mInstallLock) { 21442 final PackageParser.Package pkg; 21443 try { 21444 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21445 loaded.add(pkg.applicationInfo); 21446 21447 } catch (PackageManagerException e) { 21448 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21449 } 21450 21451 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21452 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21453 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21454 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21455 } 21456 } 21457 } 21458 21459 // Reconcile app data for all started/unlocked users 21460 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21461 final UserManager um = mContext.getSystemService(UserManager.class); 21462 UserManagerInternal umInternal = getUserManagerInternal(); 21463 for (UserInfo user : um.getUsers()) { 21464 final int flags; 21465 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21466 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21467 } else if (umInternal.isUserRunning(user.id)) { 21468 flags = StorageManager.FLAG_STORAGE_DE; 21469 } else { 21470 continue; 21471 } 21472 21473 try { 21474 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21475 synchronized (mInstallLock) { 21476 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21477 } 21478 } catch (IllegalStateException e) { 21479 // Device was probably ejected, and we'll process that event momentarily 21480 Slog.w(TAG, "Failed to prepare storage: " + e); 21481 } 21482 } 21483 21484 synchronized (mPackages) { 21485 int updateFlags = UPDATE_PERMISSIONS_ALL; 21486 if (ver.sdkVersion != mSdkVersion) { 21487 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21488 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21489 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21490 } 21491 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21492 21493 // Yay, everything is now upgraded 21494 ver.forceCurrent(); 21495 21496 mSettings.writeLPr(); 21497 } 21498 21499 for (PackageFreezer freezer : freezers) { 21500 freezer.close(); 21501 } 21502 21503 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21504 sendResourcesChangedBroadcast(true, false, loaded, null); 21505 } 21506 21507 private void unloadPrivatePackages(final VolumeInfo vol) { 21508 mHandler.post(new Runnable() { 21509 @Override 21510 public void run() { 21511 unloadPrivatePackagesInner(vol); 21512 } 21513 }); 21514 } 21515 21516 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21517 final String volumeUuid = vol.fsUuid; 21518 if (TextUtils.isEmpty(volumeUuid)) { 21519 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21520 return; 21521 } 21522 21523 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21524 synchronized (mInstallLock) { 21525 synchronized (mPackages) { 21526 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21527 for (PackageSetting ps : packages) { 21528 if (ps.pkg == null) continue; 21529 21530 final ApplicationInfo info = ps.pkg.applicationInfo; 21531 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21532 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21533 21534 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21535 "unloadPrivatePackagesInner")) { 21536 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21537 false, null)) { 21538 unloaded.add(info); 21539 } else { 21540 Slog.w(TAG, "Failed to unload " + ps.codePath); 21541 } 21542 } 21543 21544 // Try very hard to release any references to this package 21545 // so we don't risk the system server being killed due to 21546 // open FDs 21547 AttributeCache.instance().removePackage(ps.name); 21548 } 21549 21550 mSettings.writeLPr(); 21551 } 21552 } 21553 21554 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21555 sendResourcesChangedBroadcast(false, false, unloaded, null); 21556 21557 // Try very hard to release any references to this path so we don't risk 21558 // the system server being killed due to open FDs 21559 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21560 21561 for (int i = 0; i < 3; i++) { 21562 System.gc(); 21563 System.runFinalization(); 21564 } 21565 } 21566 21567 private void assertPackageKnown(String volumeUuid, String packageName) 21568 throws PackageManagerException { 21569 synchronized (mPackages) { 21570 // Normalize package name to handle renamed packages 21571 packageName = normalizePackageNameLPr(packageName); 21572 21573 final PackageSetting ps = mSettings.mPackages.get(packageName); 21574 if (ps == null) { 21575 throw new PackageManagerException("Package " + packageName + " is unknown"); 21576 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21577 throw new PackageManagerException( 21578 "Package " + packageName + " found on unknown volume " + volumeUuid 21579 + "; expected volume " + ps.volumeUuid); 21580 } 21581 } 21582 } 21583 21584 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21585 throws PackageManagerException { 21586 synchronized (mPackages) { 21587 // Normalize package name to handle renamed packages 21588 packageName = normalizePackageNameLPr(packageName); 21589 21590 final PackageSetting ps = mSettings.mPackages.get(packageName); 21591 if (ps == null) { 21592 throw new PackageManagerException("Package " + packageName + " is unknown"); 21593 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21594 throw new PackageManagerException( 21595 "Package " + packageName + " found on unknown volume " + volumeUuid 21596 + "; expected volume " + ps.volumeUuid); 21597 } else if (!ps.getInstalled(userId)) { 21598 throw new PackageManagerException( 21599 "Package " + packageName + " not installed for user " + userId); 21600 } 21601 } 21602 } 21603 21604 private List<String> collectAbsoluteCodePaths() { 21605 synchronized (mPackages) { 21606 List<String> codePaths = new ArrayList<>(); 21607 final int packageCount = mSettings.mPackages.size(); 21608 for (int i = 0; i < packageCount; i++) { 21609 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21610 codePaths.add(ps.codePath.getAbsolutePath()); 21611 } 21612 return codePaths; 21613 } 21614 } 21615 21616 /** 21617 * Examine all apps present on given mounted volume, and destroy apps that 21618 * aren't expected, either due to uninstallation or reinstallation on 21619 * another volume. 21620 */ 21621 private void reconcileApps(String volumeUuid) { 21622 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21623 List<File> filesToDelete = null; 21624 21625 final File[] files = FileUtils.listFilesOrEmpty( 21626 Environment.getDataAppDirectory(volumeUuid)); 21627 for (File file : files) { 21628 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21629 && !PackageInstallerService.isStageName(file.getName()); 21630 if (!isPackage) { 21631 // Ignore entries which are not packages 21632 continue; 21633 } 21634 21635 String absolutePath = file.getAbsolutePath(); 21636 21637 boolean pathValid = false; 21638 final int absoluteCodePathCount = absoluteCodePaths.size(); 21639 for (int i = 0; i < absoluteCodePathCount; i++) { 21640 String absoluteCodePath = absoluteCodePaths.get(i); 21641 if (absolutePath.startsWith(absoluteCodePath)) { 21642 pathValid = true; 21643 break; 21644 } 21645 } 21646 21647 if (!pathValid) { 21648 if (filesToDelete == null) { 21649 filesToDelete = new ArrayList<>(); 21650 } 21651 filesToDelete.add(file); 21652 } 21653 } 21654 21655 if (filesToDelete != null) { 21656 final int fileToDeleteCount = filesToDelete.size(); 21657 for (int i = 0; i < fileToDeleteCount; i++) { 21658 File fileToDelete = filesToDelete.get(i); 21659 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21660 synchronized (mInstallLock) { 21661 removeCodePathLI(fileToDelete); 21662 } 21663 } 21664 } 21665 } 21666 21667 /** 21668 * Reconcile all app data for the given user. 21669 * <p> 21670 * Verifies that directories exist and that ownership and labeling is 21671 * correct for all installed apps on all mounted volumes. 21672 */ 21673 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21674 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21675 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21676 final String volumeUuid = vol.getFsUuid(); 21677 synchronized (mInstallLock) { 21678 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21679 } 21680 } 21681 } 21682 21683 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21684 boolean migrateAppData) { 21685 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21686 } 21687 21688 /** 21689 * Reconcile all app data on given mounted volume. 21690 * <p> 21691 * Destroys app data that isn't expected, either due to uninstallation or 21692 * reinstallation on another volume. 21693 * <p> 21694 * Verifies that directories exist and that ownership and labeling is 21695 * correct for all installed apps. 21696 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21697 */ 21698 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21699 boolean migrateAppData, boolean onlyCoreApps) { 21700 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21701 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21702 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21703 21704 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21705 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21706 21707 // First look for stale data that doesn't belong, and check if things 21708 // have changed since we did our last restorecon 21709 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21710 if (StorageManager.isFileEncryptedNativeOrEmulated() 21711 && !StorageManager.isUserKeyUnlocked(userId)) { 21712 throw new RuntimeException( 21713 "Yikes, someone asked us to reconcile CE storage while " + userId 21714 + " was still locked; this would have caused massive data loss!"); 21715 } 21716 21717 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21718 for (File file : files) { 21719 final String packageName = file.getName(); 21720 try { 21721 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21722 } catch (PackageManagerException e) { 21723 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21724 try { 21725 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21726 StorageManager.FLAG_STORAGE_CE, 0); 21727 } catch (InstallerException e2) { 21728 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21729 } 21730 } 21731 } 21732 } 21733 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21734 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21735 for (File file : files) { 21736 final String packageName = file.getName(); 21737 try { 21738 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21739 } catch (PackageManagerException e) { 21740 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21741 try { 21742 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21743 StorageManager.FLAG_STORAGE_DE, 0); 21744 } catch (InstallerException e2) { 21745 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21746 } 21747 } 21748 } 21749 } 21750 21751 // Ensure that data directories are ready to roll for all packages 21752 // installed for this volume and user 21753 final List<PackageSetting> packages; 21754 synchronized (mPackages) { 21755 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21756 } 21757 int preparedCount = 0; 21758 for (PackageSetting ps : packages) { 21759 final String packageName = ps.name; 21760 if (ps.pkg == null) { 21761 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21762 // TODO: might be due to legacy ASEC apps; we should circle back 21763 // and reconcile again once they're scanned 21764 continue; 21765 } 21766 // Skip non-core apps if requested 21767 if (onlyCoreApps && !ps.pkg.coreApp) { 21768 result.add(packageName); 21769 continue; 21770 } 21771 21772 if (ps.getInstalled(userId)) { 21773 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21774 preparedCount++; 21775 } 21776 } 21777 21778 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21779 return result; 21780 } 21781 21782 /** 21783 * Prepare app data for the given app just after it was installed or 21784 * upgraded. This method carefully only touches users that it's installed 21785 * for, and it forces a restorecon to handle any seinfo changes. 21786 * <p> 21787 * Verifies that directories exist and that ownership and labeling is 21788 * correct for all installed apps. If there is an ownership mismatch, it 21789 * will try recovering system apps by wiping data; third-party app data is 21790 * left intact. 21791 * <p> 21792 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21793 */ 21794 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21795 final PackageSetting ps; 21796 synchronized (mPackages) { 21797 ps = mSettings.mPackages.get(pkg.packageName); 21798 mSettings.writeKernelMappingLPr(ps); 21799 } 21800 21801 final UserManager um = mContext.getSystemService(UserManager.class); 21802 UserManagerInternal umInternal = getUserManagerInternal(); 21803 for (UserInfo user : um.getUsers()) { 21804 final int flags; 21805 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21806 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21807 } else if (umInternal.isUserRunning(user.id)) { 21808 flags = StorageManager.FLAG_STORAGE_DE; 21809 } else { 21810 continue; 21811 } 21812 21813 if (ps.getInstalled(user.id)) { 21814 // TODO: when user data is locked, mark that we're still dirty 21815 prepareAppDataLIF(pkg, user.id, flags); 21816 } 21817 } 21818 } 21819 21820 /** 21821 * Prepare app data for the given app. 21822 * <p> 21823 * Verifies that directories exist and that ownership and labeling is 21824 * correct for all installed apps. If there is an ownership mismatch, this 21825 * will try recovering system apps by wiping data; third-party app data is 21826 * left intact. 21827 */ 21828 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21829 if (pkg == null) { 21830 Slog.wtf(TAG, "Package was null!", new Throwable()); 21831 return; 21832 } 21833 prepareAppDataLeafLIF(pkg, userId, flags); 21834 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21835 for (int i = 0; i < childCount; i++) { 21836 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21837 } 21838 } 21839 21840 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21841 boolean maybeMigrateAppData) { 21842 prepareAppDataLIF(pkg, userId, flags); 21843 21844 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21845 // We may have just shuffled around app data directories, so 21846 // prepare them one more time 21847 prepareAppDataLIF(pkg, userId, flags); 21848 } 21849 } 21850 21851 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21852 if (DEBUG_APP_DATA) { 21853 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21854 + Integer.toHexString(flags)); 21855 } 21856 21857 final String volumeUuid = pkg.volumeUuid; 21858 final String packageName = pkg.packageName; 21859 final ApplicationInfo app = pkg.applicationInfo; 21860 final int appId = UserHandle.getAppId(app.uid); 21861 21862 Preconditions.checkNotNull(app.seInfo); 21863 21864 long ceDataInode = -1; 21865 try { 21866 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21867 appId, app.seInfo, app.targetSdkVersion); 21868 } catch (InstallerException e) { 21869 if (app.isSystemApp()) { 21870 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21871 + ", but trying to recover: " + e); 21872 destroyAppDataLeafLIF(pkg, userId, flags); 21873 try { 21874 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21875 appId, app.seInfo, app.targetSdkVersion); 21876 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21877 } catch (InstallerException e2) { 21878 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21879 } 21880 } else { 21881 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21882 } 21883 } 21884 21885 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21886 // TODO: mark this structure as dirty so we persist it! 21887 synchronized (mPackages) { 21888 final PackageSetting ps = mSettings.mPackages.get(packageName); 21889 if (ps != null) { 21890 ps.setCeDataInode(ceDataInode, userId); 21891 } 21892 } 21893 } 21894 21895 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21896 } 21897 21898 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21899 if (pkg == null) { 21900 Slog.wtf(TAG, "Package was null!", new Throwable()); 21901 return; 21902 } 21903 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21904 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21905 for (int i = 0; i < childCount; i++) { 21906 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21907 } 21908 } 21909 21910 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21911 final String volumeUuid = pkg.volumeUuid; 21912 final String packageName = pkg.packageName; 21913 final ApplicationInfo app = pkg.applicationInfo; 21914 21915 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21916 // Create a native library symlink only if we have native libraries 21917 // and if the native libraries are 32 bit libraries. We do not provide 21918 // this symlink for 64 bit libraries. 21919 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21920 final String nativeLibPath = app.nativeLibraryDir; 21921 try { 21922 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21923 nativeLibPath, userId); 21924 } catch (InstallerException e) { 21925 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21926 } 21927 } 21928 } 21929 } 21930 21931 /** 21932 * For system apps on non-FBE devices, this method migrates any existing 21933 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21934 * requested by the app. 21935 */ 21936 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21937 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 21938 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21939 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21940 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21941 try { 21942 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21943 storageTarget); 21944 } catch (InstallerException e) { 21945 logCriticalInfo(Log.WARN, 21946 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21947 } 21948 return true; 21949 } else { 21950 return false; 21951 } 21952 } 21953 21954 public PackageFreezer freezePackage(String packageName, String killReason) { 21955 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21956 } 21957 21958 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21959 return new PackageFreezer(packageName, userId, killReason); 21960 } 21961 21962 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21963 String killReason) { 21964 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21965 } 21966 21967 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21968 String killReason) { 21969 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21970 return new PackageFreezer(); 21971 } else { 21972 return freezePackage(packageName, userId, killReason); 21973 } 21974 } 21975 21976 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21977 String killReason) { 21978 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21979 } 21980 21981 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21982 String killReason) { 21983 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21984 return new PackageFreezer(); 21985 } else { 21986 return freezePackage(packageName, userId, killReason); 21987 } 21988 } 21989 21990 /** 21991 * Class that freezes and kills the given package upon creation, and 21992 * unfreezes it upon closing. This is typically used when doing surgery on 21993 * app code/data to prevent the app from running while you're working. 21994 */ 21995 private class PackageFreezer implements AutoCloseable { 21996 private final String mPackageName; 21997 private final PackageFreezer[] mChildren; 21998 21999 private final boolean mWeFroze; 22000 22001 private final AtomicBoolean mClosed = new AtomicBoolean(); 22002 private final CloseGuard mCloseGuard = CloseGuard.get(); 22003 22004 /** 22005 * Create and return a stub freezer that doesn't actually do anything, 22006 * typically used when someone requested 22007 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22008 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22009 */ 22010 public PackageFreezer() { 22011 mPackageName = null; 22012 mChildren = null; 22013 mWeFroze = false; 22014 mCloseGuard.open("close"); 22015 } 22016 22017 public PackageFreezer(String packageName, int userId, String killReason) { 22018 synchronized (mPackages) { 22019 mPackageName = packageName; 22020 mWeFroze = mFrozenPackages.add(mPackageName); 22021 22022 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22023 if (ps != null) { 22024 killApplication(ps.name, ps.appId, userId, killReason); 22025 } 22026 22027 final PackageParser.Package p = mPackages.get(packageName); 22028 if (p != null && p.childPackages != null) { 22029 final int N = p.childPackages.size(); 22030 mChildren = new PackageFreezer[N]; 22031 for (int i = 0; i < N; i++) { 22032 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22033 userId, killReason); 22034 } 22035 } else { 22036 mChildren = null; 22037 } 22038 } 22039 mCloseGuard.open("close"); 22040 } 22041 22042 @Override 22043 protected void finalize() throws Throwable { 22044 try { 22045 mCloseGuard.warnIfOpen(); 22046 close(); 22047 } finally { 22048 super.finalize(); 22049 } 22050 } 22051 22052 @Override 22053 public void close() { 22054 mCloseGuard.close(); 22055 if (mClosed.compareAndSet(false, true)) { 22056 synchronized (mPackages) { 22057 if (mWeFroze) { 22058 mFrozenPackages.remove(mPackageName); 22059 } 22060 22061 if (mChildren != null) { 22062 for (PackageFreezer freezer : mChildren) { 22063 freezer.close(); 22064 } 22065 } 22066 } 22067 } 22068 } 22069 } 22070 22071 /** 22072 * Verify that given package is currently frozen. 22073 */ 22074 private void checkPackageFrozen(String packageName) { 22075 synchronized (mPackages) { 22076 if (!mFrozenPackages.contains(packageName)) { 22077 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22078 } 22079 } 22080 } 22081 22082 @Override 22083 public int movePackage(final String packageName, final String volumeUuid) { 22084 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22085 22086 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22087 final int moveId = mNextMoveId.getAndIncrement(); 22088 mHandler.post(new Runnable() { 22089 @Override 22090 public void run() { 22091 try { 22092 movePackageInternal(packageName, volumeUuid, moveId, user); 22093 } catch (PackageManagerException e) { 22094 Slog.w(TAG, "Failed to move " + packageName, e); 22095 mMoveCallbacks.notifyStatusChanged(moveId, 22096 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22097 } 22098 } 22099 }); 22100 return moveId; 22101 } 22102 22103 private void movePackageInternal(final String packageName, final String volumeUuid, 22104 final int moveId, UserHandle user) throws PackageManagerException { 22105 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22106 final PackageManager pm = mContext.getPackageManager(); 22107 22108 final boolean currentAsec; 22109 final String currentVolumeUuid; 22110 final File codeFile; 22111 final String installerPackageName; 22112 final String packageAbiOverride; 22113 final int appId; 22114 final String seinfo; 22115 final String label; 22116 final int targetSdkVersion; 22117 final PackageFreezer freezer; 22118 final int[] installedUserIds; 22119 22120 // reader 22121 synchronized (mPackages) { 22122 final PackageParser.Package pkg = mPackages.get(packageName); 22123 final PackageSetting ps = mSettings.mPackages.get(packageName); 22124 if (pkg == null || ps == null) { 22125 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22126 } 22127 22128 if (pkg.applicationInfo.isSystemApp()) { 22129 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22130 "Cannot move system application"); 22131 } 22132 22133 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22134 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22135 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22136 if (isInternalStorage && !allow3rdPartyOnInternal) { 22137 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22138 "3rd party apps are not allowed on internal storage"); 22139 } 22140 22141 if (pkg.applicationInfo.isExternalAsec()) { 22142 currentAsec = true; 22143 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22144 } else if (pkg.applicationInfo.isForwardLocked()) { 22145 currentAsec = true; 22146 currentVolumeUuid = "forward_locked"; 22147 } else { 22148 currentAsec = false; 22149 currentVolumeUuid = ps.volumeUuid; 22150 22151 final File probe = new File(pkg.codePath); 22152 final File probeOat = new File(probe, "oat"); 22153 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22154 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22155 "Move only supported for modern cluster style installs"); 22156 } 22157 } 22158 22159 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22160 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22161 "Package already moved to " + volumeUuid); 22162 } 22163 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22164 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22165 "Device admin cannot be moved"); 22166 } 22167 22168 if (mFrozenPackages.contains(packageName)) { 22169 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22170 "Failed to move already frozen package"); 22171 } 22172 22173 codeFile = new File(pkg.codePath); 22174 installerPackageName = ps.installerPackageName; 22175 packageAbiOverride = ps.cpuAbiOverrideString; 22176 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22177 seinfo = pkg.applicationInfo.seInfo; 22178 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22179 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22180 freezer = freezePackage(packageName, "movePackageInternal"); 22181 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22182 } 22183 22184 final Bundle extras = new Bundle(); 22185 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22186 extras.putString(Intent.EXTRA_TITLE, label); 22187 mMoveCallbacks.notifyCreated(moveId, extras); 22188 22189 int installFlags; 22190 final boolean moveCompleteApp; 22191 final File measurePath; 22192 22193 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22194 installFlags = INSTALL_INTERNAL; 22195 moveCompleteApp = !currentAsec; 22196 measurePath = Environment.getDataAppDirectory(volumeUuid); 22197 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22198 installFlags = INSTALL_EXTERNAL; 22199 moveCompleteApp = false; 22200 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22201 } else { 22202 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22203 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22204 || !volume.isMountedWritable()) { 22205 freezer.close(); 22206 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22207 "Move location not mounted private volume"); 22208 } 22209 22210 Preconditions.checkState(!currentAsec); 22211 22212 installFlags = INSTALL_INTERNAL; 22213 moveCompleteApp = true; 22214 measurePath = Environment.getDataAppDirectory(volumeUuid); 22215 } 22216 22217 final PackageStats stats = new PackageStats(null, -1); 22218 synchronized (mInstaller) { 22219 for (int userId : installedUserIds) { 22220 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22221 freezer.close(); 22222 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22223 "Failed to measure package size"); 22224 } 22225 } 22226 } 22227 22228 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22229 + stats.dataSize); 22230 22231 final long startFreeBytes = measurePath.getFreeSpace(); 22232 final long sizeBytes; 22233 if (moveCompleteApp) { 22234 sizeBytes = stats.codeSize + stats.dataSize; 22235 } else { 22236 sizeBytes = stats.codeSize; 22237 } 22238 22239 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22240 freezer.close(); 22241 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22242 "Not enough free space to move"); 22243 } 22244 22245 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22246 22247 final CountDownLatch installedLatch = new CountDownLatch(1); 22248 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22249 @Override 22250 public void onUserActionRequired(Intent intent) throws RemoteException { 22251 throw new IllegalStateException(); 22252 } 22253 22254 @Override 22255 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22256 Bundle extras) throws RemoteException { 22257 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22258 + PackageManager.installStatusToString(returnCode, msg)); 22259 22260 installedLatch.countDown(); 22261 freezer.close(); 22262 22263 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22264 switch (status) { 22265 case PackageInstaller.STATUS_SUCCESS: 22266 mMoveCallbacks.notifyStatusChanged(moveId, 22267 PackageManager.MOVE_SUCCEEDED); 22268 break; 22269 case PackageInstaller.STATUS_FAILURE_STORAGE: 22270 mMoveCallbacks.notifyStatusChanged(moveId, 22271 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22272 break; 22273 default: 22274 mMoveCallbacks.notifyStatusChanged(moveId, 22275 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22276 break; 22277 } 22278 } 22279 }; 22280 22281 final MoveInfo move; 22282 if (moveCompleteApp) { 22283 // Kick off a thread to report progress estimates 22284 new Thread() { 22285 @Override 22286 public void run() { 22287 while (true) { 22288 try { 22289 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22290 break; 22291 } 22292 } catch (InterruptedException ignored) { 22293 } 22294 22295 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 22296 final int progress = 10 + (int) MathUtils.constrain( 22297 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22298 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22299 } 22300 } 22301 }.start(); 22302 22303 final String dataAppName = codeFile.getName(); 22304 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22305 dataAppName, appId, seinfo, targetSdkVersion); 22306 } else { 22307 move = null; 22308 } 22309 22310 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22311 22312 final Message msg = mHandler.obtainMessage(INIT_COPY); 22313 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22314 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22315 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22316 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22317 PackageManager.INSTALL_REASON_UNKNOWN); 22318 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22319 msg.obj = params; 22320 22321 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22322 System.identityHashCode(msg.obj)); 22323 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22324 System.identityHashCode(msg.obj)); 22325 22326 mHandler.sendMessage(msg); 22327 } 22328 22329 @Override 22330 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22331 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22332 22333 final int realMoveId = mNextMoveId.getAndIncrement(); 22334 final Bundle extras = new Bundle(); 22335 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22336 mMoveCallbacks.notifyCreated(realMoveId, extras); 22337 22338 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22339 @Override 22340 public void onCreated(int moveId, Bundle extras) { 22341 // Ignored 22342 } 22343 22344 @Override 22345 public void onStatusChanged(int moveId, int status, long estMillis) { 22346 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22347 } 22348 }; 22349 22350 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22351 storage.setPrimaryStorageUuid(volumeUuid, callback); 22352 return realMoveId; 22353 } 22354 22355 @Override 22356 public int getMoveStatus(int moveId) { 22357 mContext.enforceCallingOrSelfPermission( 22358 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22359 return mMoveCallbacks.mLastStatus.get(moveId); 22360 } 22361 22362 @Override 22363 public void registerMoveCallback(IPackageMoveObserver callback) { 22364 mContext.enforceCallingOrSelfPermission( 22365 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22366 mMoveCallbacks.register(callback); 22367 } 22368 22369 @Override 22370 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22371 mContext.enforceCallingOrSelfPermission( 22372 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22373 mMoveCallbacks.unregister(callback); 22374 } 22375 22376 @Override 22377 public boolean setInstallLocation(int loc) { 22378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22379 null); 22380 if (getInstallLocation() == loc) { 22381 return true; 22382 } 22383 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22384 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22385 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22386 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22387 return true; 22388 } 22389 return false; 22390 } 22391 22392 @Override 22393 public int getInstallLocation() { 22394 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22395 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22396 PackageHelper.APP_INSTALL_AUTO); 22397 } 22398 22399 /** Called by UserManagerService */ 22400 void cleanUpUser(UserManagerService userManager, int userHandle) { 22401 synchronized (mPackages) { 22402 mDirtyUsers.remove(userHandle); 22403 mUserNeedsBadging.delete(userHandle); 22404 mSettings.removeUserLPw(userHandle); 22405 mPendingBroadcasts.remove(userHandle); 22406 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22407 removeUnusedPackagesLPw(userManager, userHandle); 22408 } 22409 } 22410 22411 /** 22412 * We're removing userHandle and would like to remove any downloaded packages 22413 * that are no longer in use by any other user. 22414 * @param userHandle the user being removed 22415 */ 22416 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22417 final boolean DEBUG_CLEAN_APKS = false; 22418 int [] users = userManager.getUserIds(); 22419 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22420 while (psit.hasNext()) { 22421 PackageSetting ps = psit.next(); 22422 if (ps.pkg == null) { 22423 continue; 22424 } 22425 final String packageName = ps.pkg.packageName; 22426 // Skip over if system app 22427 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22428 continue; 22429 } 22430 if (DEBUG_CLEAN_APKS) { 22431 Slog.i(TAG, "Checking package " + packageName); 22432 } 22433 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22434 if (keep) { 22435 if (DEBUG_CLEAN_APKS) { 22436 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22437 } 22438 } else { 22439 for (int i = 0; i < users.length; i++) { 22440 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22441 keep = true; 22442 if (DEBUG_CLEAN_APKS) { 22443 Slog.i(TAG, " Keeping package " + packageName + " for user " 22444 + users[i]); 22445 } 22446 break; 22447 } 22448 } 22449 } 22450 if (!keep) { 22451 if (DEBUG_CLEAN_APKS) { 22452 Slog.i(TAG, " Removing package " + packageName); 22453 } 22454 mHandler.post(new Runnable() { 22455 public void run() { 22456 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22457 userHandle, 0); 22458 } //end run 22459 }); 22460 } 22461 } 22462 } 22463 22464 /** Called by UserManagerService */ 22465 void createNewUser(int userId, String[] disallowedPackages) { 22466 synchronized (mInstallLock) { 22467 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22468 } 22469 synchronized (mPackages) { 22470 scheduleWritePackageRestrictionsLocked(userId); 22471 scheduleWritePackageListLocked(userId); 22472 applyFactoryDefaultBrowserLPw(userId); 22473 primeDomainVerificationsLPw(userId); 22474 } 22475 } 22476 22477 void onNewUserCreated(final int userId) { 22478 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22479 // If permission review for legacy apps is required, we represent 22480 // dagerous permissions for such apps as always granted runtime 22481 // permissions to keep per user flag state whether review is needed. 22482 // Hence, if a new user is added we have to propagate dangerous 22483 // permission grants for these legacy apps. 22484 if (mPermissionReviewRequired) { 22485 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22486 | UPDATE_PERMISSIONS_REPLACE_ALL); 22487 } 22488 } 22489 22490 @Override 22491 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22492 mContext.enforceCallingOrSelfPermission( 22493 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22494 "Only package verification agents can read the verifier device identity"); 22495 22496 synchronized (mPackages) { 22497 return mSettings.getVerifierDeviceIdentityLPw(); 22498 } 22499 } 22500 22501 @Override 22502 public void setPermissionEnforced(String permission, boolean enforced) { 22503 // TODO: Now that we no longer change GID for storage, this should to away. 22504 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22505 "setPermissionEnforced"); 22506 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22507 synchronized (mPackages) { 22508 if (mSettings.mReadExternalStorageEnforced == null 22509 || mSettings.mReadExternalStorageEnforced != enforced) { 22510 mSettings.mReadExternalStorageEnforced = enforced; 22511 mSettings.writeLPr(); 22512 } 22513 } 22514 // kill any non-foreground processes so we restart them and 22515 // grant/revoke the GID. 22516 final IActivityManager am = ActivityManager.getService(); 22517 if (am != null) { 22518 final long token = Binder.clearCallingIdentity(); 22519 try { 22520 am.killProcessesBelowForeground("setPermissionEnforcement"); 22521 } catch (RemoteException e) { 22522 } finally { 22523 Binder.restoreCallingIdentity(token); 22524 } 22525 } 22526 } else { 22527 throw new IllegalArgumentException("No selective enforcement for " + permission); 22528 } 22529 } 22530 22531 @Override 22532 @Deprecated 22533 public boolean isPermissionEnforced(String permission) { 22534 return true; 22535 } 22536 22537 @Override 22538 public boolean isStorageLow() { 22539 final long token = Binder.clearCallingIdentity(); 22540 try { 22541 final DeviceStorageMonitorInternal 22542 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22543 if (dsm != null) { 22544 return dsm.isMemoryLow(); 22545 } else { 22546 return false; 22547 } 22548 } finally { 22549 Binder.restoreCallingIdentity(token); 22550 } 22551 } 22552 22553 @Override 22554 public IPackageInstaller getPackageInstaller() { 22555 return mInstallerService; 22556 } 22557 22558 private boolean userNeedsBadging(int userId) { 22559 int index = mUserNeedsBadging.indexOfKey(userId); 22560 if (index < 0) { 22561 final UserInfo userInfo; 22562 final long token = Binder.clearCallingIdentity(); 22563 try { 22564 userInfo = sUserManager.getUserInfo(userId); 22565 } finally { 22566 Binder.restoreCallingIdentity(token); 22567 } 22568 final boolean b; 22569 if (userInfo != null && userInfo.isManagedProfile()) { 22570 b = true; 22571 } else { 22572 b = false; 22573 } 22574 mUserNeedsBadging.put(userId, b); 22575 return b; 22576 } 22577 return mUserNeedsBadging.valueAt(index); 22578 } 22579 22580 @Override 22581 public KeySet getKeySetByAlias(String packageName, String alias) { 22582 if (packageName == null || alias == null) { 22583 return null; 22584 } 22585 synchronized(mPackages) { 22586 final PackageParser.Package pkg = mPackages.get(packageName); 22587 if (pkg == null) { 22588 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22589 throw new IllegalArgumentException("Unknown package: " + packageName); 22590 } 22591 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22592 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22593 } 22594 } 22595 22596 @Override 22597 public KeySet getSigningKeySet(String packageName) { 22598 if (packageName == null) { 22599 return null; 22600 } 22601 synchronized(mPackages) { 22602 final PackageParser.Package pkg = mPackages.get(packageName); 22603 if (pkg == null) { 22604 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22605 throw new IllegalArgumentException("Unknown package: " + packageName); 22606 } 22607 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22608 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22609 throw new SecurityException("May not access signing KeySet of other apps."); 22610 } 22611 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22612 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22613 } 22614 } 22615 22616 @Override 22617 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22618 if (packageName == null || ks == null) { 22619 return false; 22620 } 22621 synchronized(mPackages) { 22622 final PackageParser.Package pkg = mPackages.get(packageName); 22623 if (pkg == null) { 22624 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22625 throw new IllegalArgumentException("Unknown package: " + packageName); 22626 } 22627 IBinder ksh = ks.getToken(); 22628 if (ksh instanceof KeySetHandle) { 22629 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22630 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22631 } 22632 return false; 22633 } 22634 } 22635 22636 @Override 22637 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22638 if (packageName == null || ks == null) { 22639 return false; 22640 } 22641 synchronized(mPackages) { 22642 final PackageParser.Package pkg = mPackages.get(packageName); 22643 if (pkg == null) { 22644 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22645 throw new IllegalArgumentException("Unknown package: " + packageName); 22646 } 22647 IBinder ksh = ks.getToken(); 22648 if (ksh instanceof KeySetHandle) { 22649 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22650 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22651 } 22652 return false; 22653 } 22654 } 22655 22656 private void deletePackageIfUnusedLPr(final String packageName) { 22657 PackageSetting ps = mSettings.mPackages.get(packageName); 22658 if (ps == null) { 22659 return; 22660 } 22661 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22662 // TODO Implement atomic delete if package is unused 22663 // It is currently possible that the package will be deleted even if it is installed 22664 // after this method returns. 22665 mHandler.post(new Runnable() { 22666 public void run() { 22667 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22668 0, PackageManager.DELETE_ALL_USERS); 22669 } 22670 }); 22671 } 22672 } 22673 22674 /** 22675 * Check and throw if the given before/after packages would be considered a 22676 * downgrade. 22677 */ 22678 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22679 throws PackageManagerException { 22680 if (after.versionCode < before.mVersionCode) { 22681 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22682 "Update version code " + after.versionCode + " is older than current " 22683 + before.mVersionCode); 22684 } else if (after.versionCode == before.mVersionCode) { 22685 if (after.baseRevisionCode < before.baseRevisionCode) { 22686 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22687 "Update base revision code " + after.baseRevisionCode 22688 + " is older than current " + before.baseRevisionCode); 22689 } 22690 22691 if (!ArrayUtils.isEmpty(after.splitNames)) { 22692 for (int i = 0; i < after.splitNames.length; i++) { 22693 final String splitName = after.splitNames[i]; 22694 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22695 if (j != -1) { 22696 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22697 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22698 "Update split " + splitName + " revision code " 22699 + after.splitRevisionCodes[i] + " is older than current " 22700 + before.splitRevisionCodes[j]); 22701 } 22702 } 22703 } 22704 } 22705 } 22706 } 22707 22708 private static class MoveCallbacks extends Handler { 22709 private static final int MSG_CREATED = 1; 22710 private static final int MSG_STATUS_CHANGED = 2; 22711 22712 private final RemoteCallbackList<IPackageMoveObserver> 22713 mCallbacks = new RemoteCallbackList<>(); 22714 22715 private final SparseIntArray mLastStatus = new SparseIntArray(); 22716 22717 public MoveCallbacks(Looper looper) { 22718 super(looper); 22719 } 22720 22721 public void register(IPackageMoveObserver callback) { 22722 mCallbacks.register(callback); 22723 } 22724 22725 public void unregister(IPackageMoveObserver callback) { 22726 mCallbacks.unregister(callback); 22727 } 22728 22729 @Override 22730 public void handleMessage(Message msg) { 22731 final SomeArgs args = (SomeArgs) msg.obj; 22732 final int n = mCallbacks.beginBroadcast(); 22733 for (int i = 0; i < n; i++) { 22734 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22735 try { 22736 invokeCallback(callback, msg.what, args); 22737 } catch (RemoteException ignored) { 22738 } 22739 } 22740 mCallbacks.finishBroadcast(); 22741 args.recycle(); 22742 } 22743 22744 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22745 throws RemoteException { 22746 switch (what) { 22747 case MSG_CREATED: { 22748 callback.onCreated(args.argi1, (Bundle) args.arg2); 22749 break; 22750 } 22751 case MSG_STATUS_CHANGED: { 22752 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22753 break; 22754 } 22755 } 22756 } 22757 22758 private void notifyCreated(int moveId, Bundle extras) { 22759 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22760 22761 final SomeArgs args = SomeArgs.obtain(); 22762 args.argi1 = moveId; 22763 args.arg2 = extras; 22764 obtainMessage(MSG_CREATED, args).sendToTarget(); 22765 } 22766 22767 private void notifyStatusChanged(int moveId, int status) { 22768 notifyStatusChanged(moveId, status, -1); 22769 } 22770 22771 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22772 Slog.v(TAG, "Move " + moveId + " status " + status); 22773 22774 final SomeArgs args = SomeArgs.obtain(); 22775 args.argi1 = moveId; 22776 args.argi2 = status; 22777 args.arg3 = estMillis; 22778 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22779 22780 synchronized (mLastStatus) { 22781 mLastStatus.put(moveId, status); 22782 } 22783 } 22784 } 22785 22786 private final static class OnPermissionChangeListeners extends Handler { 22787 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22788 22789 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22790 new RemoteCallbackList<>(); 22791 22792 public OnPermissionChangeListeners(Looper looper) { 22793 super(looper); 22794 } 22795 22796 @Override 22797 public void handleMessage(Message msg) { 22798 switch (msg.what) { 22799 case MSG_ON_PERMISSIONS_CHANGED: { 22800 final int uid = msg.arg1; 22801 handleOnPermissionsChanged(uid); 22802 } break; 22803 } 22804 } 22805 22806 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22807 mPermissionListeners.register(listener); 22808 22809 } 22810 22811 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22812 mPermissionListeners.unregister(listener); 22813 } 22814 22815 public void onPermissionsChanged(int uid) { 22816 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22817 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22818 } 22819 } 22820 22821 private void handleOnPermissionsChanged(int uid) { 22822 final int count = mPermissionListeners.beginBroadcast(); 22823 try { 22824 for (int i = 0; i < count; i++) { 22825 IOnPermissionsChangeListener callback = mPermissionListeners 22826 .getBroadcastItem(i); 22827 try { 22828 callback.onPermissionsChanged(uid); 22829 } catch (RemoteException e) { 22830 Log.e(TAG, "Permission listener is dead", e); 22831 } 22832 } 22833 } finally { 22834 mPermissionListeners.finishBroadcast(); 22835 } 22836 } 22837 } 22838 22839 private class PackageManagerInternalImpl extends PackageManagerInternal { 22840 @Override 22841 public void setLocationPackagesProvider(PackagesProvider provider) { 22842 synchronized (mPackages) { 22843 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 22844 } 22845 } 22846 22847 @Override 22848 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 22849 synchronized (mPackages) { 22850 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 22851 } 22852 } 22853 22854 @Override 22855 public void setSmsAppPackagesProvider(PackagesProvider provider) { 22856 synchronized (mPackages) { 22857 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 22858 } 22859 } 22860 22861 @Override 22862 public void setDialerAppPackagesProvider(PackagesProvider provider) { 22863 synchronized (mPackages) { 22864 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 22865 } 22866 } 22867 22868 @Override 22869 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 22870 synchronized (mPackages) { 22871 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 22872 } 22873 } 22874 22875 @Override 22876 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 22877 synchronized (mPackages) { 22878 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 22879 } 22880 } 22881 22882 @Override 22883 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 22884 synchronized (mPackages) { 22885 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 22886 packageName, userId); 22887 } 22888 } 22889 22890 @Override 22891 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 22892 synchronized (mPackages) { 22893 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 22894 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 22895 packageName, userId); 22896 } 22897 } 22898 22899 @Override 22900 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 22901 synchronized (mPackages) { 22902 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 22903 packageName, userId); 22904 } 22905 } 22906 22907 @Override 22908 public void setKeepUninstalledPackages(final List<String> packageList) { 22909 Preconditions.checkNotNull(packageList); 22910 List<String> removedFromList = null; 22911 synchronized (mPackages) { 22912 if (mKeepUninstalledPackages != null) { 22913 final int packagesCount = mKeepUninstalledPackages.size(); 22914 for (int i = 0; i < packagesCount; i++) { 22915 String oldPackage = mKeepUninstalledPackages.get(i); 22916 if (packageList != null && packageList.contains(oldPackage)) { 22917 continue; 22918 } 22919 if (removedFromList == null) { 22920 removedFromList = new ArrayList<>(); 22921 } 22922 removedFromList.add(oldPackage); 22923 } 22924 } 22925 mKeepUninstalledPackages = new ArrayList<>(packageList); 22926 if (removedFromList != null) { 22927 final int removedCount = removedFromList.size(); 22928 for (int i = 0; i < removedCount; i++) { 22929 deletePackageIfUnusedLPr(removedFromList.get(i)); 22930 } 22931 } 22932 } 22933 } 22934 22935 @Override 22936 public boolean isPermissionsReviewRequired(String packageName, int userId) { 22937 synchronized (mPackages) { 22938 // If we do not support permission review, done. 22939 if (!mPermissionReviewRequired) { 22940 return false; 22941 } 22942 22943 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 22944 if (packageSetting == null) { 22945 return false; 22946 } 22947 22948 // Permission review applies only to apps not supporting the new permission model. 22949 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 22950 return false; 22951 } 22952 22953 // Legacy apps have the permission and get user consent on launch. 22954 PermissionsState permissionsState = packageSetting.getPermissionsState(); 22955 return permissionsState.isPermissionReviewRequired(userId); 22956 } 22957 } 22958 22959 @Override 22960 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 22961 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 22962 } 22963 22964 @Override 22965 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 22966 int userId) { 22967 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 22968 } 22969 22970 @Override 22971 public void setDeviceAndProfileOwnerPackages( 22972 int deviceOwnerUserId, String deviceOwnerPackage, 22973 SparseArray<String> profileOwnerPackages) { 22974 mProtectedPackages.setDeviceAndProfileOwnerPackages( 22975 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 22976 } 22977 22978 @Override 22979 public boolean isPackageDataProtected(int userId, String packageName) { 22980 return mProtectedPackages.isPackageDataProtected(userId, packageName); 22981 } 22982 22983 @Override 22984 public boolean isPackageEphemeral(int userId, String packageName) { 22985 synchronized (mPackages) { 22986 final PackageSetting ps = mSettings.mPackages.get(packageName); 22987 return ps != null ? ps.getInstantApp(userId) : false; 22988 } 22989 } 22990 22991 @Override 22992 public boolean wasPackageEverLaunched(String packageName, int userId) { 22993 synchronized (mPackages) { 22994 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 22995 } 22996 } 22997 22998 @Override 22999 public void grantRuntimePermission(String packageName, String name, int userId, 23000 boolean overridePolicy) { 23001 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23002 overridePolicy); 23003 } 23004 23005 @Override 23006 public void revokeRuntimePermission(String packageName, String name, int userId, 23007 boolean overridePolicy) { 23008 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23009 overridePolicy); 23010 } 23011 23012 @Override 23013 public String getNameForUid(int uid) { 23014 return PackageManagerService.this.getNameForUid(uid); 23015 } 23016 23017 @Override 23018 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23019 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23020 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23021 responseObj, origIntent, resolvedType, callingPackage, userId); 23022 } 23023 23024 @Override 23025 public void grantEphemeralAccess(int userId, Intent intent, 23026 int targetAppId, int ephemeralAppId) { 23027 synchronized (mPackages) { 23028 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23029 targetAppId, ephemeralAppId); 23030 } 23031 } 23032 23033 @Override 23034 public void pruneInstantApps() { 23035 synchronized (mPackages) { 23036 mInstantAppRegistry.pruneInstantAppsLPw(); 23037 } 23038 } 23039 23040 @Override 23041 public String getSetupWizardPackageName() { 23042 return mSetupWizardPackage; 23043 } 23044 23045 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23046 if (policy != null) { 23047 mExternalSourcesPolicy = policy; 23048 } 23049 } 23050 23051 @Override 23052 public boolean isPackagePersistent(String packageName) { 23053 synchronized (mPackages) { 23054 PackageParser.Package pkg = mPackages.get(packageName); 23055 return pkg != null 23056 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23057 | ApplicationInfo.FLAG_PERSISTENT)) == 23058 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23059 : false; 23060 } 23061 } 23062 23063 @Override 23064 public List<PackageInfo> getOverlayPackages(int userId) { 23065 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23066 synchronized (mPackages) { 23067 for (PackageParser.Package p : mPackages.values()) { 23068 if (p.mOverlayTarget != null) { 23069 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23070 if (pkg != null) { 23071 overlayPackages.add(pkg); 23072 } 23073 } 23074 } 23075 } 23076 return overlayPackages; 23077 } 23078 23079 @Override 23080 public List<String> getTargetPackageNames(int userId) { 23081 List<String> targetPackages = new ArrayList<>(); 23082 synchronized (mPackages) { 23083 for (PackageParser.Package p : mPackages.values()) { 23084 if (p.mOverlayTarget == null) { 23085 targetPackages.add(p.packageName); 23086 } 23087 } 23088 } 23089 return targetPackages; 23090 } 23091 23092 @Override 23093 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23094 @Nullable List<String> overlayPackageNames) { 23095 synchronized (mPackages) { 23096 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23097 Slog.e(TAG, "failed to find package " + targetPackageName); 23098 return false; 23099 } 23100 23101 ArrayList<String> paths = null; 23102 if (overlayPackageNames != null) { 23103 final int N = overlayPackageNames.size(); 23104 paths = new ArrayList<>(N); 23105 for (int i = 0; i < N; i++) { 23106 final String packageName = overlayPackageNames.get(i); 23107 final PackageParser.Package pkg = mPackages.get(packageName); 23108 if (pkg == null) { 23109 Slog.e(TAG, "failed to find package " + packageName); 23110 return false; 23111 } 23112 paths.add(pkg.baseCodePath); 23113 } 23114 } 23115 23116 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23117 mEnabledOverlayPaths.get(userId); 23118 if (userSpecificOverlays == null) { 23119 userSpecificOverlays = new ArrayMap<>(); 23120 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23121 } 23122 23123 if (paths != null && paths.size() > 0) { 23124 userSpecificOverlays.put(targetPackageName, paths); 23125 } else { 23126 userSpecificOverlays.remove(targetPackageName); 23127 } 23128 return true; 23129 } 23130 } 23131 23132 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23133 int flags, int userId) { 23134 return resolveIntentInternal( 23135 intent, resolvedType, flags, userId, true /*includeInstantApp*/); 23136 } 23137 } 23138 23139 @Override 23140 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23141 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23142 synchronized (mPackages) { 23143 final long identity = Binder.clearCallingIdentity(); 23144 try { 23145 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23146 packageNames, userId); 23147 } finally { 23148 Binder.restoreCallingIdentity(identity); 23149 } 23150 } 23151 } 23152 23153 @Override 23154 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23155 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23156 synchronized (mPackages) { 23157 final long identity = Binder.clearCallingIdentity(); 23158 try { 23159 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23160 packageNames, userId); 23161 } finally { 23162 Binder.restoreCallingIdentity(identity); 23163 } 23164 } 23165 } 23166 23167 private static void enforceSystemOrPhoneCaller(String tag) { 23168 int callingUid = Binder.getCallingUid(); 23169 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23170 throw new SecurityException( 23171 "Cannot call " + tag + " from UID " + callingUid); 23172 } 23173 } 23174 23175 boolean isHistoricalPackageUsageAvailable() { 23176 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23177 } 23178 23179 /** 23180 * Return a <b>copy</b> of the collection of packages known to the package manager. 23181 * @return A copy of the values of mPackages. 23182 */ 23183 Collection<PackageParser.Package> getPackages() { 23184 synchronized (mPackages) { 23185 return new ArrayList<>(mPackages.values()); 23186 } 23187 } 23188 23189 /** 23190 * Logs process start information (including base APK hash) to the security log. 23191 * @hide 23192 */ 23193 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23194 String apkFile, int pid) { 23195 if (!SecurityLog.isLoggingEnabled()) { 23196 return; 23197 } 23198 Bundle data = new Bundle(); 23199 data.putLong("startTimestamp", System.currentTimeMillis()); 23200 data.putString("processName", processName); 23201 data.putInt("uid", uid); 23202 data.putString("seinfo", seinfo); 23203 data.putString("apkFile", apkFile); 23204 data.putInt("pid", pid); 23205 Message msg = mProcessLoggingHandler.obtainMessage( 23206 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23207 msg.setData(data); 23208 mProcessLoggingHandler.sendMessage(msg); 23209 } 23210 23211 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23212 return mCompilerStats.getPackageStats(pkgName); 23213 } 23214 23215 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23216 return getOrCreateCompilerPackageStats(pkg.packageName); 23217 } 23218 23219 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23220 return mCompilerStats.getOrCreatePackageStats(pkgName); 23221 } 23222 23223 public void deleteCompilerPackageStats(String pkgName) { 23224 mCompilerStats.deletePackageStats(pkgName); 23225 } 23226 23227 @Override 23228 public int getInstallReason(String packageName, int userId) { 23229 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23230 true /* requireFullPermission */, false /* checkShell */, 23231 "get install reason"); 23232 synchronized (mPackages) { 23233 final PackageSetting ps = mSettings.mPackages.get(packageName); 23234 if (ps != null) { 23235 return ps.getInstallReason(userId); 23236 } 23237 } 23238 return PackageManager.INSTALL_REASON_UNKNOWN; 23239 } 23240 23241 @Override 23242 public boolean canRequestPackageInstalls(String packageName, int userId) { 23243 int callingUid = Binder.getCallingUid(); 23244 int uid = getPackageUid(packageName, 0, userId); 23245 if (callingUid != uid && callingUid != Process.ROOT_UID 23246 && callingUid != Process.SYSTEM_UID) { 23247 throw new SecurityException( 23248 "Caller uid " + callingUid + " does not own package " + packageName); 23249 } 23250 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23251 if (info == null) { 23252 return false; 23253 } 23254 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23255 throw new UnsupportedOperationException( 23256 "Operation only supported on apps targeting Android O or higher"); 23257 } 23258 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23259 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23260 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23261 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23262 } 23263 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23264 return false; 23265 } 23266 if (mExternalSourcesPolicy != null) { 23267 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23268 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23269 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23270 } 23271 } 23272 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23273 } 23274} 23275