PackageManagerService.java revision 433d68713f76a4fe0c4616d775ae90c4133105b1
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.database.ContentObserver; 177import android.graphics.Bitmap; 178import android.hardware.display.DisplayManager; 179import android.net.Uri; 180import android.os.Binder; 181import android.os.Build; 182import android.os.Bundle; 183import android.os.Debug; 184import android.os.Environment; 185import android.os.Environment.UserEnvironment; 186import android.os.FileUtils; 187import android.os.Handler; 188import android.os.IBinder; 189import android.os.Looper; 190import android.os.Message; 191import android.os.Parcel; 192import android.os.ParcelFileDescriptor; 193import android.os.PatternMatcher; 194import android.os.Process; 195import android.os.RemoteCallbackList; 196import android.os.RemoteException; 197import android.os.ResultReceiver; 198import android.os.SELinux; 199import android.os.ServiceManager; 200import android.os.ShellCallback; 201import android.os.SystemClock; 202import android.os.SystemProperties; 203import android.os.Trace; 204import android.os.UserHandle; 205import android.os.UserManager; 206import android.os.UserManagerInternal; 207import android.os.storage.IStorageManager; 208import android.os.storage.StorageEventListener; 209import android.os.storage.StorageManager; 210import android.os.storage.StorageManagerInternal; 211import android.os.storage.VolumeInfo; 212import android.os.storage.VolumeRecord; 213import android.provider.Settings.Global; 214import android.provider.Settings.Secure; 215import android.security.KeyStore; 216import android.security.SystemKeyStore; 217import android.service.pm.PackageServiceDumpProto; 218import android.system.ErrnoException; 219import android.system.Os; 220import android.text.TextUtils; 221import android.text.format.DateUtils; 222import android.util.ArrayMap; 223import android.util.ArraySet; 224import android.util.Base64; 225import android.util.DisplayMetrics; 226import android.util.EventLog; 227import android.util.ExceptionUtils; 228import android.util.Log; 229import android.util.LogPrinter; 230import android.util.MathUtils; 231import android.util.PackageUtils; 232import android.util.Pair; 233import android.util.PrintStreamPrinter; 234import android.util.Slog; 235import android.util.SparseArray; 236import android.util.SparseBooleanArray; 237import android.util.SparseIntArray; 238import android.util.Xml; 239import android.util.jar.StrictJarFile; 240import android.util.proto.ProtoOutputStream; 241import android.view.Display; 242 243import com.android.internal.R; 244import com.android.internal.annotations.GuardedBy; 245import com.android.internal.app.IMediaContainerService; 246import com.android.internal.app.ResolverActivity; 247import com.android.internal.content.NativeLibraryHelper; 248import com.android.internal.content.PackageHelper; 249import com.android.internal.logging.MetricsLogger; 250import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 251import com.android.internal.os.IParcelFileDescriptorFactory; 252import com.android.internal.os.RoSystemProperties; 253import com.android.internal.os.SomeArgs; 254import com.android.internal.os.Zygote; 255import com.android.internal.telephony.CarrierAppUtils; 256import com.android.internal.util.ArrayUtils; 257import com.android.internal.util.ConcurrentUtils; 258import com.android.internal.util.DumpUtils; 259import com.android.internal.util.FastPrintWriter; 260import com.android.internal.util.FastXmlSerializer; 261import com.android.internal.util.IndentingPrintWriter; 262import com.android.internal.util.Preconditions; 263import com.android.internal.util.XmlUtils; 264import com.android.server.AttributeCache; 265import com.android.server.DeviceIdleController; 266import com.android.server.EventLogTags; 267import com.android.server.FgThread; 268import com.android.server.IntentResolver; 269import com.android.server.LocalServices; 270import com.android.server.LockGuard; 271import com.android.server.ServiceThread; 272import com.android.server.SystemConfig; 273import com.android.server.SystemServerInitThreadPool; 274import com.android.server.Watchdog; 275import com.android.server.net.NetworkPolicyManagerInternal; 276import com.android.server.pm.BackgroundDexOptService; 277import com.android.server.pm.Installer.InstallerException; 278import com.android.server.pm.PermissionsState.PermissionState; 279import com.android.server.pm.Settings.DatabaseVersion; 280import com.android.server.pm.Settings.VersionInfo; 281import com.android.server.pm.dex.DexManager; 282import com.android.server.storage.DeviceStorageMonitorInternal; 283 284import dalvik.system.CloseGuard; 285import dalvik.system.DexFile; 286import dalvik.system.VMRuntime; 287 288import libcore.io.IoUtils; 289import libcore.util.EmptyArray; 290 291import org.xmlpull.v1.XmlPullParser; 292import org.xmlpull.v1.XmlPullParserException; 293import org.xmlpull.v1.XmlSerializer; 294 295import java.io.BufferedOutputStream; 296import java.io.BufferedReader; 297import java.io.ByteArrayInputStream; 298import java.io.ByteArrayOutputStream; 299import java.io.File; 300import java.io.FileDescriptor; 301import java.io.FileInputStream; 302import java.io.FileNotFoundException; 303import java.io.FileOutputStream; 304import java.io.FileReader; 305import java.io.FilenameFilter; 306import java.io.IOException; 307import java.io.PrintWriter; 308import java.nio.charset.StandardCharsets; 309import java.security.DigestInputStream; 310import java.security.MessageDigest; 311import java.security.NoSuchAlgorithmException; 312import java.security.PublicKey; 313import java.security.SecureRandom; 314import java.security.cert.Certificate; 315import java.security.cert.CertificateEncodingException; 316import java.security.cert.CertificateException; 317import java.text.SimpleDateFormat; 318import java.util.ArrayList; 319import java.util.Arrays; 320import java.util.Collection; 321import java.util.Collections; 322import java.util.Comparator; 323import java.util.Date; 324import java.util.HashMap; 325import java.util.HashSet; 326import java.util.Iterator; 327import java.util.List; 328import java.util.Map; 329import java.util.Objects; 330import java.util.Set; 331import java.util.concurrent.CountDownLatch; 332import java.util.concurrent.Future; 333import java.util.concurrent.TimeUnit; 334import java.util.concurrent.atomic.AtomicBoolean; 335import java.util.concurrent.atomic.AtomicInteger; 336 337/** 338 * Keep track of all those APKs everywhere. 339 * <p> 340 * Internally there are two important locks: 341 * <ul> 342 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 343 * and other related state. It is a fine-grained lock that should only be held 344 * momentarily, as it's one of the most contended locks in the system. 345 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 346 * operations typically involve heavy lifting of application data on disk. Since 347 * {@code installd} is single-threaded, and it's operations can often be slow, 348 * this lock should never be acquired while already holding {@link #mPackages}. 349 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 350 * holding {@link #mInstallLock}. 351 * </ul> 352 * Many internal methods rely on the caller to hold the appropriate locks, and 353 * this contract is expressed through method name suffixes: 354 * <ul> 355 * <li>fooLI(): the caller must hold {@link #mInstallLock} 356 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 357 * being modified must be frozen 358 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 359 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 360 * </ul> 361 * <p> 362 * Because this class is very central to the platform's security; please run all 363 * CTS and unit tests whenever making modifications: 364 * 365 * <pre> 366 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 367 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 368 * </pre> 369 */ 370public class PackageManagerService extends IPackageManager.Stub { 371 static final String TAG = "PackageManager"; 372 static final boolean DEBUG_SETTINGS = false; 373 static final boolean DEBUG_PREFERRED = false; 374 static final boolean DEBUG_UPGRADE = false; 375 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 376 private static final boolean DEBUG_BACKUP = false; 377 private static final boolean DEBUG_INSTALL = false; 378 private static final boolean DEBUG_REMOVE = false; 379 private static final boolean DEBUG_BROADCASTS = false; 380 private static final boolean DEBUG_SHOW_INFO = false; 381 private static final boolean DEBUG_PACKAGE_INFO = false; 382 private static final boolean DEBUG_INTENT_MATCHING = false; 383 private static final boolean DEBUG_PACKAGE_SCANNING = false; 384 private static final boolean DEBUG_VERIFY = false; 385 private static final boolean DEBUG_FILTERS = false; 386 387 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 388 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 389 // user, but by default initialize to this. 390 public static final boolean DEBUG_DEXOPT = false; 391 392 private static final boolean DEBUG_ABI_SELECTION = false; 393 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 394 private static final boolean DEBUG_TRIAGED_MISSING = false; 395 private static final boolean DEBUG_APP_DATA = false; 396 397 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 398 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 399 400 private static final boolean HIDE_EPHEMERAL_APIS = false; 401 402 private static final boolean ENABLE_FREE_CACHE_V2 = 403 SystemProperties.getBoolean("fw.free_cache_v2", true); 404 405 private static final int RADIO_UID = Process.PHONE_UID; 406 private static final int LOG_UID = Process.LOG_UID; 407 private static final int NFC_UID = Process.NFC_UID; 408 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 409 private static final int SHELL_UID = Process.SHELL_UID; 410 411 // Cap the size of permission trees that 3rd party apps can define 412 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 413 414 // Suffix used during package installation when copying/moving 415 // package apks to install directory. 416 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 417 418 static final int SCAN_NO_DEX = 1<<1; 419 static final int SCAN_FORCE_DEX = 1<<2; 420 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 421 static final int SCAN_NEW_INSTALL = 1<<4; 422 static final int SCAN_UPDATE_TIME = 1<<5; 423 static final int SCAN_BOOTING = 1<<6; 424 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 425 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 426 static final int SCAN_REPLACING = 1<<9; 427 static final int SCAN_REQUIRE_KNOWN = 1<<10; 428 static final int SCAN_MOVE = 1<<11; 429 static final int SCAN_INITIAL = 1<<12; 430 static final int SCAN_CHECK_ONLY = 1<<13; 431 static final int SCAN_DONT_KILL_APP = 1<<14; 432 static final int SCAN_IGNORE_FROZEN = 1<<15; 433 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<16; 434 static final int SCAN_AS_INSTANT_APP = 1<<17; 435 static final int SCAN_AS_FULL_APP = 1<<18; 436 /** Should not be with the scan flags */ 437 static final int FLAGS_REMOVE_CHATTY = 1<<31; 438 439 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 440 441 private static final int[] EMPTY_INT_ARRAY = new int[0]; 442 443 /** 444 * Timeout (in milliseconds) after which the watchdog should declare that 445 * our handler thread is wedged. The usual default for such things is one 446 * minute but we sometimes do very lengthy I/O operations on this thread, 447 * such as installing multi-gigabyte applications, so ours needs to be longer. 448 */ 449 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 450 451 /** 452 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 453 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 454 * settings entry if available, otherwise we use the hardcoded default. If it's been 455 * more than this long since the last fstrim, we force one during the boot sequence. 456 * 457 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 458 * one gets run at the next available charging+idle time. This final mandatory 459 * no-fstrim check kicks in only of the other scheduling criteria is never met. 460 */ 461 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 462 463 /** 464 * Whether verification is enabled by default. 465 */ 466 private static final boolean DEFAULT_VERIFY_ENABLE = true; 467 468 /** 469 * The default maximum time to wait for the verification agent to return in 470 * milliseconds. 471 */ 472 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 473 474 /** 475 * The default response for package verification timeout. 476 * 477 * This can be either PackageManager.VERIFICATION_ALLOW or 478 * PackageManager.VERIFICATION_REJECT. 479 */ 480 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 481 482 static final String PLATFORM_PACKAGE_NAME = "android"; 483 484 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 485 486 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 487 DEFAULT_CONTAINER_PACKAGE, 488 "com.android.defcontainer.DefaultContainerService"); 489 490 private static final String KILL_APP_REASON_GIDS_CHANGED = 491 "permission grant or revoke changed gids"; 492 493 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 494 "permissions revoked"; 495 496 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 497 498 private static final String PACKAGE_SCHEME = "package"; 499 500 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 501 502 /** Permission grant: not grant the permission. */ 503 private static final int GRANT_DENIED = 1; 504 505 /** Permission grant: grant the permission as an install permission. */ 506 private static final int GRANT_INSTALL = 2; 507 508 /** Permission grant: grant the permission as a runtime one. */ 509 private static final int GRANT_RUNTIME = 3; 510 511 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 512 private static final int GRANT_UPGRADE = 4; 513 514 /** Canonical intent used to identify what counts as a "web browser" app */ 515 private static final Intent sBrowserIntent; 516 static { 517 sBrowserIntent = new Intent(); 518 sBrowserIntent.setAction(Intent.ACTION_VIEW); 519 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 520 sBrowserIntent.setData(Uri.parse("http:")); 521 } 522 523 /** 524 * The set of all protected actions [i.e. those actions for which a high priority 525 * intent filter is disallowed]. 526 */ 527 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 528 static { 529 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 530 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 531 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 532 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 533 } 534 535 // Compilation reasons. 536 public static final int REASON_FIRST_BOOT = 0; 537 public static final int REASON_BOOT = 1; 538 public static final int REASON_INSTALL = 2; 539 public static final int REASON_BACKGROUND_DEXOPT = 3; 540 public static final int REASON_AB_OTA = 4; 541 public static final int REASON_FORCED_DEXOPT = 5; 542 543 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 544 545 /** All dangerous permission names in the same order as the events in MetricsEvent */ 546 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 547 Manifest.permission.READ_CALENDAR, 548 Manifest.permission.WRITE_CALENDAR, 549 Manifest.permission.CAMERA, 550 Manifest.permission.READ_CONTACTS, 551 Manifest.permission.WRITE_CONTACTS, 552 Manifest.permission.GET_ACCOUNTS, 553 Manifest.permission.ACCESS_FINE_LOCATION, 554 Manifest.permission.ACCESS_COARSE_LOCATION, 555 Manifest.permission.RECORD_AUDIO, 556 Manifest.permission.READ_PHONE_STATE, 557 Manifest.permission.CALL_PHONE, 558 Manifest.permission.READ_CALL_LOG, 559 Manifest.permission.WRITE_CALL_LOG, 560 Manifest.permission.ADD_VOICEMAIL, 561 Manifest.permission.USE_SIP, 562 Manifest.permission.PROCESS_OUTGOING_CALLS, 563 Manifest.permission.READ_CELL_BROADCASTS, 564 Manifest.permission.BODY_SENSORS, 565 Manifest.permission.SEND_SMS, 566 Manifest.permission.RECEIVE_SMS, 567 Manifest.permission.READ_SMS, 568 Manifest.permission.RECEIVE_WAP_PUSH, 569 Manifest.permission.RECEIVE_MMS, 570 Manifest.permission.READ_EXTERNAL_STORAGE, 571 Manifest.permission.WRITE_EXTERNAL_STORAGE, 572 Manifest.permission.READ_PHONE_NUMBERS, 573 Manifest.permission.ANSWER_PHONE_CALLS); 574 575 576 /** 577 * Version number for the package parser cache. Increment this whenever the format or 578 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 579 */ 580 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 581 582 /** 583 * Whether the package parser cache is enabled. 584 */ 585 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 586 587 final ServiceThread mHandlerThread; 588 589 final PackageHandler mHandler; 590 591 private final ProcessLoggingHandler mProcessLoggingHandler; 592 593 /** 594 * Messages for {@link #mHandler} that need to wait for system ready before 595 * being dispatched. 596 */ 597 private ArrayList<Message> mPostSystemReadyMessages; 598 599 final int mSdkVersion = Build.VERSION.SDK_INT; 600 601 final Context mContext; 602 final boolean mFactoryTest; 603 final boolean mOnlyCore; 604 final DisplayMetrics mMetrics; 605 final int mDefParseFlags; 606 final String[] mSeparateProcesses; 607 final boolean mIsUpgrade; 608 final boolean mIsPreNUpgrade; 609 final boolean mIsPreNMR1Upgrade; 610 611 // Have we told the Activity Manager to whitelist the default container service by uid yet? 612 @GuardedBy("mPackages") 613 boolean mDefaultContainerWhitelisted = false; 614 615 @GuardedBy("mPackages") 616 private boolean mDexOptDialogShown; 617 618 /** The location for ASEC container files on internal storage. */ 619 final String mAsecInternalPath; 620 621 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 622 // LOCK HELD. Can be called with mInstallLock held. 623 @GuardedBy("mInstallLock") 624 final Installer mInstaller; 625 626 /** Directory where installed third-party apps stored */ 627 final File mAppInstallDir; 628 629 /** 630 * Directory to which applications installed internally have their 631 * 32 bit native libraries copied. 632 */ 633 private File mAppLib32InstallDir; 634 635 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 636 // apps. 637 final File mDrmAppPrivateInstallDir; 638 639 // ---------------------------------------------------------------- 640 641 // Lock for state used when installing and doing other long running 642 // operations. Methods that must be called with this lock held have 643 // the suffix "LI". 644 final Object mInstallLock = new Object(); 645 646 // ---------------------------------------------------------------- 647 648 // Keys are String (package name), values are Package. This also serves 649 // as the lock for the global state. Methods that must be called with 650 // this lock held have the prefix "LP". 651 @GuardedBy("mPackages") 652 final ArrayMap<String, PackageParser.Package> mPackages = 653 new ArrayMap<String, PackageParser.Package>(); 654 655 final ArrayMap<String, Set<String>> mKnownCodebase = 656 new ArrayMap<String, Set<String>>(); 657 658 // Keys are isolated uids and values are the uid of the application 659 // that created the isolated proccess. 660 @GuardedBy("mPackages") 661 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 662 663 // List of APK paths to load for each user and package. This data is never 664 // persisted by the package manager. Instead, the overlay manager will 665 // ensure the data is up-to-date in runtime. 666 @GuardedBy("mPackages") 667 final SparseArray<ArrayMap<String, ArrayList<String>>> mEnabledOverlayPaths = 668 new SparseArray<ArrayMap<String, ArrayList<String>>>(); 669 670 /** 671 * Tracks new system packages [received in an OTA] that we expect to 672 * find updated user-installed versions. Keys are package name, values 673 * are package location. 674 */ 675 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 676 /** 677 * Tracks high priority intent filters for protected actions. During boot, certain 678 * filter actions are protected and should never be allowed to have a high priority 679 * intent filter for them. However, there is one, and only one exception -- the 680 * setup wizard. It must be able to define a high priority intent filter for these 681 * actions to ensure there are no escapes from the wizard. We need to delay processing 682 * of these during boot as we need to look at all of the system packages in order 683 * to know which component is the setup wizard. 684 */ 685 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 686 /** 687 * Whether or not processing protected filters should be deferred. 688 */ 689 private boolean mDeferProtectedFilters = true; 690 691 /** 692 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 693 */ 694 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 695 /** 696 * Whether or not system app permissions should be promoted from install to runtime. 697 */ 698 boolean mPromoteSystemApps; 699 700 @GuardedBy("mPackages") 701 final Settings mSettings; 702 703 /** 704 * Set of package names that are currently "frozen", which means active 705 * surgery is being done on the code/data for that package. The platform 706 * will refuse to launch frozen packages to avoid race conditions. 707 * 708 * @see PackageFreezer 709 */ 710 @GuardedBy("mPackages") 711 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 712 713 final ProtectedPackages mProtectedPackages; 714 715 boolean mFirstBoot; 716 717 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 718 719 // System configuration read by SystemConfig. 720 final int[] mGlobalGids; 721 final SparseArray<ArraySet<String>> mSystemPermissions; 722 @GuardedBy("mAvailableFeatures") 723 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 724 725 // If mac_permissions.xml was found for seinfo labeling. 726 boolean mFoundPolicyFile; 727 728 private final InstantAppRegistry mInstantAppRegistry; 729 730 @GuardedBy("mPackages") 731 int mChangedPackagesSequenceNumber; 732 /** 733 * List of changed [installed, removed or updated] packages. 734 * mapping from user id -> sequence number -> package name 735 */ 736 @GuardedBy("mPackages") 737 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 738 /** 739 * The sequence number of the last change to a package. 740 * mapping from user id -> package name -> sequence number 741 */ 742 @GuardedBy("mPackages") 743 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 744 745 final PackageParser.Callback mPackageParserCallback = new PackageParser.Callback() { 746 @Override public boolean hasFeature(String feature) { 747 return PackageManagerService.this.hasSystemFeature(feature, 0); 748 } 749 }; 750 751 public static final class SharedLibraryEntry { 752 public final String path; 753 public final String apk; 754 public final SharedLibraryInfo info; 755 756 SharedLibraryEntry(String _path, String _apk, String name, int version, int type, 757 String declaringPackageName, int declaringPackageVersionCode) { 758 path = _path; 759 apk = _apk; 760 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 761 declaringPackageName, declaringPackageVersionCode), null); 762 } 763 } 764 765 // Currently known shared libraries. 766 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 767 final ArrayMap<String, SparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 768 new ArrayMap<>(); 769 770 // All available activities, for your resolving pleasure. 771 final ActivityIntentResolver mActivities = 772 new ActivityIntentResolver(); 773 774 // All available receivers, for your resolving pleasure. 775 final ActivityIntentResolver mReceivers = 776 new ActivityIntentResolver(); 777 778 // All available services, for your resolving pleasure. 779 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 780 781 // All available providers, for your resolving pleasure. 782 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 783 784 // Mapping from provider base names (first directory in content URI codePath) 785 // to the provider information. 786 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 787 new ArrayMap<String, PackageParser.Provider>(); 788 789 // Mapping from instrumentation class names to info about them. 790 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 791 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 792 793 // Mapping from permission names to info about them. 794 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 795 new ArrayMap<String, PackageParser.PermissionGroup>(); 796 797 // Packages whose data we have transfered into another package, thus 798 // should no longer exist. 799 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 800 801 // Broadcast actions that are only available to the system. 802 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 803 804 /** List of packages waiting for verification. */ 805 final SparseArray<PackageVerificationState> mPendingVerification 806 = new SparseArray<PackageVerificationState>(); 807 808 /** Set of packages associated with each app op permission. */ 809 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 810 811 final PackageInstallerService mInstallerService; 812 813 private final PackageDexOptimizer mPackageDexOptimizer; 814 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 815 // is used by other apps). 816 private final DexManager mDexManager; 817 818 private AtomicInteger mNextMoveId = new AtomicInteger(); 819 private final MoveCallbacks mMoveCallbacks; 820 821 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 822 823 // Cache of users who need badging. 824 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 825 826 /** Token for keys in mPendingVerification. */ 827 private int mPendingVerificationToken = 0; 828 829 volatile boolean mSystemReady; 830 volatile boolean mSafeMode; 831 volatile boolean mHasSystemUidErrors; 832 private volatile boolean mEphemeralAppsDisabled; 833 834 ApplicationInfo mAndroidApplication; 835 final ActivityInfo mResolveActivity = new ActivityInfo(); 836 final ResolveInfo mResolveInfo = new ResolveInfo(); 837 ComponentName mResolveComponentName; 838 PackageParser.Package mPlatformPackage; 839 ComponentName mCustomResolverComponentName; 840 841 boolean mResolverReplaced = false; 842 843 private final @Nullable ComponentName mIntentFilterVerifierComponent; 844 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 845 846 private int mIntentFilterVerificationToken = 0; 847 848 /** The service connection to the ephemeral resolver */ 849 final EphemeralResolverConnection mInstantAppResolverConnection; 850 /** Component used to show resolver settings for Instant Apps */ 851 final ComponentName mInstantAppResolverSettingsComponent; 852 853 /** Activity used to install instant applications */ 854 ActivityInfo mInstantAppInstallerActivity; 855 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 856 857 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 858 = new SparseArray<IntentFilterVerificationState>(); 859 860 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 861 862 // List of packages names to keep cached, even if they are uninstalled for all users 863 private List<String> mKeepUninstalledPackages; 864 865 private UserManagerInternal mUserManagerInternal; 866 867 private DeviceIdleController.LocalService mDeviceIdleController; 868 869 private File mCacheDir; 870 871 private ArraySet<String> mPrivappPermissionsViolations; 872 873 private Future<?> mPrepareAppDataFuture; 874 875 private static class IFVerificationParams { 876 PackageParser.Package pkg; 877 boolean replacing; 878 int userId; 879 int verifierUid; 880 881 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 882 int _userId, int _verifierUid) { 883 pkg = _pkg; 884 replacing = _replacing; 885 userId = _userId; 886 replacing = _replacing; 887 verifierUid = _verifierUid; 888 } 889 } 890 891 private interface IntentFilterVerifier<T extends IntentFilter> { 892 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 893 T filter, String packageName); 894 void startVerifications(int userId); 895 void receiveVerificationResponse(int verificationId); 896 } 897 898 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 899 private Context mContext; 900 private ComponentName mIntentFilterVerifierComponent; 901 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 902 903 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 904 mContext = context; 905 mIntentFilterVerifierComponent = verifierComponent; 906 } 907 908 private String getDefaultScheme() { 909 return IntentFilter.SCHEME_HTTPS; 910 } 911 912 @Override 913 public void startVerifications(int userId) { 914 // Launch verifications requests 915 int count = mCurrentIntentFilterVerifications.size(); 916 for (int n=0; n<count; n++) { 917 int verificationId = mCurrentIntentFilterVerifications.get(n); 918 final IntentFilterVerificationState ivs = 919 mIntentFilterVerificationStates.get(verificationId); 920 921 String packageName = ivs.getPackageName(); 922 923 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 924 final int filterCount = filters.size(); 925 ArraySet<String> domainsSet = new ArraySet<>(); 926 for (int m=0; m<filterCount; m++) { 927 PackageParser.ActivityIntentInfo filter = filters.get(m); 928 domainsSet.addAll(filter.getHostsList()); 929 } 930 synchronized (mPackages) { 931 if (mSettings.createIntentFilterVerificationIfNeededLPw( 932 packageName, domainsSet) != null) { 933 scheduleWriteSettingsLocked(); 934 } 935 } 936 sendVerificationRequest(userId, verificationId, ivs); 937 } 938 mCurrentIntentFilterVerifications.clear(); 939 } 940 941 private void sendVerificationRequest(int userId, int verificationId, 942 IntentFilterVerificationState ivs) { 943 944 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 945 verificationIntent.putExtra( 946 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 947 verificationId); 948 verificationIntent.putExtra( 949 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 950 getDefaultScheme()); 951 verificationIntent.putExtra( 952 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 953 ivs.getHostsString()); 954 verificationIntent.putExtra( 955 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 956 ivs.getPackageName()); 957 verificationIntent.setComponent(mIntentFilterVerifierComponent); 958 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 959 960 UserHandle user = new UserHandle(userId); 961 mContext.sendBroadcastAsUser(verificationIntent, user); 962 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 963 "Sending IntentFilter verification broadcast"); 964 } 965 966 public void receiveVerificationResponse(int verificationId) { 967 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 968 969 final boolean verified = ivs.isVerified(); 970 971 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 972 final int count = filters.size(); 973 if (DEBUG_DOMAIN_VERIFICATION) { 974 Slog.i(TAG, "Received verification response " + verificationId 975 + " for " + count + " filters, verified=" + verified); 976 } 977 for (int n=0; n<count; n++) { 978 PackageParser.ActivityIntentInfo filter = filters.get(n); 979 filter.setVerified(verified); 980 981 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 982 + " verified with result:" + verified + " and hosts:" 983 + ivs.getHostsString()); 984 } 985 986 mIntentFilterVerificationStates.remove(verificationId); 987 988 final String packageName = ivs.getPackageName(); 989 IntentFilterVerificationInfo ivi = null; 990 991 synchronized (mPackages) { 992 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 993 } 994 if (ivi == null) { 995 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 996 + verificationId + " packageName:" + packageName); 997 return; 998 } 999 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1000 "Updating IntentFilterVerificationInfo for package " + packageName 1001 +" verificationId:" + verificationId); 1002 1003 synchronized (mPackages) { 1004 if (verified) { 1005 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1006 } else { 1007 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1008 } 1009 scheduleWriteSettingsLocked(); 1010 1011 final int userId = ivs.getUserId(); 1012 if (userId != UserHandle.USER_ALL) { 1013 final int userStatus = 1014 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1015 1016 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1017 boolean needUpdate = false; 1018 1019 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1020 // already been set by the User thru the Disambiguation dialog 1021 switch (userStatus) { 1022 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1023 if (verified) { 1024 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1025 } else { 1026 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1027 } 1028 needUpdate = true; 1029 break; 1030 1031 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1032 if (verified) { 1033 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1034 needUpdate = true; 1035 } 1036 break; 1037 1038 default: 1039 // Nothing to do 1040 } 1041 1042 if (needUpdate) { 1043 mSettings.updateIntentFilterVerificationStatusLPw( 1044 packageName, updatedStatus, userId); 1045 scheduleWritePackageRestrictionsLocked(userId); 1046 } 1047 } 1048 } 1049 } 1050 1051 @Override 1052 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1053 ActivityIntentInfo filter, String packageName) { 1054 if (!hasValidDomains(filter)) { 1055 return false; 1056 } 1057 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1058 if (ivs == null) { 1059 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1060 packageName); 1061 } 1062 if (DEBUG_DOMAIN_VERIFICATION) { 1063 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1064 } 1065 ivs.addFilter(filter); 1066 return true; 1067 } 1068 1069 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1070 int userId, int verificationId, String packageName) { 1071 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1072 verifierUid, userId, packageName); 1073 ivs.setPendingState(); 1074 synchronized (mPackages) { 1075 mIntentFilterVerificationStates.append(verificationId, ivs); 1076 mCurrentIntentFilterVerifications.add(verificationId); 1077 } 1078 return ivs; 1079 } 1080 } 1081 1082 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1083 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1084 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1085 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1086 } 1087 1088 // Set of pending broadcasts for aggregating enable/disable of components. 1089 static class PendingPackageBroadcasts { 1090 // for each user id, a map of <package name -> components within that package> 1091 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1092 1093 public PendingPackageBroadcasts() { 1094 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1095 } 1096 1097 public ArrayList<String> get(int userId, String packageName) { 1098 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1099 return packages.get(packageName); 1100 } 1101 1102 public void put(int userId, String packageName, ArrayList<String> components) { 1103 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1104 packages.put(packageName, components); 1105 } 1106 1107 public void remove(int userId, String packageName) { 1108 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1109 if (packages != null) { 1110 packages.remove(packageName); 1111 } 1112 } 1113 1114 public void remove(int userId) { 1115 mUidMap.remove(userId); 1116 } 1117 1118 public int userIdCount() { 1119 return mUidMap.size(); 1120 } 1121 1122 public int userIdAt(int n) { 1123 return mUidMap.keyAt(n); 1124 } 1125 1126 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1127 return mUidMap.get(userId); 1128 } 1129 1130 public int size() { 1131 // total number of pending broadcast entries across all userIds 1132 int num = 0; 1133 for (int i = 0; i< mUidMap.size(); i++) { 1134 num += mUidMap.valueAt(i).size(); 1135 } 1136 return num; 1137 } 1138 1139 public void clear() { 1140 mUidMap.clear(); 1141 } 1142 1143 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1144 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1145 if (map == null) { 1146 map = new ArrayMap<String, ArrayList<String>>(); 1147 mUidMap.put(userId, map); 1148 } 1149 return map; 1150 } 1151 } 1152 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1153 1154 // Service Connection to remote media container service to copy 1155 // package uri's from external media onto secure containers 1156 // or internal storage. 1157 private IMediaContainerService mContainerService = null; 1158 1159 static final int SEND_PENDING_BROADCAST = 1; 1160 static final int MCS_BOUND = 3; 1161 static final int END_COPY = 4; 1162 static final int INIT_COPY = 5; 1163 static final int MCS_UNBIND = 6; 1164 static final int START_CLEANING_PACKAGE = 7; 1165 static final int FIND_INSTALL_LOC = 8; 1166 static final int POST_INSTALL = 9; 1167 static final int MCS_RECONNECT = 10; 1168 static final int MCS_GIVE_UP = 11; 1169 static final int UPDATED_MEDIA_STATUS = 12; 1170 static final int WRITE_SETTINGS = 13; 1171 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1172 static final int PACKAGE_VERIFIED = 15; 1173 static final int CHECK_PENDING_VERIFICATION = 16; 1174 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1175 static final int INTENT_FILTER_VERIFIED = 18; 1176 static final int WRITE_PACKAGE_LIST = 19; 1177 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1178 1179 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1180 1181 // Delay time in millisecs 1182 static final int BROADCAST_DELAY = 10 * 1000; 1183 1184 static UserManagerService sUserManager; 1185 1186 // Stores a list of users whose package restrictions file needs to be updated 1187 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1188 1189 final private DefaultContainerConnection mDefContainerConn = 1190 new DefaultContainerConnection(); 1191 class DefaultContainerConnection implements ServiceConnection { 1192 public void onServiceConnected(ComponentName name, IBinder service) { 1193 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1194 final IMediaContainerService imcs = IMediaContainerService.Stub 1195 .asInterface(Binder.allowBlocking(service)); 1196 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1197 } 1198 1199 public void onServiceDisconnected(ComponentName name) { 1200 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1201 } 1202 } 1203 1204 // Recordkeeping of restore-after-install operations that are currently in flight 1205 // between the Package Manager and the Backup Manager 1206 static class PostInstallData { 1207 public InstallArgs args; 1208 public PackageInstalledInfo res; 1209 1210 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1211 args = _a; 1212 res = _r; 1213 } 1214 } 1215 1216 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1217 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1218 1219 // XML tags for backup/restore of various bits of state 1220 private static final String TAG_PREFERRED_BACKUP = "pa"; 1221 private static final String TAG_DEFAULT_APPS = "da"; 1222 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1223 1224 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1225 private static final String TAG_ALL_GRANTS = "rt-grants"; 1226 private static final String TAG_GRANT = "grant"; 1227 private static final String ATTR_PACKAGE_NAME = "pkg"; 1228 1229 private static final String TAG_PERMISSION = "perm"; 1230 private static final String ATTR_PERMISSION_NAME = "name"; 1231 private static final String ATTR_IS_GRANTED = "g"; 1232 private static final String ATTR_USER_SET = "set"; 1233 private static final String ATTR_USER_FIXED = "fixed"; 1234 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1235 1236 // System/policy permission grants are not backed up 1237 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1238 FLAG_PERMISSION_POLICY_FIXED 1239 | FLAG_PERMISSION_SYSTEM_FIXED 1240 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1241 1242 // And we back up these user-adjusted states 1243 private static final int USER_RUNTIME_GRANT_MASK = 1244 FLAG_PERMISSION_USER_SET 1245 | FLAG_PERMISSION_USER_FIXED 1246 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1247 1248 final @Nullable String mRequiredVerifierPackage; 1249 final @NonNull String mRequiredInstallerPackage; 1250 final @NonNull String mRequiredUninstallerPackage; 1251 final @Nullable String mSetupWizardPackage; 1252 final @Nullable String mStorageManagerPackage; 1253 final @NonNull String mServicesSystemSharedLibraryPackageName; 1254 final @NonNull String mSharedSystemSharedLibraryPackageName; 1255 1256 final boolean mPermissionReviewRequired; 1257 1258 private final PackageUsage mPackageUsage = new PackageUsage(); 1259 private final CompilerStats mCompilerStats = new CompilerStats(); 1260 1261 class PackageHandler extends Handler { 1262 private boolean mBound = false; 1263 final ArrayList<HandlerParams> mPendingInstalls = 1264 new ArrayList<HandlerParams>(); 1265 1266 private boolean connectToService() { 1267 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1268 " DefaultContainerService"); 1269 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1272 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1274 mBound = true; 1275 return true; 1276 } 1277 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1278 return false; 1279 } 1280 1281 private void disconnectService() { 1282 mContainerService = null; 1283 mBound = false; 1284 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1285 mContext.unbindService(mDefContainerConn); 1286 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1287 } 1288 1289 PackageHandler(Looper looper) { 1290 super(looper); 1291 } 1292 1293 public void handleMessage(Message msg) { 1294 try { 1295 doHandleMessage(msg); 1296 } finally { 1297 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1298 } 1299 } 1300 1301 void doHandleMessage(Message msg) { 1302 switch (msg.what) { 1303 case INIT_COPY: { 1304 HandlerParams params = (HandlerParams) msg.obj; 1305 int idx = mPendingInstalls.size(); 1306 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1307 // If a bind was already initiated we dont really 1308 // need to do anything. The pending install 1309 // will be processed later on. 1310 if (!mBound) { 1311 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1312 System.identityHashCode(mHandler)); 1313 // If this is the only one pending we might 1314 // have to bind to the service again. 1315 if (!connectToService()) { 1316 Slog.e(TAG, "Failed to bind to media container service"); 1317 params.serviceError(); 1318 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1319 System.identityHashCode(mHandler)); 1320 if (params.traceMethod != null) { 1321 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1322 params.traceCookie); 1323 } 1324 return; 1325 } else { 1326 // Once we bind to the service, the first 1327 // pending request will be processed. 1328 mPendingInstalls.add(idx, params); 1329 } 1330 } else { 1331 mPendingInstalls.add(idx, params); 1332 // Already bound to the service. Just make 1333 // sure we trigger off processing the first request. 1334 if (idx == 0) { 1335 mHandler.sendEmptyMessage(MCS_BOUND); 1336 } 1337 } 1338 break; 1339 } 1340 case MCS_BOUND: { 1341 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1342 if (msg.obj != null) { 1343 mContainerService = (IMediaContainerService) msg.obj; 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1345 System.identityHashCode(mHandler)); 1346 } 1347 if (mContainerService == null) { 1348 if (!mBound) { 1349 // Something seriously wrong since we are not bound and we are not 1350 // waiting for connection. Bail out. 1351 Slog.e(TAG, "Cannot bind to media container service"); 1352 for (HandlerParams params : mPendingInstalls) { 1353 // Indicate service bind error 1354 params.serviceError(); 1355 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1356 System.identityHashCode(params)); 1357 if (params.traceMethod != null) { 1358 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1359 params.traceMethod, params.traceCookie); 1360 } 1361 return; 1362 } 1363 mPendingInstalls.clear(); 1364 } else { 1365 Slog.w(TAG, "Waiting to connect to media container service"); 1366 } 1367 } else if (mPendingInstalls.size() > 0) { 1368 HandlerParams params = mPendingInstalls.get(0); 1369 if (params != null) { 1370 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1371 System.identityHashCode(params)); 1372 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1373 if (params.startCopy()) { 1374 // We are done... look for more work or to 1375 // go idle. 1376 if (DEBUG_SD_INSTALL) Log.i(TAG, 1377 "Checking for more work or unbind..."); 1378 // Delete pending install 1379 if (mPendingInstalls.size() > 0) { 1380 mPendingInstalls.remove(0); 1381 } 1382 if (mPendingInstalls.size() == 0) { 1383 if (mBound) { 1384 if (DEBUG_SD_INSTALL) Log.i(TAG, 1385 "Posting delayed MCS_UNBIND"); 1386 removeMessages(MCS_UNBIND); 1387 Message ubmsg = obtainMessage(MCS_UNBIND); 1388 // Unbind after a little delay, to avoid 1389 // continual thrashing. 1390 sendMessageDelayed(ubmsg, 10000); 1391 } 1392 } else { 1393 // There are more pending requests in queue. 1394 // Just post MCS_BOUND message to trigger processing 1395 // of next pending install. 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, 1397 "Posting MCS_BOUND for next work"); 1398 mHandler.sendEmptyMessage(MCS_BOUND); 1399 } 1400 } 1401 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1402 } 1403 } else { 1404 // Should never happen ideally. 1405 Slog.w(TAG, "Empty queue"); 1406 } 1407 break; 1408 } 1409 case MCS_RECONNECT: { 1410 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1411 if (mPendingInstalls.size() > 0) { 1412 if (mBound) { 1413 disconnectService(); 1414 } 1415 if (!connectToService()) { 1416 Slog.e(TAG, "Failed to bind to media container service"); 1417 for (HandlerParams params : mPendingInstalls) { 1418 // Indicate service bind error 1419 params.serviceError(); 1420 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1421 System.identityHashCode(params)); 1422 } 1423 mPendingInstalls.clear(); 1424 } 1425 } 1426 break; 1427 } 1428 case MCS_UNBIND: { 1429 // If there is no actual work left, then time to unbind. 1430 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1431 1432 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1433 if (mBound) { 1434 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1435 1436 disconnectService(); 1437 } 1438 } else if (mPendingInstalls.size() > 0) { 1439 // There are more pending requests in queue. 1440 // Just post MCS_BOUND message to trigger processing 1441 // of next pending install. 1442 mHandler.sendEmptyMessage(MCS_BOUND); 1443 } 1444 1445 break; 1446 } 1447 case MCS_GIVE_UP: { 1448 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1449 HandlerParams params = mPendingInstalls.remove(0); 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1451 System.identityHashCode(params)); 1452 break; 1453 } 1454 case SEND_PENDING_BROADCAST: { 1455 String packages[]; 1456 ArrayList<String> components[]; 1457 int size = 0; 1458 int uids[]; 1459 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1460 synchronized (mPackages) { 1461 if (mPendingBroadcasts == null) { 1462 return; 1463 } 1464 size = mPendingBroadcasts.size(); 1465 if (size <= 0) { 1466 // Nothing to be done. Just return 1467 return; 1468 } 1469 packages = new String[size]; 1470 components = new ArrayList[size]; 1471 uids = new int[size]; 1472 int i = 0; // filling out the above arrays 1473 1474 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1475 int packageUserId = mPendingBroadcasts.userIdAt(n); 1476 Iterator<Map.Entry<String, ArrayList<String>>> it 1477 = mPendingBroadcasts.packagesForUserId(packageUserId) 1478 .entrySet().iterator(); 1479 while (it.hasNext() && i < size) { 1480 Map.Entry<String, ArrayList<String>> ent = it.next(); 1481 packages[i] = ent.getKey(); 1482 components[i] = ent.getValue(); 1483 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1484 uids[i] = (ps != null) 1485 ? UserHandle.getUid(packageUserId, ps.appId) 1486 : -1; 1487 i++; 1488 } 1489 } 1490 size = i; 1491 mPendingBroadcasts.clear(); 1492 } 1493 // Send broadcasts 1494 for (int i = 0; i < size; i++) { 1495 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1496 } 1497 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1498 break; 1499 } 1500 case START_CLEANING_PACKAGE: { 1501 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1502 final String packageName = (String)msg.obj; 1503 final int userId = msg.arg1; 1504 final boolean andCode = msg.arg2 != 0; 1505 synchronized (mPackages) { 1506 if (userId == UserHandle.USER_ALL) { 1507 int[] users = sUserManager.getUserIds(); 1508 for (int user : users) { 1509 mSettings.addPackageToCleanLPw( 1510 new PackageCleanItem(user, packageName, andCode)); 1511 } 1512 } else { 1513 mSettings.addPackageToCleanLPw( 1514 new PackageCleanItem(userId, packageName, andCode)); 1515 } 1516 } 1517 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1518 startCleaningPackages(); 1519 } break; 1520 case POST_INSTALL: { 1521 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1522 1523 PostInstallData data = mRunningInstalls.get(msg.arg1); 1524 final boolean didRestore = (msg.arg2 != 0); 1525 mRunningInstalls.delete(msg.arg1); 1526 1527 if (data != null) { 1528 InstallArgs args = data.args; 1529 PackageInstalledInfo parentRes = data.res; 1530 1531 final boolean grantPermissions = (args.installFlags 1532 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1533 final boolean killApp = (args.installFlags 1534 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1535 final String[] grantedPermissions = args.installGrantPermissions; 1536 1537 // Handle the parent package 1538 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1539 grantedPermissions, didRestore, args.installerPackageName, 1540 args.observer); 1541 1542 // Handle the child packages 1543 final int childCount = (parentRes.addedChildPackages != null) 1544 ? parentRes.addedChildPackages.size() : 0; 1545 for (int i = 0; i < childCount; i++) { 1546 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1547 handlePackagePostInstall(childRes, grantPermissions, killApp, 1548 grantedPermissions, false, args.installerPackageName, 1549 args.observer); 1550 } 1551 1552 // Log tracing if needed 1553 if (args.traceMethod != null) { 1554 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1555 args.traceCookie); 1556 } 1557 } else { 1558 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1559 } 1560 1561 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1562 } break; 1563 case UPDATED_MEDIA_STATUS: { 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1565 boolean reportStatus = msg.arg1 == 1; 1566 boolean doGc = msg.arg2 == 1; 1567 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1568 if (doGc) { 1569 // Force a gc to clear up stale containers. 1570 Runtime.getRuntime().gc(); 1571 } 1572 if (msg.obj != null) { 1573 @SuppressWarnings("unchecked") 1574 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1575 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1576 // Unload containers 1577 unloadAllContainers(args); 1578 } 1579 if (reportStatus) { 1580 try { 1581 if (DEBUG_SD_INSTALL) Log.i(TAG, 1582 "Invoking StorageManagerService call back"); 1583 PackageHelper.getStorageManager().finishMediaUpdate(); 1584 } catch (RemoteException e) { 1585 Log.e(TAG, "StorageManagerService not running?"); 1586 } 1587 } 1588 } break; 1589 case WRITE_SETTINGS: { 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1591 synchronized (mPackages) { 1592 removeMessages(WRITE_SETTINGS); 1593 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1594 mSettings.writeLPr(); 1595 mDirtyUsers.clear(); 1596 } 1597 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1598 } break; 1599 case WRITE_PACKAGE_RESTRICTIONS: { 1600 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1601 synchronized (mPackages) { 1602 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1603 for (int userId : mDirtyUsers) { 1604 mSettings.writePackageRestrictionsLPr(userId); 1605 } 1606 mDirtyUsers.clear(); 1607 } 1608 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1609 } break; 1610 case WRITE_PACKAGE_LIST: { 1611 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1612 synchronized (mPackages) { 1613 removeMessages(WRITE_PACKAGE_LIST); 1614 mSettings.writePackageListLPr(msg.arg1); 1615 } 1616 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1617 } break; 1618 case CHECK_PENDING_VERIFICATION: { 1619 final int verificationId = msg.arg1; 1620 final PackageVerificationState state = mPendingVerification.get(verificationId); 1621 1622 if ((state != null) && !state.timeoutExtended()) { 1623 final InstallArgs args = state.getInstallArgs(); 1624 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1625 1626 Slog.i(TAG, "Verification timed out for " + originUri); 1627 mPendingVerification.remove(verificationId); 1628 1629 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1630 1631 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1632 Slog.i(TAG, "Continuing with installation of " + originUri); 1633 state.setVerifierResponse(Binder.getCallingUid(), 1634 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1635 broadcastPackageVerified(verificationId, originUri, 1636 PackageManager.VERIFICATION_ALLOW, 1637 state.getInstallArgs().getUser()); 1638 try { 1639 ret = args.copyApk(mContainerService, true); 1640 } catch (RemoteException e) { 1641 Slog.e(TAG, "Could not contact the ContainerService"); 1642 } 1643 } else { 1644 broadcastPackageVerified(verificationId, originUri, 1645 PackageManager.VERIFICATION_REJECT, 1646 state.getInstallArgs().getUser()); 1647 } 1648 1649 Trace.asyncTraceEnd( 1650 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1651 1652 processPendingInstall(args, ret); 1653 mHandler.sendEmptyMessage(MCS_UNBIND); 1654 } 1655 break; 1656 } 1657 case PACKAGE_VERIFIED: { 1658 final int verificationId = msg.arg1; 1659 1660 final PackageVerificationState state = mPendingVerification.get(verificationId); 1661 if (state == null) { 1662 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1663 break; 1664 } 1665 1666 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1667 1668 state.setVerifierResponse(response.callerUid, response.code); 1669 1670 if (state.isVerificationComplete()) { 1671 mPendingVerification.remove(verificationId); 1672 1673 final InstallArgs args = state.getInstallArgs(); 1674 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1675 1676 int ret; 1677 if (state.isInstallAllowed()) { 1678 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1679 broadcastPackageVerified(verificationId, originUri, 1680 response.code, state.getInstallArgs().getUser()); 1681 try { 1682 ret = args.copyApk(mContainerService, true); 1683 } catch (RemoteException e) { 1684 Slog.e(TAG, "Could not contact the ContainerService"); 1685 } 1686 } else { 1687 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1688 } 1689 1690 Trace.asyncTraceEnd( 1691 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1692 1693 processPendingInstall(args, ret); 1694 mHandler.sendEmptyMessage(MCS_UNBIND); 1695 } 1696 1697 break; 1698 } 1699 case START_INTENT_FILTER_VERIFICATIONS: { 1700 IFVerificationParams params = (IFVerificationParams) msg.obj; 1701 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1702 params.replacing, params.pkg); 1703 break; 1704 } 1705 case INTENT_FILTER_VERIFIED: { 1706 final int verificationId = msg.arg1; 1707 1708 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1709 verificationId); 1710 if (state == null) { 1711 Slog.w(TAG, "Invalid IntentFilter verification token " 1712 + verificationId + " received"); 1713 break; 1714 } 1715 1716 final int userId = state.getUserId(); 1717 1718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1719 "Processing IntentFilter verification with token:" 1720 + verificationId + " and userId:" + userId); 1721 1722 final IntentFilterVerificationResponse response = 1723 (IntentFilterVerificationResponse) msg.obj; 1724 1725 state.setVerifierResponse(response.callerUid, response.code); 1726 1727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1728 "IntentFilter verification with token:" + verificationId 1729 + " and userId:" + userId 1730 + " is settings verifier response with response code:" 1731 + response.code); 1732 1733 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1735 + response.getFailedDomainsString()); 1736 } 1737 1738 if (state.isVerificationComplete()) { 1739 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1740 } else { 1741 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1742 "IntentFilter verification with token:" + verificationId 1743 + " was not said to be complete"); 1744 } 1745 1746 break; 1747 } 1748 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1749 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1750 mInstantAppResolverConnection, 1751 (InstantAppRequest) msg.obj, 1752 mInstantAppInstallerActivity, 1753 mHandler); 1754 } 1755 } 1756 } 1757 } 1758 1759 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1760 boolean killApp, String[] grantedPermissions, 1761 boolean launchedForRestore, String installerPackage, 1762 IPackageInstallObserver2 installObserver) { 1763 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1764 // Send the removed broadcasts 1765 if (res.removedInfo != null) { 1766 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1767 } 1768 1769 // Now that we successfully installed the package, grant runtime 1770 // permissions if requested before broadcasting the install. Also 1771 // for legacy apps in permission review mode we clear the permission 1772 // review flag which is used to emulate runtime permissions for 1773 // legacy apps. 1774 if (grantPermissions) { 1775 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1776 } 1777 1778 final boolean update = res.removedInfo != null 1779 && res.removedInfo.removedPackage != null; 1780 1781 // If this is the first time we have child packages for a disabled privileged 1782 // app that had no children, we grant requested runtime permissions to the new 1783 // children if the parent on the system image had them already granted. 1784 if (res.pkg.parentPackage != null) { 1785 synchronized (mPackages) { 1786 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1787 } 1788 } 1789 1790 synchronized (mPackages) { 1791 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1792 } 1793 1794 final String packageName = res.pkg.applicationInfo.packageName; 1795 1796 // Determine the set of users who are adding this package for 1797 // the first time vs. those who are seeing an update. 1798 int[] firstUsers = EMPTY_INT_ARRAY; 1799 int[] updateUsers = EMPTY_INT_ARRAY; 1800 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1801 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1802 for (int newUser : res.newUsers) { 1803 if (ps.getInstantApp(newUser)) { 1804 continue; 1805 } 1806 if (allNewUsers) { 1807 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1808 continue; 1809 } 1810 boolean isNew = true; 1811 for (int origUser : res.origUsers) { 1812 if (origUser == newUser) { 1813 isNew = false; 1814 break; 1815 } 1816 } 1817 if (isNew) { 1818 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1819 } else { 1820 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1821 } 1822 } 1823 1824 // Send installed broadcasts if the package is not a static shared lib. 1825 if (res.pkg.staticSharedLibName == null) { 1826 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1827 1828 // Send added for users that see the package for the first time 1829 // sendPackageAddedForNewUsers also deals with system apps 1830 int appId = UserHandle.getAppId(res.uid); 1831 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1832 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1833 1834 // Send added for users that don't see the package for the first time 1835 Bundle extras = new Bundle(1); 1836 extras.putInt(Intent.EXTRA_UID, res.uid); 1837 if (update) { 1838 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1839 } 1840 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1841 extras, 0 /*flags*/, null /*targetPackage*/, 1842 null /*finishedReceiver*/, updateUsers); 1843 1844 // Send replaced for users that don't see the package for the first time 1845 if (update) { 1846 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1847 packageName, extras, 0 /*flags*/, 1848 null /*targetPackage*/, null /*finishedReceiver*/, 1849 updateUsers); 1850 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1851 null /*package*/, null /*extras*/, 0 /*flags*/, 1852 packageName /*targetPackage*/, 1853 null /*finishedReceiver*/, updateUsers); 1854 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1855 // First-install and we did a restore, so we're responsible for the 1856 // first-launch broadcast. 1857 if (DEBUG_BACKUP) { 1858 Slog.i(TAG, "Post-restore of " + packageName 1859 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1860 } 1861 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1862 } 1863 1864 // Send broadcast package appeared if forward locked/external for all users 1865 // treat asec-hosted packages like removable media on upgrade 1866 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1867 if (DEBUG_INSTALL) { 1868 Slog.i(TAG, "upgrading pkg " + res.pkg 1869 + " is ASEC-hosted -> AVAILABLE"); 1870 } 1871 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1872 ArrayList<String> pkgList = new ArrayList<>(1); 1873 pkgList.add(packageName); 1874 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1875 } 1876 } 1877 1878 // Work that needs to happen on first install within each user 1879 if (firstUsers != null && firstUsers.length > 0) { 1880 synchronized (mPackages) { 1881 for (int userId : firstUsers) { 1882 // If this app is a browser and it's newly-installed for some 1883 // users, clear any default-browser state in those users. The 1884 // app's nature doesn't depend on the user, so we can just check 1885 // its browser nature in any user and generalize. 1886 if (packageIsBrowser(packageName, userId)) { 1887 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1888 } 1889 1890 // We may also need to apply pending (restored) runtime 1891 // permission grants within these users. 1892 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1893 } 1894 } 1895 } 1896 1897 // Log current value of "unknown sources" setting 1898 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1899 getUnknownSourcesSettings()); 1900 1901 // Force a gc to clear up things 1902 Runtime.getRuntime().gc(); 1903 1904 // Remove the replaced package's older resources safely now 1905 // We delete after a gc for applications on sdcard. 1906 if (res.removedInfo != null && res.removedInfo.args != null) { 1907 synchronized (mInstallLock) { 1908 res.removedInfo.args.doPostDeleteLI(true); 1909 } 1910 } 1911 1912 // Notify DexManager that the package was installed for new users. 1913 // The updated users should already be indexed and the package code paths 1914 // should not change. 1915 // Don't notify the manager for ephemeral apps as they are not expected to 1916 // survive long enough to benefit of background optimizations. 1917 for (int userId : firstUsers) { 1918 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 1919 mDexManager.notifyPackageInstalled(info, userId); 1920 } 1921 } 1922 1923 // If someone is watching installs - notify them 1924 if (installObserver != null) { 1925 try { 1926 Bundle extras = extrasForInstallResult(res); 1927 installObserver.onPackageInstalled(res.name, res.returnCode, 1928 res.returnMsg, extras); 1929 } catch (RemoteException e) { 1930 Slog.i(TAG, "Observer no longer exists."); 1931 } 1932 } 1933 } 1934 1935 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1936 PackageParser.Package pkg) { 1937 if (pkg.parentPackage == null) { 1938 return; 1939 } 1940 if (pkg.requestedPermissions == null) { 1941 return; 1942 } 1943 final PackageSetting disabledSysParentPs = mSettings 1944 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1945 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1946 || !disabledSysParentPs.isPrivileged() 1947 || (disabledSysParentPs.childPackageNames != null 1948 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1949 return; 1950 } 1951 final int[] allUserIds = sUserManager.getUserIds(); 1952 final int permCount = pkg.requestedPermissions.size(); 1953 for (int i = 0; i < permCount; i++) { 1954 String permission = pkg.requestedPermissions.get(i); 1955 BasePermission bp = mSettings.mPermissions.get(permission); 1956 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1957 continue; 1958 } 1959 for (int userId : allUserIds) { 1960 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1961 permission, userId)) { 1962 grantRuntimePermission(pkg.packageName, permission, userId); 1963 } 1964 } 1965 } 1966 } 1967 1968 private StorageEventListener mStorageListener = new StorageEventListener() { 1969 @Override 1970 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1971 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1972 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1973 final String volumeUuid = vol.getFsUuid(); 1974 1975 // Clean up any users or apps that were removed or recreated 1976 // while this volume was missing 1977 sUserManager.reconcileUsers(volumeUuid); 1978 reconcileApps(volumeUuid); 1979 1980 // Clean up any install sessions that expired or were 1981 // cancelled while this volume was missing 1982 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1983 1984 loadPrivatePackages(vol); 1985 1986 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1987 unloadPrivatePackages(vol); 1988 } 1989 } 1990 1991 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1992 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1993 updateExternalMediaStatus(true, false); 1994 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1995 updateExternalMediaStatus(false, false); 1996 } 1997 } 1998 } 1999 2000 @Override 2001 public void onVolumeForgotten(String fsUuid) { 2002 if (TextUtils.isEmpty(fsUuid)) { 2003 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2004 return; 2005 } 2006 2007 // Remove any apps installed on the forgotten volume 2008 synchronized (mPackages) { 2009 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2010 for (PackageSetting ps : packages) { 2011 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2012 deletePackageVersioned(new VersionedPackage(ps.name, 2013 PackageManager.VERSION_CODE_HIGHEST), 2014 new LegacyPackageDeleteObserver(null).getBinder(), 2015 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2016 // Try very hard to release any references to this package 2017 // so we don't risk the system server being killed due to 2018 // open FDs 2019 AttributeCache.instance().removePackage(ps.name); 2020 } 2021 2022 mSettings.onVolumeForgotten(fsUuid); 2023 mSettings.writeLPr(); 2024 } 2025 } 2026 }; 2027 2028 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2029 String[] grantedPermissions) { 2030 for (int userId : userIds) { 2031 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2032 } 2033 } 2034 2035 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2036 String[] grantedPermissions) { 2037 SettingBase sb = (SettingBase) pkg.mExtras; 2038 if (sb == null) { 2039 return; 2040 } 2041 2042 PermissionsState permissionsState = sb.getPermissionsState(); 2043 2044 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2045 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2046 2047 final boolean supportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 2048 >= Build.VERSION_CODES.M; 2049 2050 final boolean instantApp = isInstantApp(pkg.packageName, userId); 2051 2052 for (String permission : pkg.requestedPermissions) { 2053 final BasePermission bp; 2054 synchronized (mPackages) { 2055 bp = mSettings.mPermissions.get(permission); 2056 } 2057 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2058 && (!instantApp || bp.isInstant()) 2059 && (supportsRuntimePermissions || !bp.isRuntimeOnly()) 2060 && (grantedPermissions == null 2061 || ArrayUtils.contains(grantedPermissions, permission))) { 2062 final int flags = permissionsState.getPermissionFlags(permission, userId); 2063 if (supportsRuntimePermissions) { 2064 // Installer cannot change immutable permissions. 2065 if ((flags & immutableFlags) == 0) { 2066 grantRuntimePermission(pkg.packageName, permission, userId); 2067 } 2068 } else if (mPermissionReviewRequired) { 2069 // In permission review mode we clear the review flag when we 2070 // are asked to install the app with all permissions granted. 2071 if ((flags & PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 2072 updatePermissionFlags(permission, pkg.packageName, 2073 PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED, 0, userId); 2074 } 2075 } 2076 } 2077 } 2078 } 2079 2080 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2081 Bundle extras = null; 2082 switch (res.returnCode) { 2083 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2084 extras = new Bundle(); 2085 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2086 res.origPermission); 2087 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2088 res.origPackage); 2089 break; 2090 } 2091 case PackageManager.INSTALL_SUCCEEDED: { 2092 extras = new Bundle(); 2093 extras.putBoolean(Intent.EXTRA_REPLACING, 2094 res.removedInfo != null && res.removedInfo.removedPackage != null); 2095 break; 2096 } 2097 } 2098 return extras; 2099 } 2100 2101 void scheduleWriteSettingsLocked() { 2102 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2103 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2104 } 2105 } 2106 2107 void scheduleWritePackageListLocked(int userId) { 2108 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2109 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2110 msg.arg1 = userId; 2111 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2112 } 2113 } 2114 2115 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2116 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2117 scheduleWritePackageRestrictionsLocked(userId); 2118 } 2119 2120 void scheduleWritePackageRestrictionsLocked(int userId) { 2121 final int[] userIds = (userId == UserHandle.USER_ALL) 2122 ? sUserManager.getUserIds() : new int[]{userId}; 2123 for (int nextUserId : userIds) { 2124 if (!sUserManager.exists(nextUserId)) return; 2125 mDirtyUsers.add(nextUserId); 2126 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2127 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 } 2131 2132 public static PackageManagerService main(Context context, Installer installer, 2133 boolean factoryTest, boolean onlyCore) { 2134 // Self-check for initial settings. 2135 PackageManagerServiceCompilerMapping.checkProperties(); 2136 2137 PackageManagerService m = new PackageManagerService(context, installer, 2138 factoryTest, onlyCore); 2139 m.enableSystemUserPackages(); 2140 ServiceManager.addService("package", m); 2141 return m; 2142 } 2143 2144 private void enableSystemUserPackages() { 2145 if (!UserManager.isSplitSystemUser()) { 2146 return; 2147 } 2148 // For system user, enable apps based on the following conditions: 2149 // - app is whitelisted or belong to one of these groups: 2150 // -- system app which has no launcher icons 2151 // -- system app which has INTERACT_ACROSS_USERS permission 2152 // -- system IME app 2153 // - app is not in the blacklist 2154 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2155 Set<String> enableApps = new ArraySet<>(); 2156 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2157 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2158 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2159 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2160 enableApps.addAll(wlApps); 2161 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2162 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2163 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2164 enableApps.removeAll(blApps); 2165 Log.i(TAG, "Applications installed for system user: " + enableApps); 2166 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2167 UserHandle.SYSTEM); 2168 final int allAppsSize = allAps.size(); 2169 synchronized (mPackages) { 2170 for (int i = 0; i < allAppsSize; i++) { 2171 String pName = allAps.get(i); 2172 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2173 // Should not happen, but we shouldn't be failing if it does 2174 if (pkgSetting == null) { 2175 continue; 2176 } 2177 boolean install = enableApps.contains(pName); 2178 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2179 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2180 + " for system user"); 2181 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2182 } 2183 } 2184 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2185 } 2186 } 2187 2188 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2189 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2190 Context.DISPLAY_SERVICE); 2191 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2192 } 2193 2194 /** 2195 * Requests that files preopted on a secondary system partition be copied to the data partition 2196 * if possible. Note that the actual copying of the files is accomplished by init for security 2197 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2198 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2199 */ 2200 private static void requestCopyPreoptedFiles() { 2201 final int WAIT_TIME_MS = 100; 2202 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2203 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2204 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2205 // We will wait for up to 100 seconds. 2206 final long timeStart = SystemClock.uptimeMillis(); 2207 final long timeEnd = timeStart + 100 * 1000; 2208 long timeNow = timeStart; 2209 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2210 try { 2211 Thread.sleep(WAIT_TIME_MS); 2212 } catch (InterruptedException e) { 2213 // Do nothing 2214 } 2215 timeNow = SystemClock.uptimeMillis(); 2216 if (timeNow > timeEnd) { 2217 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2218 Slog.wtf(TAG, "cppreopt did not finish!"); 2219 break; 2220 } 2221 } 2222 2223 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2224 } 2225 } 2226 2227 public PackageManagerService(Context context, Installer installer, 2228 boolean factoryTest, boolean onlyCore) { 2229 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2230 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2231 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2232 SystemClock.uptimeMillis()); 2233 2234 if (mSdkVersion <= 0) { 2235 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2236 } 2237 2238 mContext = context; 2239 2240 mPermissionReviewRequired = context.getResources().getBoolean( 2241 R.bool.config_permissionReviewRequired); 2242 2243 mFactoryTest = factoryTest; 2244 mOnlyCore = onlyCore; 2245 mMetrics = new DisplayMetrics(); 2246 mSettings = new Settings(mPackages); 2247 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2248 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2249 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2250 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2251 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2252 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2253 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2254 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2255 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2256 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2257 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2258 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2259 2260 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2261 if (separateProcesses != null && separateProcesses.length() > 0) { 2262 if ("*".equals(separateProcesses)) { 2263 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2264 mSeparateProcesses = null; 2265 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2266 } else { 2267 mDefParseFlags = 0; 2268 mSeparateProcesses = separateProcesses.split(","); 2269 Slog.w(TAG, "Running with debug.separate_processes: " 2270 + separateProcesses); 2271 } 2272 } else { 2273 mDefParseFlags = 0; 2274 mSeparateProcesses = null; 2275 } 2276 2277 mInstaller = installer; 2278 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2279 "*dexopt*"); 2280 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock); 2281 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2282 2283 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2284 FgThread.get().getLooper()); 2285 2286 getDefaultDisplayMetrics(context, mMetrics); 2287 2288 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2289 SystemConfig systemConfig = SystemConfig.getInstance(); 2290 mGlobalGids = systemConfig.getGlobalGids(); 2291 mSystemPermissions = systemConfig.getSystemPermissions(); 2292 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2294 2295 mProtectedPackages = new ProtectedPackages(mContext); 2296 2297 synchronized (mInstallLock) { 2298 // writer 2299 synchronized (mPackages) { 2300 mHandlerThread = new ServiceThread(TAG, 2301 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2302 mHandlerThread.start(); 2303 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2304 mProcessLoggingHandler = new ProcessLoggingHandler(); 2305 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2306 2307 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2308 mInstantAppRegistry = new InstantAppRegistry(this); 2309 2310 File dataDir = Environment.getDataDirectory(); 2311 mAppInstallDir = new File(dataDir, "app"); 2312 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2313 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2314 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2315 sUserManager = new UserManagerService(context, this, 2316 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2317 2318 // Propagate permission configuration in to package manager. 2319 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2320 = systemConfig.getPermissions(); 2321 for (int i=0; i<permConfig.size(); i++) { 2322 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2323 BasePermission bp = mSettings.mPermissions.get(perm.name); 2324 if (bp == null) { 2325 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2326 mSettings.mPermissions.put(perm.name, bp); 2327 } 2328 if (perm.gids != null) { 2329 bp.setGids(perm.gids, perm.perUser); 2330 } 2331 } 2332 2333 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2334 final int builtInLibCount = libConfig.size(); 2335 for (int i = 0; i < builtInLibCount; i++) { 2336 String name = libConfig.keyAt(i); 2337 String path = libConfig.valueAt(i); 2338 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2339 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2340 } 2341 2342 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2343 2344 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2345 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2346 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2347 2348 // Clean up orphaned packages for which the code path doesn't exist 2349 // and they are an update to a system app - caused by bug/32321269 2350 final int packageSettingCount = mSettings.mPackages.size(); 2351 for (int i = packageSettingCount - 1; i >= 0; i--) { 2352 PackageSetting ps = mSettings.mPackages.valueAt(i); 2353 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2354 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2355 mSettings.mPackages.removeAt(i); 2356 mSettings.enableSystemPackageLPw(ps.name); 2357 } 2358 } 2359 2360 if (mFirstBoot) { 2361 requestCopyPreoptedFiles(); 2362 } 2363 2364 String customResolverActivity = Resources.getSystem().getString( 2365 R.string.config_customResolverActivity); 2366 if (TextUtils.isEmpty(customResolverActivity)) { 2367 customResolverActivity = null; 2368 } else { 2369 mCustomResolverComponentName = ComponentName.unflattenFromString( 2370 customResolverActivity); 2371 } 2372 2373 long startTime = SystemClock.uptimeMillis(); 2374 2375 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2376 startTime); 2377 2378 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2379 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2380 2381 if (bootClassPath == null) { 2382 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2383 } 2384 2385 if (systemServerClassPath == null) { 2386 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2387 } 2388 2389 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2390 2391 final VersionInfo ver = mSettings.getInternalVersion(); 2392 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2393 if (mIsUpgrade) { 2394 logCriticalInfo(Log.INFO, 2395 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2396 } 2397 2398 // when upgrading from pre-M, promote system app permissions from install to runtime 2399 mPromoteSystemApps = 2400 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2401 2402 // When upgrading from pre-N, we need to handle package extraction like first boot, 2403 // as there is no profiling data available. 2404 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2405 2406 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2407 2408 // save off the names of pre-existing system packages prior to scanning; we don't 2409 // want to automatically grant runtime permissions for new system apps 2410 if (mPromoteSystemApps) { 2411 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2412 while (pkgSettingIter.hasNext()) { 2413 PackageSetting ps = pkgSettingIter.next(); 2414 if (isSystemApp(ps)) { 2415 mExistingSystemPackages.add(ps.name); 2416 } 2417 } 2418 } 2419 2420 mCacheDir = preparePackageParserCache(mIsUpgrade); 2421 2422 // Set flag to monitor and not change apk file paths when 2423 // scanning install directories. 2424 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2425 2426 if (mIsUpgrade || mFirstBoot) { 2427 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2428 } 2429 2430 // Collect vendor overlay packages. (Do this before scanning any apps.) 2431 // For security and version matching reason, only consider 2432 // overlay packages if they reside in the right directory. 2433 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2434 | PackageParser.PARSE_IS_SYSTEM 2435 | PackageParser.PARSE_IS_SYSTEM_DIR 2436 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2437 2438 // Find base frameworks (resource packages without code). 2439 scanDirTracedLI(frameworkDir, mDefParseFlags 2440 | PackageParser.PARSE_IS_SYSTEM 2441 | PackageParser.PARSE_IS_SYSTEM_DIR 2442 | PackageParser.PARSE_IS_PRIVILEGED, 2443 scanFlags | SCAN_NO_DEX, 0); 2444 2445 // Collected privileged system packages. 2446 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2447 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2448 | PackageParser.PARSE_IS_SYSTEM 2449 | PackageParser.PARSE_IS_SYSTEM_DIR 2450 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2451 2452 // Collect ordinary system packages. 2453 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2454 scanDirTracedLI(systemAppDir, mDefParseFlags 2455 | PackageParser.PARSE_IS_SYSTEM 2456 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2457 2458 // Collect all vendor packages. 2459 File vendorAppDir = new File("/vendor/app"); 2460 try { 2461 vendorAppDir = vendorAppDir.getCanonicalFile(); 2462 } catch (IOException e) { 2463 // failed to look up canonical path, continue with original one 2464 } 2465 scanDirTracedLI(vendorAppDir, mDefParseFlags 2466 | PackageParser.PARSE_IS_SYSTEM 2467 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2468 2469 // Collect all OEM packages. 2470 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2471 scanDirTracedLI(oemAppDir, mDefParseFlags 2472 | PackageParser.PARSE_IS_SYSTEM 2473 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2474 2475 // Prune any system packages that no longer exist. 2476 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2477 if (!mOnlyCore) { 2478 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2479 while (psit.hasNext()) { 2480 PackageSetting ps = psit.next(); 2481 2482 /* 2483 * If this is not a system app, it can't be a 2484 * disable system app. 2485 */ 2486 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2487 continue; 2488 } 2489 2490 /* 2491 * If the package is scanned, it's not erased. 2492 */ 2493 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2494 if (scannedPkg != null) { 2495 /* 2496 * If the system app is both scanned and in the 2497 * disabled packages list, then it must have been 2498 * added via OTA. Remove it from the currently 2499 * scanned package so the previously user-installed 2500 * application can be scanned. 2501 */ 2502 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2503 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2504 + ps.name + "; removing system app. Last known codePath=" 2505 + ps.codePathString + ", installStatus=" + ps.installStatus 2506 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2507 + scannedPkg.mVersionCode); 2508 removePackageLI(scannedPkg, true); 2509 mExpectingBetter.put(ps.name, ps.codePath); 2510 } 2511 2512 continue; 2513 } 2514 2515 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2516 psit.remove(); 2517 logCriticalInfo(Log.WARN, "System package " + ps.name 2518 + " no longer exists; it's data will be wiped"); 2519 // Actual deletion of code and data will be handled by later 2520 // reconciliation step 2521 } else { 2522 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2523 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2524 possiblyDeletedUpdatedSystemApps.add(ps.name); 2525 } 2526 } 2527 } 2528 } 2529 2530 //look for any incomplete package installations 2531 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2532 for (int i = 0; i < deletePkgsList.size(); i++) { 2533 // Actual deletion of code and data will be handled by later 2534 // reconciliation step 2535 final String packageName = deletePkgsList.get(i).name; 2536 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2537 synchronized (mPackages) { 2538 mSettings.removePackageLPw(packageName); 2539 } 2540 } 2541 2542 //delete tmp files 2543 deleteTempPackageFiles(); 2544 2545 // Remove any shared userIDs that have no associated packages 2546 mSettings.pruneSharedUsersLPw(); 2547 2548 if (!mOnlyCore) { 2549 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2550 SystemClock.uptimeMillis()); 2551 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2552 2553 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2554 | PackageParser.PARSE_FORWARD_LOCK, 2555 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2556 2557 /** 2558 * Remove disable package settings for any updated system 2559 * apps that were removed via an OTA. If they're not a 2560 * previously-updated app, remove them completely. 2561 * Otherwise, just revoke their system-level permissions. 2562 */ 2563 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2564 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2565 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2566 2567 String msg; 2568 if (deletedPkg == null) { 2569 msg = "Updated system package " + deletedAppName 2570 + " no longer exists; it's data will be wiped"; 2571 // Actual deletion of code and data will be handled by later 2572 // reconciliation step 2573 } else { 2574 msg = "Updated system app + " + deletedAppName 2575 + " no longer present; removing system privileges for " 2576 + deletedAppName; 2577 2578 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2579 2580 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2581 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2582 } 2583 logCriticalInfo(Log.WARN, msg); 2584 } 2585 2586 /** 2587 * Make sure all system apps that we expected to appear on 2588 * the userdata partition actually showed up. If they never 2589 * appeared, crawl back and revive the system version. 2590 */ 2591 for (int i = 0; i < mExpectingBetter.size(); i++) { 2592 final String packageName = mExpectingBetter.keyAt(i); 2593 if (!mPackages.containsKey(packageName)) { 2594 final File scanFile = mExpectingBetter.valueAt(i); 2595 2596 logCriticalInfo(Log.WARN, "Expected better " + packageName 2597 + " but never showed up; reverting to system"); 2598 2599 int reparseFlags = mDefParseFlags; 2600 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2601 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2602 | PackageParser.PARSE_IS_SYSTEM_DIR 2603 | PackageParser.PARSE_IS_PRIVILEGED; 2604 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2605 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2606 | PackageParser.PARSE_IS_SYSTEM_DIR; 2607 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2608 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2609 | PackageParser.PARSE_IS_SYSTEM_DIR; 2610 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2611 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2612 | PackageParser.PARSE_IS_SYSTEM_DIR; 2613 } else { 2614 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2615 continue; 2616 } 2617 2618 mSettings.enableSystemPackageLPw(packageName); 2619 2620 try { 2621 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2622 } catch (PackageManagerException e) { 2623 Slog.e(TAG, "Failed to parse original system package: " 2624 + e.getMessage()); 2625 } 2626 } 2627 } 2628 } 2629 mExpectingBetter.clear(); 2630 2631 // Resolve the storage manager. 2632 mStorageManagerPackage = getStorageManagerPackageName(); 2633 2634 // Resolve protected action filters. Only the setup wizard is allowed to 2635 // have a high priority filter for these actions. 2636 mSetupWizardPackage = getSetupWizardPackageName(); 2637 if (mProtectedFilters.size() > 0) { 2638 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2639 Slog.i(TAG, "No setup wizard;" 2640 + " All protected intents capped to priority 0"); 2641 } 2642 for (ActivityIntentInfo filter : mProtectedFilters) { 2643 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2644 if (DEBUG_FILTERS) { 2645 Slog.i(TAG, "Found setup wizard;" 2646 + " allow priority " + filter.getPriority() + ";" 2647 + " package: " + filter.activity.info.packageName 2648 + " activity: " + filter.activity.className 2649 + " priority: " + filter.getPriority()); 2650 } 2651 // skip setup wizard; allow it to keep the high priority filter 2652 continue; 2653 } 2654 Slog.w(TAG, "Protected action; cap priority to 0;" 2655 + " package: " + filter.activity.info.packageName 2656 + " activity: " + filter.activity.className 2657 + " origPrio: " + filter.getPriority()); 2658 filter.setPriority(0); 2659 } 2660 } 2661 mDeferProtectedFilters = false; 2662 mProtectedFilters.clear(); 2663 2664 // Now that we know all of the shared libraries, update all clients to have 2665 // the correct library paths. 2666 updateAllSharedLibrariesLPw(null); 2667 2668 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2669 // NOTE: We ignore potential failures here during a system scan (like 2670 // the rest of the commands above) because there's precious little we 2671 // can do about it. A settings error is reported, though. 2672 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2673 } 2674 2675 // Now that we know all the packages we are keeping, 2676 // read and update their last usage times. 2677 mPackageUsage.read(mPackages); 2678 mCompilerStats.read(); 2679 2680 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2681 SystemClock.uptimeMillis()); 2682 Slog.i(TAG, "Time to scan packages: " 2683 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2684 + " seconds"); 2685 2686 // If the platform SDK has changed since the last time we booted, 2687 // we need to re-grant app permission to catch any new ones that 2688 // appear. This is really a hack, and means that apps can in some 2689 // cases get permissions that the user didn't initially explicitly 2690 // allow... it would be nice to have some better way to handle 2691 // this situation. 2692 int updateFlags = UPDATE_PERMISSIONS_ALL; 2693 if (ver.sdkVersion != mSdkVersion) { 2694 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2695 + mSdkVersion + "; regranting permissions for internal storage"); 2696 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2697 } 2698 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2699 ver.sdkVersion = mSdkVersion; 2700 2701 // If this is the first boot or an update from pre-M, and it is a normal 2702 // boot, then we need to initialize the default preferred apps across 2703 // all defined users. 2704 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2705 for (UserInfo user : sUserManager.getUsers(true)) { 2706 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2707 applyFactoryDefaultBrowserLPw(user.id); 2708 primeDomainVerificationsLPw(user.id); 2709 } 2710 } 2711 2712 // Prepare storage for system user really early during boot, 2713 // since core system apps like SettingsProvider and SystemUI 2714 // can't wait for user to start 2715 final int storageFlags; 2716 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2717 storageFlags = StorageManager.FLAG_STORAGE_DE; 2718 } else { 2719 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2720 } 2721 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2722 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2723 true /* onlyCoreApps */); 2724 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2725 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "fixup"); 2726 try { 2727 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2728 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2729 } catch (InstallerException e) { 2730 Slog.w(TAG, "Trouble fixing GIDs", e); 2731 } 2732 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2733 2734 if (deferPackages == null || deferPackages.isEmpty()) { 2735 return; 2736 } 2737 int count = 0; 2738 for (String pkgName : deferPackages) { 2739 PackageParser.Package pkg = null; 2740 synchronized (mPackages) { 2741 PackageSetting ps = mSettings.getPackageLPr(pkgName); 2742 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 2743 pkg = ps.pkg; 2744 } 2745 } 2746 if (pkg != null) { 2747 synchronized (mInstallLock) { 2748 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 2749 true /* maybeMigrateAppData */); 2750 } 2751 count++; 2752 } 2753 } 2754 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 2755 }, "prepareAppData"); 2756 2757 // If this is first boot after an OTA, and a normal boot, then 2758 // we need to clear code cache directories. 2759 // Note that we do *not* clear the application profiles. These remain valid 2760 // across OTAs and are used to drive profile verification (post OTA) and 2761 // profile compilation (without waiting to collect a fresh set of profiles). 2762 if (mIsUpgrade && !onlyCore) { 2763 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2764 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2765 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2766 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2767 // No apps are running this early, so no need to freeze 2768 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2769 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2770 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2771 } 2772 } 2773 ver.fingerprint = Build.FINGERPRINT; 2774 } 2775 2776 checkDefaultBrowser(); 2777 2778 // clear only after permissions and other defaults have been updated 2779 mExistingSystemPackages.clear(); 2780 mPromoteSystemApps = false; 2781 2782 // All the changes are done during package scanning. 2783 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2784 2785 // can downgrade to reader 2786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2787 mSettings.writeLPr(); 2788 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2789 2790 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2791 SystemClock.uptimeMillis()); 2792 2793 if (!mOnlyCore) { 2794 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2795 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2796 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2797 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2798 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2799 mIntentFilterVerifierComponent); 2800 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2801 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 2802 SharedLibraryInfo.VERSION_UNDEFINED); 2803 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2804 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2805 SharedLibraryInfo.VERSION_UNDEFINED); 2806 } else { 2807 mRequiredVerifierPackage = null; 2808 mRequiredInstallerPackage = null; 2809 mRequiredUninstallerPackage = null; 2810 mIntentFilterVerifierComponent = null; 2811 mIntentFilterVerifier = null; 2812 mServicesSystemSharedLibraryPackageName = null; 2813 mSharedSystemSharedLibraryPackageName = null; 2814 } 2815 2816 mInstallerService = new PackageInstallerService(context, this); 2817 final Pair<ComponentName, String> instantAppResolverComponent = 2818 getInstantAppResolverLPr(); 2819 if (instantAppResolverComponent != null) { 2820 if (DEBUG_EPHEMERAL) { 2821 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2822 } 2823 mInstantAppResolverConnection = new EphemeralResolverConnection( 2824 mContext, instantAppResolverComponent.first, 2825 instantAppResolverComponent.second); 2826 mInstantAppResolverSettingsComponent = 2827 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 2828 } else { 2829 mInstantAppResolverConnection = null; 2830 mInstantAppResolverSettingsComponent = null; 2831 } 2832 updateInstantAppInstallerLocked(null); 2833 2834 // Read and update the usage of dex files. 2835 // Do this at the end of PM init so that all the packages have their 2836 // data directory reconciled. 2837 // At this point we know the code paths of the packages, so we can validate 2838 // the disk file and build the internal cache. 2839 // The usage file is expected to be small so loading and verifying it 2840 // should take a fairly small time compare to the other activities (e.g. package 2841 // scanning). 2842 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2843 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 2844 for (int userId : currentUserIds) { 2845 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 2846 } 2847 mDexManager.load(userPackages); 2848 } // synchronized (mPackages) 2849 } // synchronized (mInstallLock) 2850 2851 // Now after opening every single application zip, make sure they 2852 // are all flushed. Not really needed, but keeps things nice and 2853 // tidy. 2854 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2855 Runtime.getRuntime().gc(); 2856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2857 2858 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2859 FallbackCategoryProvider.loadFallbacks(); 2860 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2861 2862 // The initial scanning above does many calls into installd while 2863 // holding the mPackages lock, but we're mostly interested in yelling 2864 // once we have a booted system. 2865 mInstaller.setWarnIfHeld(mPackages); 2866 2867 // Expose private service for system components to use. 2868 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2869 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2870 } 2871 2872 private void updateInstantAppInstallerLocked(String modifiedPackage) { 2873 // we're only interested in updating the installer appliction when 1) it's not 2874 // already set or 2) the modified package is the installer 2875 if (mInstantAppInstallerActivity != null 2876 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 2877 .equals(modifiedPackage)) { 2878 return; 2879 } 2880 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 2881 } 2882 2883 private static File preparePackageParserCache(boolean isUpgrade) { 2884 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 2885 return null; 2886 } 2887 2888 // Disable package parsing on eng builds to allow for faster incremental development. 2889 if ("eng".equals(Build.TYPE)) { 2890 return null; 2891 } 2892 2893 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 2894 Slog.i(TAG, "Disabling package parser cache due to system property."); 2895 return null; 2896 } 2897 2898 // The base directory for the package parser cache lives under /data/system/. 2899 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 2900 "package_cache"); 2901 if (cacheBaseDir == null) { 2902 return null; 2903 } 2904 2905 // If this is a system upgrade scenario, delete the contents of the package cache dir. 2906 // This also serves to "GC" unused entries when the package cache version changes (which 2907 // can only happen during upgrades). 2908 if (isUpgrade) { 2909 FileUtils.deleteContents(cacheBaseDir); 2910 } 2911 2912 2913 // Return the versioned package cache directory. This is something like 2914 // "/data/system/package_cache/1" 2915 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2916 2917 // The following is a workaround to aid development on non-numbered userdebug 2918 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 2919 // the system partition is newer. 2920 // 2921 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 2922 // that starts with "eng." to signify that this is an engineering build and not 2923 // destined for release. 2924 if ("userdebug".equals(Build.TYPE) && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 2925 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 2926 2927 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 2928 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 2929 // in general and should not be used for production changes. In this specific case, 2930 // we know that they will work. 2931 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2932 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 2933 FileUtils.deleteContents(cacheBaseDir); 2934 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 2935 } 2936 } 2937 2938 return cacheDir; 2939 } 2940 2941 @Override 2942 public boolean isFirstBoot() { 2943 return mFirstBoot; 2944 } 2945 2946 @Override 2947 public boolean isOnlyCoreApps() { 2948 return mOnlyCore; 2949 } 2950 2951 @Override 2952 public boolean isUpgrade() { 2953 return mIsUpgrade; 2954 } 2955 2956 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2957 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2958 2959 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2960 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2961 UserHandle.USER_SYSTEM); 2962 if (matches.size() == 1) { 2963 return matches.get(0).getComponentInfo().packageName; 2964 } else if (matches.size() == 0) { 2965 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2966 return null; 2967 } 2968 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2969 } 2970 2971 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 2972 synchronized (mPackages) { 2973 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 2974 if (libraryEntry == null) { 2975 throw new IllegalStateException("Missing required shared library:" + name); 2976 } 2977 return libraryEntry.apk; 2978 } 2979 } 2980 2981 private @NonNull String getRequiredInstallerLPr() { 2982 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2983 intent.addCategory(Intent.CATEGORY_DEFAULT); 2984 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2985 2986 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2987 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2988 UserHandle.USER_SYSTEM); 2989 if (matches.size() == 1) { 2990 ResolveInfo resolveInfo = matches.get(0); 2991 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2992 throw new RuntimeException("The installer must be a privileged app"); 2993 } 2994 return matches.get(0).getComponentInfo().packageName; 2995 } else { 2996 throw new RuntimeException("There must be exactly one installer; found " + matches); 2997 } 2998 } 2999 3000 private @NonNull String getRequiredUninstallerLPr() { 3001 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3002 intent.addCategory(Intent.CATEGORY_DEFAULT); 3003 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3004 3005 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3006 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3007 UserHandle.USER_SYSTEM); 3008 if (resolveInfo == null || 3009 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3010 throw new RuntimeException("There must be exactly one uninstaller; found " 3011 + resolveInfo); 3012 } 3013 return resolveInfo.getComponentInfo().packageName; 3014 } 3015 3016 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3017 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3018 3019 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3020 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3021 UserHandle.USER_SYSTEM); 3022 ResolveInfo best = null; 3023 final int N = matches.size(); 3024 for (int i = 0; i < N; i++) { 3025 final ResolveInfo cur = matches.get(i); 3026 final String packageName = cur.getComponentInfo().packageName; 3027 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3028 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3029 continue; 3030 } 3031 3032 if (best == null || cur.priority > best.priority) { 3033 best = cur; 3034 } 3035 } 3036 3037 if (best != null) { 3038 return best.getComponentInfo().getComponentName(); 3039 } else { 3040 throw new RuntimeException("There must be at least one intent filter verifier"); 3041 } 3042 } 3043 3044 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3045 final String[] packageArray = 3046 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3047 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3048 if (DEBUG_EPHEMERAL) { 3049 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3050 } 3051 return null; 3052 } 3053 3054 final int callingUid = Binder.getCallingUid(); 3055 final int resolveFlags = 3056 MATCH_DIRECT_BOOT_AWARE 3057 | MATCH_DIRECT_BOOT_UNAWARE 3058 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3059 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3060 final Intent resolverIntent = new Intent(actionName); 3061 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3062 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3063 // temporarily look for the old action 3064 if (resolvers.size() == 0) { 3065 if (DEBUG_EPHEMERAL) { 3066 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3067 } 3068 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3069 resolverIntent.setAction(actionName); 3070 resolvers = queryIntentServicesInternal(resolverIntent, null, 3071 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3072 } 3073 final int N = resolvers.size(); 3074 if (N == 0) { 3075 if (DEBUG_EPHEMERAL) { 3076 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3077 } 3078 return null; 3079 } 3080 3081 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3082 for (int i = 0; i < N; i++) { 3083 final ResolveInfo info = resolvers.get(i); 3084 3085 if (info.serviceInfo == null) { 3086 continue; 3087 } 3088 3089 final String packageName = info.serviceInfo.packageName; 3090 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3091 if (DEBUG_EPHEMERAL) { 3092 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3093 + " pkg: " + packageName + ", info:" + info); 3094 } 3095 continue; 3096 } 3097 3098 if (DEBUG_EPHEMERAL) { 3099 Slog.v(TAG, "Ephemeral resolver found;" 3100 + " pkg: " + packageName + ", info:" + info); 3101 } 3102 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3103 } 3104 if (DEBUG_EPHEMERAL) { 3105 Slog.v(TAG, "Ephemeral resolver NOT found"); 3106 } 3107 return null; 3108 } 3109 3110 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3111 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3112 intent.addCategory(Intent.CATEGORY_DEFAULT); 3113 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3114 3115 final int resolveFlags = 3116 MATCH_DIRECT_BOOT_AWARE 3117 | MATCH_DIRECT_BOOT_UNAWARE 3118 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3119 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3120 resolveFlags, UserHandle.USER_SYSTEM); 3121 // temporarily look for the old action 3122 if (matches.isEmpty()) { 3123 if (DEBUG_EPHEMERAL) { 3124 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3125 } 3126 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3127 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3128 resolveFlags, UserHandle.USER_SYSTEM); 3129 } 3130 Iterator<ResolveInfo> iter = matches.iterator(); 3131 while (iter.hasNext()) { 3132 final ResolveInfo rInfo = iter.next(); 3133 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3134 if (ps != null) { 3135 final PermissionsState permissionsState = ps.getPermissionsState(); 3136 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3137 continue; 3138 } 3139 } 3140 iter.remove(); 3141 } 3142 if (matches.size() == 0) { 3143 return null; 3144 } else if (matches.size() == 1) { 3145 return (ActivityInfo) matches.get(0).getComponentInfo(); 3146 } else { 3147 throw new RuntimeException( 3148 "There must be at most one ephemeral installer; found " + matches); 3149 } 3150 } 3151 3152 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3153 @NonNull ComponentName resolver) { 3154 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3155 .addCategory(Intent.CATEGORY_DEFAULT) 3156 .setPackage(resolver.getPackageName()); 3157 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3158 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3159 UserHandle.USER_SYSTEM); 3160 // temporarily look for the old action 3161 if (matches.isEmpty()) { 3162 if (DEBUG_EPHEMERAL) { 3163 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3164 } 3165 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3166 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3167 UserHandle.USER_SYSTEM); 3168 } 3169 if (matches.isEmpty()) { 3170 return null; 3171 } 3172 return matches.get(0).getComponentInfo().getComponentName(); 3173 } 3174 3175 private void primeDomainVerificationsLPw(int userId) { 3176 if (DEBUG_DOMAIN_VERIFICATION) { 3177 Slog.d(TAG, "Priming domain verifications in user " + userId); 3178 } 3179 3180 SystemConfig systemConfig = SystemConfig.getInstance(); 3181 ArraySet<String> packages = systemConfig.getLinkedApps(); 3182 3183 for (String packageName : packages) { 3184 PackageParser.Package pkg = mPackages.get(packageName); 3185 if (pkg != null) { 3186 if (!pkg.isSystemApp()) { 3187 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3188 continue; 3189 } 3190 3191 ArraySet<String> domains = null; 3192 for (PackageParser.Activity a : pkg.activities) { 3193 for (ActivityIntentInfo filter : a.intents) { 3194 if (hasValidDomains(filter)) { 3195 if (domains == null) { 3196 domains = new ArraySet<String>(); 3197 } 3198 domains.addAll(filter.getHostsList()); 3199 } 3200 } 3201 } 3202 3203 if (domains != null && domains.size() > 0) { 3204 if (DEBUG_DOMAIN_VERIFICATION) { 3205 Slog.v(TAG, " + " + packageName); 3206 } 3207 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3208 // state w.r.t. the formal app-linkage "no verification attempted" state; 3209 // and then 'always' in the per-user state actually used for intent resolution. 3210 final IntentFilterVerificationInfo ivi; 3211 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3212 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3213 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3214 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3215 } else { 3216 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3217 + "' does not handle web links"); 3218 } 3219 } else { 3220 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3221 } 3222 } 3223 3224 scheduleWritePackageRestrictionsLocked(userId); 3225 scheduleWriteSettingsLocked(); 3226 } 3227 3228 private void applyFactoryDefaultBrowserLPw(int userId) { 3229 // The default browser app's package name is stored in a string resource, 3230 // with a product-specific overlay used for vendor customization. 3231 String browserPkg = mContext.getResources().getString( 3232 com.android.internal.R.string.default_browser); 3233 if (!TextUtils.isEmpty(browserPkg)) { 3234 // non-empty string => required to be a known package 3235 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3236 if (ps == null) { 3237 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3238 browserPkg = null; 3239 } else { 3240 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3241 } 3242 } 3243 3244 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3245 // default. If there's more than one, just leave everything alone. 3246 if (browserPkg == null) { 3247 calculateDefaultBrowserLPw(userId); 3248 } 3249 } 3250 3251 private void calculateDefaultBrowserLPw(int userId) { 3252 List<String> allBrowsers = resolveAllBrowserApps(userId); 3253 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3254 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3255 } 3256 3257 private List<String> resolveAllBrowserApps(int userId) { 3258 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3259 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3260 PackageManager.MATCH_ALL, userId); 3261 3262 final int count = list.size(); 3263 List<String> result = new ArrayList<String>(count); 3264 for (int i=0; i<count; i++) { 3265 ResolveInfo info = list.get(i); 3266 if (info.activityInfo == null 3267 || !info.handleAllWebDataURI 3268 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3269 || result.contains(info.activityInfo.packageName)) { 3270 continue; 3271 } 3272 result.add(info.activityInfo.packageName); 3273 } 3274 3275 return result; 3276 } 3277 3278 private boolean packageIsBrowser(String packageName, int userId) { 3279 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3280 PackageManager.MATCH_ALL, userId); 3281 final int N = list.size(); 3282 for (int i = 0; i < N; i++) { 3283 ResolveInfo info = list.get(i); 3284 if (packageName.equals(info.activityInfo.packageName)) { 3285 return true; 3286 } 3287 } 3288 return false; 3289 } 3290 3291 private void checkDefaultBrowser() { 3292 final int myUserId = UserHandle.myUserId(); 3293 final String packageName = getDefaultBrowserPackageName(myUserId); 3294 if (packageName != null) { 3295 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3296 if (info == null) { 3297 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3298 synchronized (mPackages) { 3299 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3300 } 3301 } 3302 } 3303 } 3304 3305 @Override 3306 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3307 throws RemoteException { 3308 try { 3309 return super.onTransact(code, data, reply, flags); 3310 } catch (RuntimeException e) { 3311 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3312 Slog.wtf(TAG, "Package Manager Crash", e); 3313 } 3314 throw e; 3315 } 3316 } 3317 3318 static int[] appendInts(int[] cur, int[] add) { 3319 if (add == null) return cur; 3320 if (cur == null) return add; 3321 final int N = add.length; 3322 for (int i=0; i<N; i++) { 3323 cur = appendInt(cur, add[i]); 3324 } 3325 return cur; 3326 } 3327 3328 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3329 if (!sUserManager.exists(userId)) return null; 3330 if (ps == null) { 3331 return null; 3332 } 3333 final PackageParser.Package p = ps.pkg; 3334 if (p == null) { 3335 return null; 3336 } 3337 // Filter out ephemeral app metadata: 3338 // * The system/shell/root can see metadata for any app 3339 // * An installed app can see metadata for 1) other installed apps 3340 // and 2) ephemeral apps that have explicitly interacted with it 3341 // * Ephemeral apps can only see their own data and exposed installed apps 3342 // * Holding a signature permission allows seeing instant apps 3343 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 3344 if (callingAppId != Process.SYSTEM_UID 3345 && callingAppId != Process.SHELL_UID 3346 && callingAppId != Process.ROOT_UID 3347 && checkUidPermission(Manifest.permission.ACCESS_INSTANT_APPS, 3348 Binder.getCallingUid()) != PackageManager.PERMISSION_GRANTED) { 3349 final String instantAppPackageName = getInstantAppPackageName(Binder.getCallingUid()); 3350 if (instantAppPackageName != null) { 3351 // ephemeral apps can only get information on themselves or 3352 // installed apps that are exposed. 3353 if (!instantAppPackageName.equals(p.packageName) 3354 && (ps.getInstantApp(userId) || !p.visibleToInstantApps)) { 3355 return null; 3356 } 3357 } else { 3358 if (ps.getInstantApp(userId)) { 3359 // only get access to the ephemeral app if we've been granted access 3360 if (!mInstantAppRegistry.isInstantAccessGranted( 3361 userId, callingAppId, ps.appId)) { 3362 return null; 3363 } 3364 } 3365 } 3366 } 3367 3368 final PermissionsState permissionsState = ps.getPermissionsState(); 3369 3370 // Compute GIDs only if requested 3371 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3372 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3373 // Compute granted permissions only if package has requested permissions 3374 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3375 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3376 final PackageUserState state = ps.readUserState(userId); 3377 3378 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3379 && ps.isSystem()) { 3380 flags |= MATCH_ANY_USER; 3381 } 3382 3383 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3384 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3385 3386 if (packageInfo == null) { 3387 return null; 3388 } 3389 3390 rebaseEnabledOverlays(packageInfo.applicationInfo, userId); 3391 3392 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3393 resolveExternalPackageNameLPr(p); 3394 3395 return packageInfo; 3396 } 3397 3398 @Override 3399 public void checkPackageStartable(String packageName, int userId) { 3400 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3401 3402 synchronized (mPackages) { 3403 final PackageSetting ps = mSettings.mPackages.get(packageName); 3404 if (ps == null) { 3405 throw new SecurityException("Package " + packageName + " was not found!"); 3406 } 3407 3408 if (!ps.getInstalled(userId)) { 3409 throw new SecurityException( 3410 "Package " + packageName + " was not installed for user " + userId + "!"); 3411 } 3412 3413 if (mSafeMode && !ps.isSystem()) { 3414 throw new SecurityException("Package " + packageName + " not a system app!"); 3415 } 3416 3417 if (mFrozenPackages.contains(packageName)) { 3418 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3419 } 3420 3421 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3422 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3423 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3424 } 3425 } 3426 } 3427 3428 @Override 3429 public boolean isPackageAvailable(String packageName, int userId) { 3430 if (!sUserManager.exists(userId)) return false; 3431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3432 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3433 synchronized (mPackages) { 3434 PackageParser.Package p = mPackages.get(packageName); 3435 if (p != null) { 3436 final PackageSetting ps = (PackageSetting) p.mExtras; 3437 if (ps != null) { 3438 final PackageUserState state = ps.readUserState(userId); 3439 if (state != null) { 3440 return PackageParser.isAvailable(state); 3441 } 3442 } 3443 } 3444 } 3445 return false; 3446 } 3447 3448 @Override 3449 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3450 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3451 flags, userId); 3452 } 3453 3454 @Override 3455 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3456 int flags, int userId) { 3457 return getPackageInfoInternal(versionedPackage.getPackageName(), 3458 // TODO: We will change version code to long, so in the new API it is long 3459 (int) versionedPackage.getVersionCode(), flags, userId); 3460 } 3461 3462 private PackageInfo getPackageInfoInternal(String packageName, int versionCode, 3463 int flags, int userId) { 3464 if (!sUserManager.exists(userId)) return null; 3465 flags = updateFlagsForPackage(flags, userId, packageName); 3466 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3467 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3468 3469 // reader 3470 synchronized (mPackages) { 3471 // Normalize package name to handle renamed packages and static libs 3472 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3473 3474 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3475 if (matchFactoryOnly) { 3476 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3477 if (ps != null) { 3478 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3479 return null; 3480 } 3481 return generatePackageInfo(ps, flags, userId); 3482 } 3483 } 3484 3485 PackageParser.Package p = mPackages.get(packageName); 3486 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3487 return null; 3488 } 3489 if (DEBUG_PACKAGE_INFO) 3490 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3491 if (p != null) { 3492 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 3493 Binder.getCallingUid(), userId)) { 3494 return null; 3495 } 3496 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3497 } 3498 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3499 final PackageSetting ps = mSettings.mPackages.get(packageName); 3500 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3501 return null; 3502 } 3503 return generatePackageInfo(ps, flags, userId); 3504 } 3505 } 3506 return null; 3507 } 3508 3509 3510 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId) { 3511 // System/shell/root get to see all static libs 3512 final int appId = UserHandle.getAppId(uid); 3513 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 3514 || appId == Process.ROOT_UID) { 3515 return false; 3516 } 3517 3518 // No package means no static lib as it is always on internal storage 3519 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 3520 return false; 3521 } 3522 3523 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 3524 ps.pkg.staticSharedLibVersion); 3525 if (libEntry == null) { 3526 return false; 3527 } 3528 3529 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 3530 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 3531 if (uidPackageNames == null) { 3532 return true; 3533 } 3534 3535 for (String uidPackageName : uidPackageNames) { 3536 if (ps.name.equals(uidPackageName)) { 3537 return false; 3538 } 3539 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 3540 if (uidPs != null) { 3541 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 3542 libEntry.info.getName()); 3543 if (index < 0) { 3544 continue; 3545 } 3546 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getVersion()) { 3547 return false; 3548 } 3549 } 3550 } 3551 return true; 3552 } 3553 3554 @Override 3555 public String[] currentToCanonicalPackageNames(String[] names) { 3556 String[] out = new String[names.length]; 3557 // reader 3558 synchronized (mPackages) { 3559 for (int i=names.length-1; i>=0; i--) { 3560 PackageSetting ps = mSettings.mPackages.get(names[i]); 3561 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3562 } 3563 } 3564 return out; 3565 } 3566 3567 @Override 3568 public String[] canonicalToCurrentPackageNames(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 String cur = mSettings.getRenamedPackageLPr(names[i]); 3574 out[i] = cur != null ? cur : names[i]; 3575 } 3576 } 3577 return out; 3578 } 3579 3580 @Override 3581 public int getPackageUid(String packageName, int flags, int userId) { 3582 if (!sUserManager.exists(userId)) return -1; 3583 flags = updateFlagsForPackage(flags, userId, packageName); 3584 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3585 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3586 3587 // reader 3588 synchronized (mPackages) { 3589 final PackageParser.Package p = mPackages.get(packageName); 3590 if (p != null && p.isMatch(flags)) { 3591 return UserHandle.getUid(userId, p.applicationInfo.uid); 3592 } 3593 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3594 final PackageSetting ps = mSettings.mPackages.get(packageName); 3595 if (ps != null && ps.isMatch(flags)) { 3596 return UserHandle.getUid(userId, ps.appId); 3597 } 3598 } 3599 } 3600 3601 return -1; 3602 } 3603 3604 @Override 3605 public int[] getPackageGids(String packageName, int flags, int userId) { 3606 if (!sUserManager.exists(userId)) return null; 3607 flags = updateFlagsForPackage(flags, userId, packageName); 3608 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3609 false /* requireFullPermission */, false /* checkShell */, 3610 "getPackageGids"); 3611 3612 // reader 3613 synchronized (mPackages) { 3614 final PackageParser.Package p = mPackages.get(packageName); 3615 if (p != null && p.isMatch(flags)) { 3616 PackageSetting ps = (PackageSetting) p.mExtras; 3617 // TODO: Shouldn't this be checking for package installed state for userId and 3618 // return null? 3619 return ps.getPermissionsState().computeGids(userId); 3620 } 3621 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3622 final PackageSetting ps = mSettings.mPackages.get(packageName); 3623 if (ps != null && ps.isMatch(flags)) { 3624 return ps.getPermissionsState().computeGids(userId); 3625 } 3626 } 3627 } 3628 3629 return null; 3630 } 3631 3632 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3633 if (bp.perm != null) { 3634 return PackageParser.generatePermissionInfo(bp.perm, flags); 3635 } 3636 PermissionInfo pi = new PermissionInfo(); 3637 pi.name = bp.name; 3638 pi.packageName = bp.sourcePackage; 3639 pi.nonLocalizedLabel = bp.name; 3640 pi.protectionLevel = bp.protectionLevel; 3641 return pi; 3642 } 3643 3644 @Override 3645 public PermissionInfo getPermissionInfo(String name, int flags) { 3646 // reader 3647 synchronized (mPackages) { 3648 final BasePermission p = mSettings.mPermissions.get(name); 3649 if (p != null) { 3650 return generatePermissionInfo(p, flags); 3651 } 3652 return null; 3653 } 3654 } 3655 3656 @Override 3657 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3658 int flags) { 3659 // reader 3660 synchronized (mPackages) { 3661 if (group != null && !mPermissionGroups.containsKey(group)) { 3662 // This is thrown as NameNotFoundException 3663 return null; 3664 } 3665 3666 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3667 for (BasePermission p : mSettings.mPermissions.values()) { 3668 if (group == null) { 3669 if (p.perm == null || p.perm.info.group == null) { 3670 out.add(generatePermissionInfo(p, flags)); 3671 } 3672 } else { 3673 if (p.perm != null && group.equals(p.perm.info.group)) { 3674 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3675 } 3676 } 3677 } 3678 return new ParceledListSlice<>(out); 3679 } 3680 } 3681 3682 @Override 3683 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3684 // reader 3685 synchronized (mPackages) { 3686 return PackageParser.generatePermissionGroupInfo( 3687 mPermissionGroups.get(name), flags); 3688 } 3689 } 3690 3691 @Override 3692 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3693 // reader 3694 synchronized (mPackages) { 3695 final int N = mPermissionGroups.size(); 3696 ArrayList<PermissionGroupInfo> out 3697 = new ArrayList<PermissionGroupInfo>(N); 3698 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3699 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3700 } 3701 return new ParceledListSlice<>(out); 3702 } 3703 } 3704 3705 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3706 int uid, int userId) { 3707 if (!sUserManager.exists(userId)) return null; 3708 PackageSetting ps = mSettings.mPackages.get(packageName); 3709 if (ps != null) { 3710 if (filterSharedLibPackageLPr(ps, uid, userId)) { 3711 return null; 3712 } 3713 if (ps.pkg == null) { 3714 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3715 if (pInfo != null) { 3716 return pInfo.applicationInfo; 3717 } 3718 return null; 3719 } 3720 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 3721 ps.readUserState(userId), userId); 3722 if (ai != null) { 3723 rebaseEnabledOverlays(ai, userId); 3724 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 3725 } 3726 return ai; 3727 } 3728 return null; 3729 } 3730 3731 @Override 3732 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3733 if (!sUserManager.exists(userId)) return null; 3734 flags = updateFlagsForApplication(flags, userId, packageName); 3735 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3736 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3737 3738 // writer 3739 synchronized (mPackages) { 3740 // Normalize package name to handle renamed packages and static libs 3741 packageName = resolveInternalPackageNameLPr(packageName, 3742 PackageManager.VERSION_CODE_HIGHEST); 3743 3744 PackageParser.Package p = mPackages.get(packageName); 3745 if (DEBUG_PACKAGE_INFO) Log.v( 3746 TAG, "getApplicationInfo " + packageName 3747 + ": " + p); 3748 if (p != null) { 3749 PackageSetting ps = mSettings.mPackages.get(packageName); 3750 if (ps == null) return null; 3751 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 3752 return null; 3753 } 3754 // Note: isEnabledLP() does not apply here - always return info 3755 ApplicationInfo ai = PackageParser.generateApplicationInfo( 3756 p, flags, ps.readUserState(userId), userId); 3757 if (ai != null) { 3758 rebaseEnabledOverlays(ai, userId); 3759 ai.packageName = resolveExternalPackageNameLPr(p); 3760 } 3761 return ai; 3762 } 3763 if ("android".equals(packageName)||"system".equals(packageName)) { 3764 return mAndroidApplication; 3765 } 3766 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3767 // Already generates the external package name 3768 return generateApplicationInfoFromSettingsLPw(packageName, 3769 Binder.getCallingUid(), flags, userId); 3770 } 3771 } 3772 return null; 3773 } 3774 3775 private void rebaseEnabledOverlays(@NonNull ApplicationInfo ai, int userId) { 3776 List<String> paths = new ArrayList<>(); 3777 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 3778 mEnabledOverlayPaths.get(userId); 3779 if (userSpecificOverlays != null) { 3780 if (!"android".equals(ai.packageName)) { 3781 ArrayList<String> frameworkOverlays = userSpecificOverlays.get("android"); 3782 if (frameworkOverlays != null) { 3783 paths.addAll(frameworkOverlays); 3784 } 3785 } 3786 3787 ArrayList<String> appOverlays = userSpecificOverlays.get(ai.packageName); 3788 if (appOverlays != null) { 3789 paths.addAll(appOverlays); 3790 } 3791 } 3792 ai.resourceDirs = paths.size() > 0 ? paths.toArray(new String[paths.size()]) : null; 3793 } 3794 3795 private String normalizePackageNameLPr(String packageName) { 3796 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 3797 return normalizedPackageName != null ? normalizedPackageName : packageName; 3798 } 3799 3800 @Override 3801 public void deletePreloadsFileCache() { 3802 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 3803 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 3804 } 3805 File dir = Environment.getDataPreloadsFileCacheDirectory(); 3806 Slog.i(TAG, "Deleting preloaded file cache " + dir); 3807 FileUtils.deleteContents(dir); 3808 } 3809 3810 @Override 3811 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3812 final IPackageDataObserver observer) { 3813 mContext.enforceCallingOrSelfPermission( 3814 android.Manifest.permission.CLEAR_APP_CACHE, null); 3815 mHandler.post(() -> { 3816 boolean success = false; 3817 try { 3818 freeStorage(volumeUuid, freeStorageSize, 0); 3819 success = true; 3820 } catch (IOException e) { 3821 Slog.w(TAG, e); 3822 } 3823 if (observer != null) { 3824 try { 3825 observer.onRemoveCompleted(null, success); 3826 } catch (RemoteException e) { 3827 Slog.w(TAG, e); 3828 } 3829 } 3830 }); 3831 } 3832 3833 @Override 3834 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3835 final IntentSender pi) { 3836 mContext.enforceCallingOrSelfPermission( 3837 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 3838 mHandler.post(() -> { 3839 boolean success = false; 3840 try { 3841 freeStorage(volumeUuid, freeStorageSize, 0); 3842 success = true; 3843 } catch (IOException e) { 3844 Slog.w(TAG, e); 3845 } 3846 if (pi != null) { 3847 try { 3848 pi.sendIntent(null, success ? 1 : 0, null, null, null); 3849 } catch (SendIntentException e) { 3850 Slog.w(TAG, e); 3851 } 3852 } 3853 }); 3854 } 3855 3856 /** 3857 * Blocking call to clear various types of cached data across the system 3858 * until the requested bytes are available. 3859 */ 3860 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 3861 final StorageManager storage = mContext.getSystemService(StorageManager.class); 3862 final File file = storage.findPathForUuid(volumeUuid); 3863 if (file.getUsableSpace() >= bytes) return; 3864 3865 if (ENABLE_FREE_CACHE_V2) { 3866 final boolean aggressive = (storageFlags 3867 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 3868 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 3869 volumeUuid); 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 if (internalVolume && (aggressive || SystemProperties 3874 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 3875 deletePreloadsFileCache(); 3876 if (file.getUsableSpace() >= bytes) return; 3877 } 3878 3879 // 3. Consider parsed APK data (aggressive only) 3880 if (internalVolume && aggressive) { 3881 FileUtils.deleteContents(mCacheDir); 3882 if (file.getUsableSpace() >= bytes) return; 3883 } 3884 3885 // 4. Consider cached app data (above quotas) 3886 try { 3887 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 3888 } catch (InstallerException ignored) { 3889 } 3890 if (file.getUsableSpace() >= bytes) return; 3891 3892 // 5. Consider shared libraries with refcount=0 and age>2h 3893 // 6. Consider dexopt output (aggressive only) 3894 // 7. Consider ephemeral apps not used in last week 3895 3896 // 8. Consider cached app data (below quotas) 3897 try { 3898 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2 3899 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 3900 } catch (InstallerException ignored) { 3901 } 3902 if (file.getUsableSpace() >= bytes) return; 3903 3904 // 9. Consider DropBox entries 3905 // 10. Consider ephemeral cookies 3906 3907 } else { 3908 try { 3909 mInstaller.freeCache(volumeUuid, bytes, 0); 3910 } catch (InstallerException ignored) { 3911 } 3912 if (file.getUsableSpace() >= bytes) return; 3913 } 3914 3915 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 3916 } 3917 3918 /** 3919 * Update given flags based on encryption status of current user. 3920 */ 3921 private int updateFlags(int flags, int userId) { 3922 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3923 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3924 // Caller expressed an explicit opinion about what encryption 3925 // aware/unaware components they want to see, so fall through and 3926 // give them what they want 3927 } else { 3928 // Caller expressed no opinion, so match based on user state 3929 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3930 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3931 } else { 3932 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3933 } 3934 } 3935 return flags; 3936 } 3937 3938 private UserManagerInternal getUserManagerInternal() { 3939 if (mUserManagerInternal == null) { 3940 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3941 } 3942 return mUserManagerInternal; 3943 } 3944 3945 private DeviceIdleController.LocalService getDeviceIdleController() { 3946 if (mDeviceIdleController == null) { 3947 mDeviceIdleController = 3948 LocalServices.getService(DeviceIdleController.LocalService.class); 3949 } 3950 return mDeviceIdleController; 3951 } 3952 3953 /** 3954 * Update given flags when being used to request {@link PackageInfo}. 3955 */ 3956 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3957 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3958 boolean triaged = true; 3959 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3960 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3961 // Caller is asking for component details, so they'd better be 3962 // asking for specific encryption matching behavior, or be triaged 3963 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3964 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3965 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3966 triaged = false; 3967 } 3968 } 3969 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3970 | PackageManager.MATCH_SYSTEM_ONLY 3971 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3972 triaged = false; 3973 } 3974 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3975 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3976 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3977 + Debug.getCallers(5)); 3978 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3979 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3980 // If the caller wants all packages and has a restricted profile associated with it, 3981 // then match all users. This is to make sure that launchers that need to access work 3982 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3983 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3984 flags |= PackageManager.MATCH_ANY_USER; 3985 } 3986 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3987 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3988 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3989 } 3990 return updateFlags(flags, userId); 3991 } 3992 3993 /** 3994 * Update given flags when being used to request {@link ApplicationInfo}. 3995 */ 3996 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3997 return updateFlagsForPackage(flags, userId, cookie); 3998 } 3999 4000 /** 4001 * Update given flags when being used to request {@link ComponentInfo}. 4002 */ 4003 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4004 if (cookie instanceof Intent) { 4005 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4006 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4007 } 4008 } 4009 4010 boolean triaged = true; 4011 // Caller is asking for component details, so they'd better be 4012 // asking for specific encryption matching behavior, or be triaged 4013 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4014 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4015 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4016 triaged = false; 4017 } 4018 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4019 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4020 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4021 } 4022 4023 return updateFlags(flags, userId); 4024 } 4025 4026 /** 4027 * Update given intent when being used to request {@link ResolveInfo}. 4028 */ 4029 private Intent updateIntentForResolve(Intent intent) { 4030 if (intent.getSelector() != null) { 4031 intent = intent.getSelector(); 4032 } 4033 if (DEBUG_PREFERRED) { 4034 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4035 } 4036 return intent; 4037 } 4038 4039 /** 4040 * Update given flags when being used to request {@link ResolveInfo}. 4041 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4042 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4043 * flag set. However, this flag is only honoured in three circumstances: 4044 * <ul> 4045 * <li>when called from a system process</li> 4046 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4047 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4048 * action and a {@code android.intent.category.BROWSABLE} category</li> 4049 * </ul> 4050 */ 4051 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4052 boolean includeInstantApps) { 4053 // Safe mode means we shouldn't match any third-party components 4054 if (mSafeMode) { 4055 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4056 } 4057 if (getInstantAppPackageName(callingUid) != null) { 4058 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4059 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4060 flags |= PackageManager.MATCH_INSTANT; 4061 } else { 4062 // Otherwise, prevent leaking ephemeral components 4063 final boolean isSpecialProcess = 4064 callingUid == Process.SYSTEM_UID 4065 || callingUid == Process.SHELL_UID 4066 || callingUid == 0; 4067 final boolean allowMatchInstant = 4068 (includeInstantApps 4069 && Intent.ACTION_VIEW.equals(intent.getAction()) 4070 && intent.hasCategory(Intent.CATEGORY_BROWSABLE) 4071 && hasWebURI(intent)) 4072 || isSpecialProcess 4073 || mContext.checkCallingOrSelfPermission( 4074 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED; 4075 flags &= ~PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4076 if (!allowMatchInstant) { 4077 flags &= ~PackageManager.MATCH_INSTANT; 4078 } 4079 } 4080 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4081 } 4082 4083 @Override 4084 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4085 if (!sUserManager.exists(userId)) return null; 4086 flags = updateFlagsForComponent(flags, userId, component); 4087 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4088 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4089 synchronized (mPackages) { 4090 PackageParser.Activity a = mActivities.mActivities.get(component); 4091 4092 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4093 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4094 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4095 if (ps == null) return null; 4096 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 4097 userId); 4098 } 4099 if (mResolveComponentName.equals(component)) { 4100 return PackageParser.generateActivityInfo(mResolveActivity, flags, 4101 new PackageUserState(), userId); 4102 } 4103 } 4104 return null; 4105 } 4106 4107 @Override 4108 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4109 String resolvedType) { 4110 synchronized (mPackages) { 4111 if (component.equals(mResolveComponentName)) { 4112 // The resolver supports EVERYTHING! 4113 return true; 4114 } 4115 PackageParser.Activity a = mActivities.mActivities.get(component); 4116 if (a == null) { 4117 return false; 4118 } 4119 for (int i=0; i<a.intents.size(); i++) { 4120 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4121 intent.getData(), intent.getCategories(), TAG) >= 0) { 4122 return true; 4123 } 4124 } 4125 return false; 4126 } 4127 } 4128 4129 @Override 4130 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4131 if (!sUserManager.exists(userId)) return null; 4132 flags = updateFlagsForComponent(flags, userId, component); 4133 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4134 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4135 synchronized (mPackages) { 4136 PackageParser.Activity a = mReceivers.mActivities.get(component); 4137 if (DEBUG_PACKAGE_INFO) Log.v( 4138 TAG, "getReceiverInfo " + component + ": " + a); 4139 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4140 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4141 if (ps == null) return null; 4142 ActivityInfo ri = PackageParser.generateActivityInfo(a, flags, 4143 ps.readUserState(userId), userId); 4144 if (ri != null) { 4145 rebaseEnabledOverlays(ri.applicationInfo, userId); 4146 } 4147 return ri; 4148 } 4149 } 4150 return null; 4151 } 4152 4153 @Override 4154 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(int flags, int userId) { 4155 if (!sUserManager.exists(userId)) return null; 4156 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4157 4158 flags = updateFlagsForPackage(flags, userId, null); 4159 4160 final boolean canSeeStaticLibraries = 4161 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4162 == PERMISSION_GRANTED 4163 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4164 == PERMISSION_GRANTED 4165 || mContext.checkCallingOrSelfPermission(REQUEST_INSTALL_PACKAGES) 4166 == PERMISSION_GRANTED 4167 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4168 == PERMISSION_GRANTED; 4169 4170 synchronized (mPackages) { 4171 List<SharedLibraryInfo> result = null; 4172 4173 final int libCount = mSharedLibraries.size(); 4174 for (int i = 0; i < libCount; i++) { 4175 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4176 if (versionedLib == null) { 4177 continue; 4178 } 4179 4180 final int versionCount = versionedLib.size(); 4181 for (int j = 0; j < versionCount; j++) { 4182 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4183 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4184 break; 4185 } 4186 final long identity = Binder.clearCallingIdentity(); 4187 try { 4188 // TODO: We will change version code to long, so in the new API it is long 4189 PackageInfo packageInfo = getPackageInfoVersioned( 4190 libInfo.getDeclaringPackage(), flags, userId); 4191 if (packageInfo == null) { 4192 continue; 4193 } 4194 } finally { 4195 Binder.restoreCallingIdentity(identity); 4196 } 4197 4198 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4199 libInfo.getVersion(), libInfo.getType(), libInfo.getDeclaringPackage(), 4200 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId)); 4201 4202 if (result == null) { 4203 result = new ArrayList<>(); 4204 } 4205 result.add(resLibInfo); 4206 } 4207 } 4208 4209 return result != null ? new ParceledListSlice<>(result) : null; 4210 } 4211 } 4212 4213 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4214 SharedLibraryInfo libInfo, int flags, int userId) { 4215 List<VersionedPackage> versionedPackages = null; 4216 final int packageCount = mSettings.mPackages.size(); 4217 for (int i = 0; i < packageCount; i++) { 4218 PackageSetting ps = mSettings.mPackages.valueAt(i); 4219 4220 if (ps == null) { 4221 continue; 4222 } 4223 4224 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4225 continue; 4226 } 4227 4228 final String libName = libInfo.getName(); 4229 if (libInfo.isStatic()) { 4230 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4231 if (libIdx < 0) { 4232 continue; 4233 } 4234 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getVersion()) { 4235 continue; 4236 } 4237 if (versionedPackages == null) { 4238 versionedPackages = new ArrayList<>(); 4239 } 4240 // If the dependent is a static shared lib, use the public package name 4241 String dependentPackageName = ps.name; 4242 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4243 dependentPackageName = ps.pkg.manifestPackageName; 4244 } 4245 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4246 } else if (ps.pkg != null) { 4247 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4248 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4249 if (versionedPackages == null) { 4250 versionedPackages = new ArrayList<>(); 4251 } 4252 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4253 } 4254 } 4255 } 4256 4257 return versionedPackages; 4258 } 4259 4260 @Override 4261 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4262 if (!sUserManager.exists(userId)) return null; 4263 flags = updateFlagsForComponent(flags, userId, component); 4264 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4265 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4266 synchronized (mPackages) { 4267 PackageParser.Service s = mServices.mServices.get(component); 4268 if (DEBUG_PACKAGE_INFO) Log.v( 4269 TAG, "getServiceInfo " + component + ": " + s); 4270 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4271 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4272 if (ps == null) return null; 4273 ServiceInfo si = PackageParser.generateServiceInfo(s, flags, 4274 ps.readUserState(userId), userId); 4275 if (si != null) { 4276 rebaseEnabledOverlays(si.applicationInfo, userId); 4277 } 4278 return si; 4279 } 4280 } 4281 return null; 4282 } 4283 4284 @Override 4285 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4286 if (!sUserManager.exists(userId)) return null; 4287 flags = updateFlagsForComponent(flags, userId, component); 4288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4289 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4290 synchronized (mPackages) { 4291 PackageParser.Provider p = mProviders.mProviders.get(component); 4292 if (DEBUG_PACKAGE_INFO) Log.v( 4293 TAG, "getProviderInfo " + component + ": " + p); 4294 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4295 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4296 if (ps == null) return null; 4297 ProviderInfo pi = PackageParser.generateProviderInfo(p, flags, 4298 ps.readUserState(userId), userId); 4299 if (pi != null) { 4300 rebaseEnabledOverlays(pi.applicationInfo, userId); 4301 } 4302 return pi; 4303 } 4304 } 4305 return null; 4306 } 4307 4308 @Override 4309 public String[] getSystemSharedLibraryNames() { 4310 synchronized (mPackages) { 4311 Set<String> libs = null; 4312 final int libCount = mSharedLibraries.size(); 4313 for (int i = 0; i < libCount; i++) { 4314 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4315 if (versionedLib == null) { 4316 continue; 4317 } 4318 final int versionCount = versionedLib.size(); 4319 for (int j = 0; j < versionCount; j++) { 4320 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4321 if (!libEntry.info.isStatic()) { 4322 if (libs == null) { 4323 libs = new ArraySet<>(); 4324 } 4325 libs.add(libEntry.info.getName()); 4326 break; 4327 } 4328 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4329 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 4330 UserHandle.getUserId(Binder.getCallingUid()))) { 4331 if (libs == null) { 4332 libs = new ArraySet<>(); 4333 } 4334 libs.add(libEntry.info.getName()); 4335 break; 4336 } 4337 } 4338 } 4339 4340 if (libs != null) { 4341 String[] libsArray = new String[libs.size()]; 4342 libs.toArray(libsArray); 4343 return libsArray; 4344 } 4345 4346 return null; 4347 } 4348 } 4349 4350 @Override 4351 public @NonNull String getServicesSystemSharedLibraryPackageName() { 4352 synchronized (mPackages) { 4353 return mServicesSystemSharedLibraryPackageName; 4354 } 4355 } 4356 4357 @Override 4358 public @NonNull String getSharedSystemSharedLibraryPackageName() { 4359 synchronized (mPackages) { 4360 return mSharedSystemSharedLibraryPackageName; 4361 } 4362 } 4363 4364 private void updateSequenceNumberLP(String packageName, int[] userList) { 4365 for (int i = userList.length - 1; i >= 0; --i) { 4366 final int userId = userList[i]; 4367 SparseArray<String> changedPackages = mChangedPackages.get(userId); 4368 if (changedPackages == null) { 4369 changedPackages = new SparseArray<>(); 4370 mChangedPackages.put(userId, changedPackages); 4371 } 4372 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 4373 if (sequenceNumbers == null) { 4374 sequenceNumbers = new HashMap<>(); 4375 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 4376 } 4377 final Integer sequenceNumber = sequenceNumbers.get(packageName); 4378 if (sequenceNumber != null) { 4379 changedPackages.remove(sequenceNumber); 4380 } 4381 changedPackages.put(mChangedPackagesSequenceNumber, packageName); 4382 sequenceNumbers.put(packageName, mChangedPackagesSequenceNumber); 4383 } 4384 mChangedPackagesSequenceNumber++; 4385 } 4386 4387 @Override 4388 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 4389 synchronized (mPackages) { 4390 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 4391 return null; 4392 } 4393 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 4394 if (changedPackages == null) { 4395 return null; 4396 } 4397 final List<String> packageNames = 4398 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 4399 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 4400 final String packageName = changedPackages.get(i); 4401 if (packageName != null) { 4402 packageNames.add(packageName); 4403 } 4404 } 4405 return packageNames.isEmpty() 4406 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 4407 } 4408 } 4409 4410 @Override 4411 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 4412 ArrayList<FeatureInfo> res; 4413 synchronized (mAvailableFeatures) { 4414 res = new ArrayList<>(mAvailableFeatures.size() + 1); 4415 res.addAll(mAvailableFeatures.values()); 4416 } 4417 final FeatureInfo fi = new FeatureInfo(); 4418 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 4419 FeatureInfo.GL_ES_VERSION_UNDEFINED); 4420 res.add(fi); 4421 4422 return new ParceledListSlice<>(res); 4423 } 4424 4425 @Override 4426 public boolean hasSystemFeature(String name, int version) { 4427 synchronized (mAvailableFeatures) { 4428 final FeatureInfo feat = mAvailableFeatures.get(name); 4429 if (feat == null) { 4430 return false; 4431 } else { 4432 return feat.version >= version; 4433 } 4434 } 4435 } 4436 4437 @Override 4438 public int checkPermission(String permName, String pkgName, int userId) { 4439 if (!sUserManager.exists(userId)) { 4440 return PackageManager.PERMISSION_DENIED; 4441 } 4442 4443 synchronized (mPackages) { 4444 final PackageParser.Package p = mPackages.get(pkgName); 4445 if (p != null && p.mExtras != null) { 4446 final PackageSetting ps = (PackageSetting) p.mExtras; 4447 final PermissionsState permissionsState = ps.getPermissionsState(); 4448 if (permissionsState.hasPermission(permName, userId)) { 4449 return PackageManager.PERMISSION_GRANTED; 4450 } 4451 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4452 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4453 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4454 return PackageManager.PERMISSION_GRANTED; 4455 } 4456 } 4457 } 4458 4459 return PackageManager.PERMISSION_DENIED; 4460 } 4461 4462 @Override 4463 public int checkUidPermission(String permName, int uid) { 4464 final int userId = UserHandle.getUserId(uid); 4465 4466 if (!sUserManager.exists(userId)) { 4467 return PackageManager.PERMISSION_DENIED; 4468 } 4469 4470 synchronized (mPackages) { 4471 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4472 if (obj != null) { 4473 final SettingBase ps = (SettingBase) obj; 4474 final PermissionsState permissionsState = ps.getPermissionsState(); 4475 if (permissionsState.hasPermission(permName, userId)) { 4476 return PackageManager.PERMISSION_GRANTED; 4477 } 4478 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 4479 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 4480 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 4481 return PackageManager.PERMISSION_GRANTED; 4482 } 4483 } else { 4484 ArraySet<String> perms = mSystemPermissions.get(uid); 4485 if (perms != null) { 4486 if (perms.contains(permName)) { 4487 return PackageManager.PERMISSION_GRANTED; 4488 } 4489 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 4490 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 4491 return PackageManager.PERMISSION_GRANTED; 4492 } 4493 } 4494 } 4495 } 4496 4497 return PackageManager.PERMISSION_DENIED; 4498 } 4499 4500 @Override 4501 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 4502 if (UserHandle.getCallingUserId() != userId) { 4503 mContext.enforceCallingPermission( 4504 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4505 "isPermissionRevokedByPolicy for user " + userId); 4506 } 4507 4508 if (checkPermission(permission, packageName, userId) 4509 == PackageManager.PERMISSION_GRANTED) { 4510 return false; 4511 } 4512 4513 final long identity = Binder.clearCallingIdentity(); 4514 try { 4515 final int flags = getPermissionFlags(permission, packageName, userId); 4516 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 4517 } finally { 4518 Binder.restoreCallingIdentity(identity); 4519 } 4520 } 4521 4522 @Override 4523 public String getPermissionControllerPackageName() { 4524 synchronized (mPackages) { 4525 return mRequiredInstallerPackage; 4526 } 4527 } 4528 4529 /** 4530 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 4531 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 4532 * @param checkShell whether to prevent shell from access if there's a debugging restriction 4533 * @param message the message to log on security exception 4534 */ 4535 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 4536 boolean checkShell, String message) { 4537 if (userId < 0) { 4538 throw new IllegalArgumentException("Invalid userId " + userId); 4539 } 4540 if (checkShell) { 4541 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 4542 } 4543 if (userId == UserHandle.getUserId(callingUid)) return; 4544 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4545 if (requireFullPermission) { 4546 mContext.enforceCallingOrSelfPermission( 4547 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4548 } else { 4549 try { 4550 mContext.enforceCallingOrSelfPermission( 4551 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 4552 } catch (SecurityException se) { 4553 mContext.enforceCallingOrSelfPermission( 4554 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 4555 } 4556 } 4557 } 4558 } 4559 4560 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 4561 if (callingUid == Process.SHELL_UID) { 4562 if (userHandle >= 0 4563 && sUserManager.hasUserRestriction(restriction, userHandle)) { 4564 throw new SecurityException("Shell does not have permission to access user " 4565 + userHandle); 4566 } else if (userHandle < 0) { 4567 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 4568 + Debug.getCallers(3)); 4569 } 4570 } 4571 } 4572 4573 private BasePermission findPermissionTreeLP(String permName) { 4574 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 4575 if (permName.startsWith(bp.name) && 4576 permName.length() > bp.name.length() && 4577 permName.charAt(bp.name.length()) == '.') { 4578 return bp; 4579 } 4580 } 4581 return null; 4582 } 4583 4584 private BasePermission checkPermissionTreeLP(String permName) { 4585 if (permName != null) { 4586 BasePermission bp = findPermissionTreeLP(permName); 4587 if (bp != null) { 4588 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 4589 return bp; 4590 } 4591 throw new SecurityException("Calling uid " 4592 + Binder.getCallingUid() 4593 + " is not allowed to add to permission tree " 4594 + bp.name + " owned by uid " + bp.uid); 4595 } 4596 } 4597 throw new SecurityException("No permission tree found for " + permName); 4598 } 4599 4600 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4601 if (s1 == null) { 4602 return s2 == null; 4603 } 4604 if (s2 == null) { 4605 return false; 4606 } 4607 if (s1.getClass() != s2.getClass()) { 4608 return false; 4609 } 4610 return s1.equals(s2); 4611 } 4612 4613 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4614 if (pi1.icon != pi2.icon) return false; 4615 if (pi1.logo != pi2.logo) return false; 4616 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4617 if (!compareStrings(pi1.name, pi2.name)) return false; 4618 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4619 // We'll take care of setting this one. 4620 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4621 // These are not currently stored in settings. 4622 //if (!compareStrings(pi1.group, pi2.group)) return false; 4623 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4624 //if (pi1.labelRes != pi2.labelRes) return false; 4625 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4626 return true; 4627 } 4628 4629 int permissionInfoFootprint(PermissionInfo info) { 4630 int size = info.name.length(); 4631 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4632 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4633 return size; 4634 } 4635 4636 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4637 int size = 0; 4638 for (BasePermission perm : mSettings.mPermissions.values()) { 4639 if (perm.uid == tree.uid) { 4640 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4641 } 4642 } 4643 return size; 4644 } 4645 4646 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4647 // We calculate the max size of permissions defined by this uid and throw 4648 // if that plus the size of 'info' would exceed our stated maximum. 4649 if (tree.uid != Process.SYSTEM_UID) { 4650 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4651 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4652 throw new SecurityException("Permission tree size cap exceeded"); 4653 } 4654 } 4655 } 4656 4657 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4658 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4659 throw new SecurityException("Label must be specified in permission"); 4660 } 4661 BasePermission tree = checkPermissionTreeLP(info.name); 4662 BasePermission bp = mSettings.mPermissions.get(info.name); 4663 boolean added = bp == null; 4664 boolean changed = true; 4665 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4666 if (added) { 4667 enforcePermissionCapLocked(info, tree); 4668 bp = new BasePermission(info.name, tree.sourcePackage, 4669 BasePermission.TYPE_DYNAMIC); 4670 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4671 throw new SecurityException( 4672 "Not allowed to modify non-dynamic permission " 4673 + info.name); 4674 } else { 4675 if (bp.protectionLevel == fixedLevel 4676 && bp.perm.owner.equals(tree.perm.owner) 4677 && bp.uid == tree.uid 4678 && comparePermissionInfos(bp.perm.info, info)) { 4679 changed = false; 4680 } 4681 } 4682 bp.protectionLevel = fixedLevel; 4683 info = new PermissionInfo(info); 4684 info.protectionLevel = fixedLevel; 4685 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4686 bp.perm.info.packageName = tree.perm.info.packageName; 4687 bp.uid = tree.uid; 4688 if (added) { 4689 mSettings.mPermissions.put(info.name, bp); 4690 } 4691 if (changed) { 4692 if (!async) { 4693 mSettings.writeLPr(); 4694 } else { 4695 scheduleWriteSettingsLocked(); 4696 } 4697 } 4698 return added; 4699 } 4700 4701 @Override 4702 public boolean addPermission(PermissionInfo info) { 4703 synchronized (mPackages) { 4704 return addPermissionLocked(info, false); 4705 } 4706 } 4707 4708 @Override 4709 public boolean addPermissionAsync(PermissionInfo info) { 4710 synchronized (mPackages) { 4711 return addPermissionLocked(info, true); 4712 } 4713 } 4714 4715 @Override 4716 public void removePermission(String name) { 4717 synchronized (mPackages) { 4718 checkPermissionTreeLP(name); 4719 BasePermission bp = mSettings.mPermissions.get(name); 4720 if (bp != null) { 4721 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4722 throw new SecurityException( 4723 "Not allowed to modify non-dynamic permission " 4724 + name); 4725 } 4726 mSettings.mPermissions.remove(name); 4727 mSettings.writeLPr(); 4728 } 4729 } 4730 } 4731 4732 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4733 BasePermission bp) { 4734 int index = pkg.requestedPermissions.indexOf(bp.name); 4735 if (index == -1) { 4736 throw new SecurityException("Package " + pkg.packageName 4737 + " has not requested permission " + bp.name); 4738 } 4739 if (!bp.isRuntime() && !bp.isDevelopment()) { 4740 throw new SecurityException("Permission " + bp.name 4741 + " is not a changeable permission type"); 4742 } 4743 } 4744 4745 @Override 4746 public void grantRuntimePermission(String packageName, String name, final int userId) { 4747 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4748 } 4749 4750 private void grantRuntimePermission(String packageName, String name, final int userId, 4751 boolean overridePolicy) { 4752 if (!sUserManager.exists(userId)) { 4753 Log.e(TAG, "No such user:" + userId); 4754 return; 4755 } 4756 4757 mContext.enforceCallingOrSelfPermission( 4758 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4759 "grantRuntimePermission"); 4760 4761 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4762 true /* requireFullPermission */, true /* checkShell */, 4763 "grantRuntimePermission"); 4764 4765 final int uid; 4766 final SettingBase sb; 4767 4768 synchronized (mPackages) { 4769 final PackageParser.Package pkg = mPackages.get(packageName); 4770 if (pkg == null) { 4771 throw new IllegalArgumentException("Unknown package: " + packageName); 4772 } 4773 4774 final BasePermission bp = mSettings.mPermissions.get(name); 4775 if (bp == null) { 4776 throw new IllegalArgumentException("Unknown permission: " + name); 4777 } 4778 4779 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4780 4781 // If a permission review is required for legacy apps we represent 4782 // their permissions as always granted runtime ones since we need 4783 // to keep the review required permission flag per user while an 4784 // install permission's state is shared across all users. 4785 if (mPermissionReviewRequired 4786 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4787 && bp.isRuntime()) { 4788 return; 4789 } 4790 4791 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4792 sb = (SettingBase) pkg.mExtras; 4793 if (sb == null) { 4794 throw new IllegalArgumentException("Unknown package: " + packageName); 4795 } 4796 4797 final PermissionsState permissionsState = sb.getPermissionsState(); 4798 4799 final int flags = permissionsState.getPermissionFlags(name, userId); 4800 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4801 throw new SecurityException("Cannot grant system fixed permission " 4802 + name + " for package " + packageName); 4803 } 4804 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4805 throw new SecurityException("Cannot grant policy fixed permission " 4806 + name + " for package " + packageName); 4807 } 4808 4809 if (bp.isDevelopment()) { 4810 // Development permissions must be handled specially, since they are not 4811 // normal runtime permissions. For now they apply to all users. 4812 if (permissionsState.grantInstallPermission(bp) != 4813 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4814 scheduleWriteSettingsLocked(); 4815 } 4816 return; 4817 } 4818 4819 final PackageSetting ps = mSettings.mPackages.get(packageName); 4820 if (ps.getInstantApp(userId) && !bp.isInstant()) { 4821 throw new SecurityException("Cannot grant non-ephemeral permission" 4822 + name + " for package " + packageName); 4823 } 4824 4825 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4826 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4827 return; 4828 } 4829 4830 final int result = permissionsState.grantRuntimePermission(bp, userId); 4831 switch (result) { 4832 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4833 return; 4834 } 4835 4836 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4837 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4838 mHandler.post(new Runnable() { 4839 @Override 4840 public void run() { 4841 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4842 } 4843 }); 4844 } 4845 break; 4846 } 4847 4848 if (bp.isRuntime()) { 4849 logPermissionGranted(mContext, name, packageName); 4850 } 4851 4852 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4853 4854 // Not critical if that is lost - app has to request again. 4855 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4856 } 4857 4858 // Only need to do this if user is initialized. Otherwise it's a new user 4859 // and there are no processes running as the user yet and there's no need 4860 // to make an expensive call to remount processes for the changed permissions. 4861 if (READ_EXTERNAL_STORAGE.equals(name) 4862 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4863 final long token = Binder.clearCallingIdentity(); 4864 try { 4865 if (sUserManager.isInitialized(userId)) { 4866 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4867 StorageManagerInternal.class); 4868 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4869 } 4870 } finally { 4871 Binder.restoreCallingIdentity(token); 4872 } 4873 } 4874 } 4875 4876 @Override 4877 public void revokeRuntimePermission(String packageName, String name, int userId) { 4878 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4879 } 4880 4881 private void revokeRuntimePermission(String packageName, String name, int userId, 4882 boolean overridePolicy) { 4883 if (!sUserManager.exists(userId)) { 4884 Log.e(TAG, "No such user:" + userId); 4885 return; 4886 } 4887 4888 mContext.enforceCallingOrSelfPermission( 4889 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4890 "revokeRuntimePermission"); 4891 4892 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4893 true /* requireFullPermission */, true /* checkShell */, 4894 "revokeRuntimePermission"); 4895 4896 final int appId; 4897 4898 synchronized (mPackages) { 4899 final PackageParser.Package pkg = mPackages.get(packageName); 4900 if (pkg == null) { 4901 throw new IllegalArgumentException("Unknown package: " + packageName); 4902 } 4903 4904 final BasePermission bp = mSettings.mPermissions.get(name); 4905 if (bp == null) { 4906 throw new IllegalArgumentException("Unknown permission: " + name); 4907 } 4908 4909 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4910 4911 // If a permission review is required for legacy apps we represent 4912 // their permissions as always granted runtime ones since we need 4913 // to keep the review required permission flag per user while an 4914 // install permission's state is shared across all users. 4915 if (mPermissionReviewRequired 4916 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4917 && bp.isRuntime()) { 4918 return; 4919 } 4920 4921 SettingBase sb = (SettingBase) pkg.mExtras; 4922 if (sb == null) { 4923 throw new IllegalArgumentException("Unknown package: " + packageName); 4924 } 4925 4926 final PermissionsState permissionsState = sb.getPermissionsState(); 4927 4928 final int flags = permissionsState.getPermissionFlags(name, userId); 4929 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4930 throw new SecurityException("Cannot revoke system fixed permission " 4931 + name + " for package " + packageName); 4932 } 4933 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4934 throw new SecurityException("Cannot revoke policy fixed permission " 4935 + name + " for package " + packageName); 4936 } 4937 4938 if (bp.isDevelopment()) { 4939 // Development permissions must be handled specially, since they are not 4940 // normal runtime permissions. For now they apply to all users. 4941 if (permissionsState.revokeInstallPermission(bp) != 4942 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4943 scheduleWriteSettingsLocked(); 4944 } 4945 return; 4946 } 4947 4948 if (permissionsState.revokeRuntimePermission(bp, userId) == 4949 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4950 return; 4951 } 4952 4953 if (bp.isRuntime()) { 4954 logPermissionRevoked(mContext, name, packageName); 4955 } 4956 4957 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4958 4959 // Critical, after this call app should never have the permission. 4960 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4961 4962 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4963 } 4964 4965 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4966 } 4967 4968 /** 4969 * Get the first event id for the permission. 4970 * 4971 * <p>There are four events for each permission: <ul> 4972 * <li>Request permission: first id + 0</li> 4973 * <li>Grant permission: first id + 1</li> 4974 * <li>Request for permission denied: first id + 2</li> 4975 * <li>Revoke permission: first id + 3</li> 4976 * </ul></p> 4977 * 4978 * @param name name of the permission 4979 * 4980 * @return The first event id for the permission 4981 */ 4982 private static int getBaseEventId(@NonNull String name) { 4983 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4984 4985 if (eventIdIndex == -1) { 4986 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4987 || "user".equals(Build.TYPE)) { 4988 Log.i(TAG, "Unknown permission " + name); 4989 4990 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4991 } else { 4992 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4993 // 4994 // Also update 4995 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4996 // - metrics_constants.proto 4997 throw new IllegalStateException("Unknown permission " + name); 4998 } 4999 } 5000 5001 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 5002 } 5003 5004 /** 5005 * Log that a permission was revoked. 5006 * 5007 * @param context Context of the caller 5008 * @param name name of the permission 5009 * @param packageName package permission if for 5010 */ 5011 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 5012 @NonNull String packageName) { 5013 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 5014 } 5015 5016 /** 5017 * Log that a permission request was granted. 5018 * 5019 * @param context Context of the caller 5020 * @param name name of the permission 5021 * @param packageName package permission if for 5022 */ 5023 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 5024 @NonNull String packageName) { 5025 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 5026 } 5027 5028 @Override 5029 public void resetRuntimePermissions() { 5030 mContext.enforceCallingOrSelfPermission( 5031 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5032 "revokeRuntimePermission"); 5033 5034 int callingUid = Binder.getCallingUid(); 5035 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5036 mContext.enforceCallingOrSelfPermission( 5037 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5038 "resetRuntimePermissions"); 5039 } 5040 5041 synchronized (mPackages) { 5042 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 5043 for (int userId : UserManagerService.getInstance().getUserIds()) { 5044 final int packageCount = mPackages.size(); 5045 for (int i = 0; i < packageCount; i++) { 5046 PackageParser.Package pkg = mPackages.valueAt(i); 5047 if (!(pkg.mExtras instanceof PackageSetting)) { 5048 continue; 5049 } 5050 PackageSetting ps = (PackageSetting) pkg.mExtras; 5051 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5052 } 5053 } 5054 } 5055 } 5056 5057 @Override 5058 public int getPermissionFlags(String name, String packageName, int userId) { 5059 if (!sUserManager.exists(userId)) { 5060 return 0; 5061 } 5062 5063 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 5064 5065 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5066 true /* requireFullPermission */, false /* checkShell */, 5067 "getPermissionFlags"); 5068 5069 synchronized (mPackages) { 5070 final PackageParser.Package pkg = mPackages.get(packageName); 5071 if (pkg == null) { 5072 return 0; 5073 } 5074 5075 final BasePermission bp = mSettings.mPermissions.get(name); 5076 if (bp == null) { 5077 return 0; 5078 } 5079 5080 SettingBase sb = (SettingBase) pkg.mExtras; 5081 if (sb == null) { 5082 return 0; 5083 } 5084 5085 PermissionsState permissionsState = sb.getPermissionsState(); 5086 return permissionsState.getPermissionFlags(name, userId); 5087 } 5088 } 5089 5090 @Override 5091 public void updatePermissionFlags(String name, String packageName, int flagMask, 5092 int flagValues, int userId) { 5093 if (!sUserManager.exists(userId)) { 5094 return; 5095 } 5096 5097 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 5098 5099 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5100 true /* requireFullPermission */, true /* checkShell */, 5101 "updatePermissionFlags"); 5102 5103 // Only the system can change these flags and nothing else. 5104 if (getCallingUid() != Process.SYSTEM_UID) { 5105 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5106 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5107 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5108 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 5109 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 5110 } 5111 5112 synchronized (mPackages) { 5113 final PackageParser.Package pkg = mPackages.get(packageName); 5114 if (pkg == null) { 5115 throw new IllegalArgumentException("Unknown package: " + packageName); 5116 } 5117 5118 final BasePermission bp = mSettings.mPermissions.get(name); 5119 if (bp == null) { 5120 throw new IllegalArgumentException("Unknown permission: " + name); 5121 } 5122 5123 SettingBase sb = (SettingBase) pkg.mExtras; 5124 if (sb == null) { 5125 throw new IllegalArgumentException("Unknown package: " + packageName); 5126 } 5127 5128 PermissionsState permissionsState = sb.getPermissionsState(); 5129 5130 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 5131 5132 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 5133 // Install and runtime permissions are stored in different places, 5134 // so figure out what permission changed and persist the change. 5135 if (permissionsState.getInstallPermissionState(name) != null) { 5136 scheduleWriteSettingsLocked(); 5137 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 5138 || hadState) { 5139 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5140 } 5141 } 5142 } 5143 } 5144 5145 /** 5146 * Update the permission flags for all packages and runtime permissions of a user in order 5147 * to allow device or profile owner to remove POLICY_FIXED. 5148 */ 5149 @Override 5150 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5151 if (!sUserManager.exists(userId)) { 5152 return; 5153 } 5154 5155 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 5156 5157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5158 true /* requireFullPermission */, true /* checkShell */, 5159 "updatePermissionFlagsForAllApps"); 5160 5161 // Only the system can change system fixed flags. 5162 if (getCallingUid() != Process.SYSTEM_UID) { 5163 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5164 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 5165 } 5166 5167 synchronized (mPackages) { 5168 boolean changed = false; 5169 final int packageCount = mPackages.size(); 5170 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 5171 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 5172 SettingBase sb = (SettingBase) pkg.mExtras; 5173 if (sb == null) { 5174 continue; 5175 } 5176 PermissionsState permissionsState = sb.getPermissionsState(); 5177 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 5178 userId, flagMask, flagValues); 5179 } 5180 if (changed) { 5181 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5182 } 5183 } 5184 } 5185 5186 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 5187 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 5188 != PackageManager.PERMISSION_GRANTED 5189 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 5190 != PackageManager.PERMISSION_GRANTED) { 5191 throw new SecurityException(message + " requires " 5192 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 5193 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 5194 } 5195 } 5196 5197 @Override 5198 public boolean shouldShowRequestPermissionRationale(String permissionName, 5199 String packageName, int userId) { 5200 if (UserHandle.getCallingUserId() != userId) { 5201 mContext.enforceCallingPermission( 5202 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5203 "canShowRequestPermissionRationale for user " + userId); 5204 } 5205 5206 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5207 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5208 return false; 5209 } 5210 5211 if (checkPermission(permissionName, packageName, userId) 5212 == PackageManager.PERMISSION_GRANTED) { 5213 return false; 5214 } 5215 5216 final int flags; 5217 5218 final long identity = Binder.clearCallingIdentity(); 5219 try { 5220 flags = getPermissionFlags(permissionName, 5221 packageName, userId); 5222 } finally { 5223 Binder.restoreCallingIdentity(identity); 5224 } 5225 5226 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5227 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5228 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5229 5230 if ((flags & fixedFlags) != 0) { 5231 return false; 5232 } 5233 5234 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5235 } 5236 5237 @Override 5238 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5239 mContext.enforceCallingOrSelfPermission( 5240 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5241 "addOnPermissionsChangeListener"); 5242 5243 synchronized (mPackages) { 5244 mOnPermissionChangeListeners.addListenerLocked(listener); 5245 } 5246 } 5247 5248 @Override 5249 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5250 synchronized (mPackages) { 5251 mOnPermissionChangeListeners.removeListenerLocked(listener); 5252 } 5253 } 5254 5255 @Override 5256 public boolean isProtectedBroadcast(String actionName) { 5257 synchronized (mPackages) { 5258 if (mProtectedBroadcasts.contains(actionName)) { 5259 return true; 5260 } else if (actionName != null) { 5261 // TODO: remove these terrible hacks 5262 if (actionName.startsWith("android.net.netmon.lingerExpired") 5263 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5264 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5265 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5266 return true; 5267 } 5268 } 5269 } 5270 return false; 5271 } 5272 5273 @Override 5274 public int checkSignatures(String pkg1, String pkg2) { 5275 synchronized (mPackages) { 5276 final PackageParser.Package p1 = mPackages.get(pkg1); 5277 final PackageParser.Package p2 = mPackages.get(pkg2); 5278 if (p1 == null || p1.mExtras == null 5279 || p2 == null || p2.mExtras == null) { 5280 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5281 } 5282 return compareSignatures(p1.mSignatures, p2.mSignatures); 5283 } 5284 } 5285 5286 @Override 5287 public int checkUidSignatures(int uid1, int uid2) { 5288 // Map to base uids. 5289 uid1 = UserHandle.getAppId(uid1); 5290 uid2 = UserHandle.getAppId(uid2); 5291 // reader 5292 synchronized (mPackages) { 5293 Signature[] s1; 5294 Signature[] s2; 5295 Object obj = mSettings.getUserIdLPr(uid1); 5296 if (obj != null) { 5297 if (obj instanceof SharedUserSetting) { 5298 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5299 } else if (obj instanceof PackageSetting) { 5300 s1 = ((PackageSetting)obj).signatures.mSignatures; 5301 } else { 5302 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5303 } 5304 } else { 5305 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5306 } 5307 obj = mSettings.getUserIdLPr(uid2); 5308 if (obj != null) { 5309 if (obj instanceof SharedUserSetting) { 5310 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5311 } else if (obj instanceof PackageSetting) { 5312 s2 = ((PackageSetting)obj).signatures.mSignatures; 5313 } else { 5314 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5315 } 5316 } else { 5317 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5318 } 5319 return compareSignatures(s1, s2); 5320 } 5321 } 5322 5323 /** 5324 * This method should typically only be used when granting or revoking 5325 * permissions, since the app may immediately restart after this call. 5326 * <p> 5327 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5328 * guard your work against the app being relaunched. 5329 */ 5330 private void killUid(int appId, int userId, String reason) { 5331 final long identity = Binder.clearCallingIdentity(); 5332 try { 5333 IActivityManager am = ActivityManager.getService(); 5334 if (am != null) { 5335 try { 5336 am.killUid(appId, userId, reason); 5337 } catch (RemoteException e) { 5338 /* ignore - same process */ 5339 } 5340 } 5341 } finally { 5342 Binder.restoreCallingIdentity(identity); 5343 } 5344 } 5345 5346 /** 5347 * Compares two sets of signatures. Returns: 5348 * <br /> 5349 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 5350 * <br /> 5351 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 5352 * <br /> 5353 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 5354 * <br /> 5355 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 5356 * <br /> 5357 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 5358 */ 5359 static int compareSignatures(Signature[] s1, Signature[] s2) { 5360 if (s1 == null) { 5361 return s2 == null 5362 ? PackageManager.SIGNATURE_NEITHER_SIGNED 5363 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 5364 } 5365 5366 if (s2 == null) { 5367 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 5368 } 5369 5370 if (s1.length != s2.length) { 5371 return PackageManager.SIGNATURE_NO_MATCH; 5372 } 5373 5374 // Since both signature sets are of size 1, we can compare without HashSets. 5375 if (s1.length == 1) { 5376 return s1[0].equals(s2[0]) ? 5377 PackageManager.SIGNATURE_MATCH : 5378 PackageManager.SIGNATURE_NO_MATCH; 5379 } 5380 5381 ArraySet<Signature> set1 = new ArraySet<Signature>(); 5382 for (Signature sig : s1) { 5383 set1.add(sig); 5384 } 5385 ArraySet<Signature> set2 = new ArraySet<Signature>(); 5386 for (Signature sig : s2) { 5387 set2.add(sig); 5388 } 5389 // Make sure s2 contains all signatures in s1. 5390 if (set1.equals(set2)) { 5391 return PackageManager.SIGNATURE_MATCH; 5392 } 5393 return PackageManager.SIGNATURE_NO_MATCH; 5394 } 5395 5396 /** 5397 * If the database version for this type of package (internal storage or 5398 * external storage) is less than the version where package signatures 5399 * were updated, return true. 5400 */ 5401 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5402 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5403 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5404 } 5405 5406 /** 5407 * Used for backward compatibility to make sure any packages with 5408 * certificate chains get upgraded to the new style. {@code existingSigs} 5409 * will be in the old format (since they were stored on disk from before the 5410 * system upgrade) and {@code scannedSigs} will be in the newer format. 5411 */ 5412 private int compareSignaturesCompat(PackageSignatures existingSigs, 5413 PackageParser.Package scannedPkg) { 5414 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 5415 return PackageManager.SIGNATURE_NO_MATCH; 5416 } 5417 5418 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 5419 for (Signature sig : existingSigs.mSignatures) { 5420 existingSet.add(sig); 5421 } 5422 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 5423 for (Signature sig : scannedPkg.mSignatures) { 5424 try { 5425 Signature[] chainSignatures = sig.getChainSignatures(); 5426 for (Signature chainSig : chainSignatures) { 5427 scannedCompatSet.add(chainSig); 5428 } 5429 } catch (CertificateEncodingException e) { 5430 scannedCompatSet.add(sig); 5431 } 5432 } 5433 /* 5434 * Make sure the expanded scanned set contains all signatures in the 5435 * existing one. 5436 */ 5437 if (scannedCompatSet.equals(existingSet)) { 5438 // Migrate the old signatures to the new scheme. 5439 existingSigs.assignSignatures(scannedPkg.mSignatures); 5440 // The new KeySets will be re-added later in the scanning process. 5441 synchronized (mPackages) { 5442 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 5443 } 5444 return PackageManager.SIGNATURE_MATCH; 5445 } 5446 return PackageManager.SIGNATURE_NO_MATCH; 5447 } 5448 5449 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5450 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5451 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5452 } 5453 5454 private int compareSignaturesRecover(PackageSignatures existingSigs, 5455 PackageParser.Package scannedPkg) { 5456 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 5457 return PackageManager.SIGNATURE_NO_MATCH; 5458 } 5459 5460 String msg = null; 5461 try { 5462 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 5463 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 5464 + scannedPkg.packageName); 5465 return PackageManager.SIGNATURE_MATCH; 5466 } 5467 } catch (CertificateException e) { 5468 msg = e.getMessage(); 5469 } 5470 5471 logCriticalInfo(Log.INFO, 5472 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 5473 return PackageManager.SIGNATURE_NO_MATCH; 5474 } 5475 5476 @Override 5477 public List<String> getAllPackages() { 5478 synchronized (mPackages) { 5479 return new ArrayList<String>(mPackages.keySet()); 5480 } 5481 } 5482 5483 @Override 5484 public String[] getPackagesForUid(int uid) { 5485 final int userId = UserHandle.getUserId(uid); 5486 uid = UserHandle.getAppId(uid); 5487 // reader 5488 synchronized (mPackages) { 5489 Object obj = mSettings.getUserIdLPr(uid); 5490 if (obj instanceof SharedUserSetting) { 5491 final SharedUserSetting sus = (SharedUserSetting) obj; 5492 final int N = sus.packages.size(); 5493 String[] res = new String[N]; 5494 final Iterator<PackageSetting> it = sus.packages.iterator(); 5495 int i = 0; 5496 while (it.hasNext()) { 5497 PackageSetting ps = it.next(); 5498 if (ps.getInstalled(userId)) { 5499 res[i++] = ps.name; 5500 } else { 5501 res = ArrayUtils.removeElement(String.class, res, res[i]); 5502 } 5503 } 5504 return res; 5505 } else if (obj instanceof PackageSetting) { 5506 final PackageSetting ps = (PackageSetting) obj; 5507 if (ps.getInstalled(userId)) { 5508 return new String[]{ps.name}; 5509 } 5510 } 5511 } 5512 return null; 5513 } 5514 5515 @Override 5516 public String getNameForUid(int uid) { 5517 // reader 5518 synchronized (mPackages) { 5519 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5520 if (obj instanceof SharedUserSetting) { 5521 final SharedUserSetting sus = (SharedUserSetting) obj; 5522 return sus.name + ":" + sus.userId; 5523 } else if (obj instanceof PackageSetting) { 5524 final PackageSetting ps = (PackageSetting) obj; 5525 return ps.name; 5526 } 5527 } 5528 return null; 5529 } 5530 5531 @Override 5532 public int getUidForSharedUser(String sharedUserName) { 5533 if(sharedUserName == null) { 5534 return -1; 5535 } 5536 // reader 5537 synchronized (mPackages) { 5538 SharedUserSetting suid; 5539 try { 5540 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5541 if (suid != null) { 5542 return suid.userId; 5543 } 5544 } catch (PackageManagerException ignore) { 5545 // can't happen, but, still need to catch it 5546 } 5547 return -1; 5548 } 5549 } 5550 5551 @Override 5552 public int getFlagsForUid(int uid) { 5553 synchronized (mPackages) { 5554 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5555 if (obj instanceof SharedUserSetting) { 5556 final SharedUserSetting sus = (SharedUserSetting) obj; 5557 return sus.pkgFlags; 5558 } else if (obj instanceof PackageSetting) { 5559 final PackageSetting ps = (PackageSetting) obj; 5560 return ps.pkgFlags; 5561 } 5562 } 5563 return 0; 5564 } 5565 5566 @Override 5567 public int getPrivateFlagsForUid(int uid) { 5568 synchronized (mPackages) { 5569 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5570 if (obj instanceof SharedUserSetting) { 5571 final SharedUserSetting sus = (SharedUserSetting) obj; 5572 return sus.pkgPrivateFlags; 5573 } else if (obj instanceof PackageSetting) { 5574 final PackageSetting ps = (PackageSetting) obj; 5575 return ps.pkgPrivateFlags; 5576 } 5577 } 5578 return 0; 5579 } 5580 5581 @Override 5582 public boolean isUidPrivileged(int uid) { 5583 uid = UserHandle.getAppId(uid); 5584 // reader 5585 synchronized (mPackages) { 5586 Object obj = mSettings.getUserIdLPr(uid); 5587 if (obj instanceof SharedUserSetting) { 5588 final SharedUserSetting sus = (SharedUserSetting) obj; 5589 final Iterator<PackageSetting> it = sus.packages.iterator(); 5590 while (it.hasNext()) { 5591 if (it.next().isPrivileged()) { 5592 return true; 5593 } 5594 } 5595 } else if (obj instanceof PackageSetting) { 5596 final PackageSetting ps = (PackageSetting) obj; 5597 return ps.isPrivileged(); 5598 } 5599 } 5600 return false; 5601 } 5602 5603 @Override 5604 public String[] getAppOpPermissionPackages(String permissionName) { 5605 synchronized (mPackages) { 5606 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 5607 if (pkgs == null) { 5608 return null; 5609 } 5610 return pkgs.toArray(new String[pkgs.size()]); 5611 } 5612 } 5613 5614 @Override 5615 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5616 int flags, int userId) { 5617 return resolveIntentInternal( 5618 intent, resolvedType, flags, userId, false /*includeInstantApps*/); 5619 } 5620 5621 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5622 int flags, int userId, boolean includeInstantApps) { 5623 try { 5624 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5625 5626 if (!sUserManager.exists(userId)) return null; 5627 final int callingUid = Binder.getCallingUid(); 5628 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 5629 enforceCrossUserPermission(callingUid, userId, 5630 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5631 5632 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5633 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5634 flags, userId, includeInstantApps); 5635 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5636 5637 final ResolveInfo bestChoice = 5638 chooseBestActivity(intent, resolvedType, flags, query, userId); 5639 return bestChoice; 5640 } finally { 5641 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5642 } 5643 } 5644 5645 @Override 5646 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5647 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5648 throw new SecurityException( 5649 "findPersistentPreferredActivity can only be run by the system"); 5650 } 5651 if (!sUserManager.exists(userId)) { 5652 return null; 5653 } 5654 final int callingUid = Binder.getCallingUid(); 5655 intent = updateIntentForResolve(intent); 5656 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5657 final int flags = updateFlagsForResolve( 5658 0, userId, intent, callingUid, false /*includeInstantApps*/); 5659 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5660 userId); 5661 synchronized (mPackages) { 5662 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5663 userId); 5664 } 5665 } 5666 5667 @Override 5668 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5669 IntentFilter filter, int match, ComponentName activity) { 5670 final int userId = UserHandle.getCallingUserId(); 5671 if (DEBUG_PREFERRED) { 5672 Log.v(TAG, "setLastChosenActivity intent=" + intent 5673 + " resolvedType=" + resolvedType 5674 + " flags=" + flags 5675 + " filter=" + filter 5676 + " match=" + match 5677 + " activity=" + activity); 5678 filter.dump(new PrintStreamPrinter(System.out), " "); 5679 } 5680 intent.setComponent(null); 5681 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5682 userId); 5683 // Find any earlier preferred or last chosen entries and nuke them 5684 findPreferredActivity(intent, resolvedType, 5685 flags, query, 0, false, true, false, userId); 5686 // Add the new activity as the last chosen for this filter 5687 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5688 "Setting last chosen"); 5689 } 5690 5691 @Override 5692 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5693 final int userId = UserHandle.getCallingUserId(); 5694 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5695 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5696 userId); 5697 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5698 false, false, false, userId); 5699 } 5700 5701 /** 5702 * Returns whether or not instant apps have been disabled remotely. 5703 */ 5704 private boolean isEphemeralDisabled() { 5705 return mEphemeralAppsDisabled; 5706 } 5707 5708 private boolean isEphemeralAllowed( 5709 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5710 boolean skipPackageCheck) { 5711 final int callingUser = UserHandle.getCallingUserId(); 5712 if (callingUser != UserHandle.USER_SYSTEM) { 5713 return false; 5714 } 5715 if (mInstantAppResolverConnection == null) { 5716 return false; 5717 } 5718 if (mInstantAppInstallerActivity == null) { 5719 return false; 5720 } 5721 if (intent.getComponent() != null) { 5722 return false; 5723 } 5724 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5725 return false; 5726 } 5727 if (!skipPackageCheck && intent.getPackage() != null) { 5728 return false; 5729 } 5730 final boolean isWebUri = hasWebURI(intent); 5731 if (!isWebUri || intent.getData().getHost() == null) { 5732 return false; 5733 } 5734 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5735 // Or if there's already an ephemeral app installed that handles the action 5736 synchronized (mPackages) { 5737 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5738 for (int n = 0; n < count; n++) { 5739 final ResolveInfo info = resolvedActivities.get(n); 5740 final String packageName = info.activityInfo.packageName; 5741 final PackageSetting ps = mSettings.mPackages.get(packageName); 5742 if (ps != null) { 5743 // only check domain verification status if the app is not a browser 5744 if (!info.handleAllWebDataURI) { 5745 // Try to get the status from User settings first 5746 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5747 final int status = (int) (packedStatus >> 32); 5748 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5749 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5750 if (DEBUG_EPHEMERAL) { 5751 Slog.v(TAG, "DENY instant app;" 5752 + " pkg: " + packageName + ", status: " + status); 5753 } 5754 return false; 5755 } 5756 } 5757 if (ps.getInstantApp(userId)) { 5758 if (DEBUG_EPHEMERAL) { 5759 Slog.v(TAG, "DENY instant app installed;" 5760 + " pkg: " + packageName); 5761 } 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 final int callingUid = Binder.getCallingUid(); 5936 flags = updateFlagsForResolve( 5937 flags, userId, intent, callingUid, false /*includeInstantApps*/); 5938 intent = updateIntentForResolve(intent); 5939 // writer 5940 synchronized (mPackages) { 5941 // Try to find a matching persistent preferred activity. 5942 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5943 debug, userId); 5944 5945 // If a persistent preferred activity matched, use it. 5946 if (pri != null) { 5947 return pri; 5948 } 5949 5950 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5951 // Get the list of preferred activities that handle the intent 5952 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5953 List<PreferredActivity> prefs = pir != null 5954 ? pir.queryIntent(intent, resolvedType, 5955 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5956 userId) 5957 : null; 5958 if (prefs != null && prefs.size() > 0) { 5959 boolean changed = false; 5960 try { 5961 // First figure out how good the original match set is. 5962 // We will only allow preferred activities that came 5963 // from the same match quality. 5964 int match = 0; 5965 5966 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5967 5968 final int N = query.size(); 5969 for (int j=0; j<N; j++) { 5970 final ResolveInfo ri = query.get(j); 5971 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5972 + ": 0x" + Integer.toHexString(match)); 5973 if (ri.match > match) { 5974 match = ri.match; 5975 } 5976 } 5977 5978 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5979 + Integer.toHexString(match)); 5980 5981 match &= IntentFilter.MATCH_CATEGORY_MASK; 5982 final int M = prefs.size(); 5983 for (int i=0; i<M; i++) { 5984 final PreferredActivity pa = prefs.get(i); 5985 if (DEBUG_PREFERRED || debug) { 5986 Slog.v(TAG, "Checking PreferredActivity ds=" 5987 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5988 + "\n component=" + pa.mPref.mComponent); 5989 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5990 } 5991 if (pa.mPref.mMatch != match) { 5992 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5993 + Integer.toHexString(pa.mPref.mMatch)); 5994 continue; 5995 } 5996 // If it's not an "always" type preferred activity and that's what we're 5997 // looking for, skip it. 5998 if (always && !pa.mPref.mAlways) { 5999 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6000 continue; 6001 } 6002 final ActivityInfo ai = getActivityInfo( 6003 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6004 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6005 userId); 6006 if (DEBUG_PREFERRED || debug) { 6007 Slog.v(TAG, "Found preferred activity:"); 6008 if (ai != null) { 6009 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6010 } else { 6011 Slog.v(TAG, " null"); 6012 } 6013 } 6014 if (ai == null) { 6015 // This previously registered preferred activity 6016 // component is no longer known. Most likely an update 6017 // to the app was installed and in the new version this 6018 // component no longer exists. Clean it up by removing 6019 // it from the preferred activities list, and skip it. 6020 Slog.w(TAG, "Removing dangling preferred activity: " 6021 + pa.mPref.mComponent); 6022 pir.removeFilter(pa); 6023 changed = true; 6024 continue; 6025 } 6026 for (int j=0; j<N; j++) { 6027 final ResolveInfo ri = query.get(j); 6028 if (!ri.activityInfo.applicationInfo.packageName 6029 .equals(ai.applicationInfo.packageName)) { 6030 continue; 6031 } 6032 if (!ri.activityInfo.name.equals(ai.name)) { 6033 continue; 6034 } 6035 6036 if (removeMatches) { 6037 pir.removeFilter(pa); 6038 changed = true; 6039 if (DEBUG_PREFERRED) { 6040 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6041 } 6042 break; 6043 } 6044 6045 // Okay we found a previously set preferred or last chosen app. 6046 // If the result set is different from when this 6047 // was created, we need to clear it and re-ask the 6048 // user their preference, if we're looking for an "always" type entry. 6049 if (always && !pa.mPref.sameSet(query)) { 6050 Slog.i(TAG, "Result set changed, dropping preferred activity for " 6051 + intent + " type " + resolvedType); 6052 if (DEBUG_PREFERRED) { 6053 Slog.v(TAG, "Removing preferred activity since set changed " 6054 + pa.mPref.mComponent); 6055 } 6056 pir.removeFilter(pa); 6057 // Re-add the filter as a "last chosen" entry (!always) 6058 PreferredActivity lastChosen = new PreferredActivity( 6059 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6060 pir.addFilter(lastChosen); 6061 changed = true; 6062 return null; 6063 } 6064 6065 // Yay! Either the set matched or we're looking for the last chosen 6066 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6067 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6068 return ri; 6069 } 6070 } 6071 } finally { 6072 if (changed) { 6073 if (DEBUG_PREFERRED) { 6074 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6075 } 6076 scheduleWritePackageRestrictionsLocked(userId); 6077 } 6078 } 6079 } 6080 } 6081 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6082 return null; 6083 } 6084 6085 /* 6086 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6087 */ 6088 @Override 6089 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6090 int targetUserId) { 6091 mContext.enforceCallingOrSelfPermission( 6092 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6093 List<CrossProfileIntentFilter> matches = 6094 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6095 if (matches != null) { 6096 int size = matches.size(); 6097 for (int i = 0; i < size; i++) { 6098 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6099 } 6100 } 6101 if (hasWebURI(intent)) { 6102 // cross-profile app linking works only towards the parent. 6103 final int callingUid = Binder.getCallingUid(); 6104 final UserInfo parent = getProfileParent(sourceUserId); 6105 synchronized(mPackages) { 6106 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6107 false /*includeInstantApps*/); 6108 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6109 intent, resolvedType, flags, sourceUserId, parent.id); 6110 return xpDomainInfo != null; 6111 } 6112 } 6113 return false; 6114 } 6115 6116 private UserInfo getProfileParent(int userId) { 6117 final long identity = Binder.clearCallingIdentity(); 6118 try { 6119 return sUserManager.getProfileParent(userId); 6120 } finally { 6121 Binder.restoreCallingIdentity(identity); 6122 } 6123 } 6124 6125 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6126 String resolvedType, int userId) { 6127 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6128 if (resolver != null) { 6129 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6130 } 6131 return null; 6132 } 6133 6134 @Override 6135 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6136 String resolvedType, int flags, int userId) { 6137 try { 6138 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6139 6140 return new ParceledListSlice<>( 6141 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6142 } finally { 6143 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6144 } 6145 } 6146 6147 /** 6148 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6149 * instant, returns {@code null}. 6150 */ 6151 private String getInstantAppPackageName(int callingUid) { 6152 // If the caller is an isolated app use the owner's uid for the lookup. 6153 if (Process.isIsolated(callingUid)) { 6154 callingUid = mIsolatedOwners.get(callingUid); 6155 } 6156 final int appId = UserHandle.getAppId(callingUid); 6157 synchronized (mPackages) { 6158 final Object obj = mSettings.getUserIdLPr(appId); 6159 if (obj instanceof PackageSetting) { 6160 final PackageSetting ps = (PackageSetting) obj; 6161 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6162 return isInstantApp ? ps.pkg.packageName : null; 6163 } 6164 } 6165 return null; 6166 } 6167 6168 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6169 String resolvedType, int flags, int userId) { 6170 return queryIntentActivitiesInternal(intent, resolvedType, flags, userId, false); 6171 } 6172 6173 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6174 String resolvedType, int flags, int userId, boolean includeInstantApps) { 6175 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6176 final int callingUid = Binder.getCallingUid(); 6177 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6178 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 6179 enforceCrossUserPermission(callingUid, userId, 6180 false /* requireFullPermission */, false /* checkShell */, 6181 "query intent activities"); 6182 ComponentName comp = intent.getComponent(); 6183 if (comp == null) { 6184 if (intent.getSelector() != null) { 6185 intent = intent.getSelector(); 6186 comp = intent.getComponent(); 6187 } 6188 } 6189 6190 if (comp != null) { 6191 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6192 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6193 if (ai != null) { 6194 // When specifying an explicit component, we prevent the activity from being 6195 // used when either 1) the calling package is normal and the activity is within 6196 // an ephemeral application or 2) the calling package is ephemeral and the 6197 // activity is not visible to ephemeral applications. 6198 final boolean matchInstantApp = 6199 (flags & PackageManager.MATCH_INSTANT) != 0; 6200 final boolean matchVisibleToInstantAppOnly = 6201 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6202 final boolean isCallerInstantApp = 6203 instantAppPkgName != null; 6204 final boolean isTargetSameInstantApp = 6205 comp.getPackageName().equals(instantAppPkgName); 6206 final boolean isTargetInstantApp = 6207 (ai.applicationInfo.privateFlags 6208 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6209 final boolean isTargetHiddenFromInstantApp = 6210 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 6211 final boolean blockResolution = 6212 !isTargetSameInstantApp 6213 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6214 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6215 && isTargetHiddenFromInstantApp)); 6216 if (!blockResolution) { 6217 final ResolveInfo ri = new ResolveInfo(); 6218 ri.activityInfo = ai; 6219 list.add(ri); 6220 } 6221 } 6222 return applyPostResolutionFilter(list, instantAppPkgName); 6223 } 6224 6225 // reader 6226 boolean sortResult = false; 6227 boolean addEphemeral = false; 6228 List<ResolveInfo> result; 6229 final String pkgName = intent.getPackage(); 6230 final boolean ephemeralDisabled = isEphemeralDisabled(); 6231 synchronized (mPackages) { 6232 if (pkgName == null) { 6233 List<CrossProfileIntentFilter> matchingFilters = 6234 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6235 // Check for results that need to skip the current profile. 6236 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6237 resolvedType, flags, userId); 6238 if (xpResolveInfo != null) { 6239 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6240 xpResult.add(xpResolveInfo); 6241 return applyPostResolutionFilter( 6242 filterIfNotSystemUser(xpResult, userId), instantAppPkgName); 6243 } 6244 6245 // Check for results in the current profile. 6246 result = filterIfNotSystemUser(mActivities.queryIntent( 6247 intent, resolvedType, flags, userId), userId); 6248 addEphemeral = !ephemeralDisabled 6249 && isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 6250 // Check for cross profile results. 6251 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6252 xpResolveInfo = queryCrossProfileIntents( 6253 matchingFilters, intent, resolvedType, flags, userId, 6254 hasNonNegativePriorityResult); 6255 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6256 boolean isVisibleToUser = filterIfNotSystemUser( 6257 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6258 if (isVisibleToUser) { 6259 result.add(xpResolveInfo); 6260 sortResult = true; 6261 } 6262 } 6263 if (hasWebURI(intent)) { 6264 CrossProfileDomainInfo xpDomainInfo = null; 6265 final UserInfo parent = getProfileParent(userId); 6266 if (parent != null) { 6267 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6268 flags, userId, parent.id); 6269 } 6270 if (xpDomainInfo != null) { 6271 if (xpResolveInfo != null) { 6272 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6273 // in the result. 6274 result.remove(xpResolveInfo); 6275 } 6276 if (result.size() == 0 && !addEphemeral) { 6277 // No result in current profile, but found candidate in parent user. 6278 // And we are not going to add emphemeral app, so we can return the 6279 // result straight away. 6280 result.add(xpDomainInfo.resolveInfo); 6281 return applyPostResolutionFilter(result, instantAppPkgName); 6282 } 6283 } else if (result.size() <= 1 && !addEphemeral) { 6284 // No result in parent user and <= 1 result in current profile, and we 6285 // are not going to add emphemeral app, so we can return the result without 6286 // further processing. 6287 return applyPostResolutionFilter(result, instantAppPkgName); 6288 } 6289 // We have more than one candidate (combining results from current and parent 6290 // profile), so we need filtering and sorting. 6291 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6292 intent, flags, result, xpDomainInfo, userId); 6293 sortResult = true; 6294 } 6295 } else { 6296 final PackageParser.Package pkg = mPackages.get(pkgName); 6297 if (pkg != null) { 6298 return applyPostResolutionFilter(filterIfNotSystemUser( 6299 mActivities.queryIntentForPackage( 6300 intent, resolvedType, flags, pkg.activities, userId), 6301 userId), instantAppPkgName); 6302 } else { 6303 // the caller wants to resolve for a particular package; however, there 6304 // were no installed results, so, try to find an ephemeral result 6305 addEphemeral = !ephemeralDisabled 6306 && isEphemeralAllowed( 6307 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6308 result = new ArrayList<ResolveInfo>(); 6309 } 6310 } 6311 } 6312 if (addEphemeral) { 6313 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6314 final InstantAppRequest requestObject = new InstantAppRequest( 6315 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6316 null /*callingPackage*/, userId); 6317 final AuxiliaryResolveInfo auxiliaryResponse = 6318 InstantAppResolver.doInstantAppResolutionPhaseOne( 6319 mContext, mInstantAppResolverConnection, requestObject); 6320 if (auxiliaryResponse != null) { 6321 if (DEBUG_EPHEMERAL) { 6322 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6323 } 6324 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6325 ephemeralInstaller.activityInfo = new ActivityInfo(mInstantAppInstallerActivity); 6326 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6327 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6328 // make sure this resolver is the default 6329 ephemeralInstaller.isDefault = true; 6330 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6331 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6332 // add a non-generic filter 6333 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6334 ephemeralInstaller.filter.addDataPath( 6335 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6336 ephemeralInstaller.instantAppAvailable = true; 6337 result.add(ephemeralInstaller); 6338 } 6339 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6340 } 6341 if (sortResult) { 6342 Collections.sort(result, mResolvePrioritySorter); 6343 } 6344 return applyPostResolutionFilter(result, instantAppPkgName); 6345 } 6346 6347 private static class CrossProfileDomainInfo { 6348 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6349 ResolveInfo resolveInfo; 6350 /* Best domain verification status of the activities found in the other profile */ 6351 int bestDomainVerificationStatus; 6352 } 6353 6354 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6355 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6356 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6357 sourceUserId)) { 6358 return null; 6359 } 6360 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6361 resolvedType, flags, parentUserId); 6362 6363 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6364 return null; 6365 } 6366 CrossProfileDomainInfo result = null; 6367 int size = resultTargetUser.size(); 6368 for (int i = 0; i < size; i++) { 6369 ResolveInfo riTargetUser = resultTargetUser.get(i); 6370 // Intent filter verification is only for filters that specify a host. So don't return 6371 // those that handle all web uris. 6372 if (riTargetUser.handleAllWebDataURI) { 6373 continue; 6374 } 6375 String packageName = riTargetUser.activityInfo.packageName; 6376 PackageSetting ps = mSettings.mPackages.get(packageName); 6377 if (ps == null) { 6378 continue; 6379 } 6380 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6381 int status = (int)(verificationState >> 32); 6382 if (result == null) { 6383 result = new CrossProfileDomainInfo(); 6384 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6385 sourceUserId, parentUserId); 6386 result.bestDomainVerificationStatus = status; 6387 } else { 6388 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6389 result.bestDomainVerificationStatus); 6390 } 6391 } 6392 // Don't consider matches with status NEVER across profiles. 6393 if (result != null && result.bestDomainVerificationStatus 6394 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6395 return null; 6396 } 6397 return result; 6398 } 6399 6400 /** 6401 * Verification statuses are ordered from the worse to the best, except for 6402 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6403 */ 6404 private int bestDomainVerificationStatus(int status1, int status2) { 6405 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6406 return status2; 6407 } 6408 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6409 return status1; 6410 } 6411 return (int) MathUtils.max(status1, status2); 6412 } 6413 6414 private boolean isUserEnabled(int userId) { 6415 long callingId = Binder.clearCallingIdentity(); 6416 try { 6417 UserInfo userInfo = sUserManager.getUserInfo(userId); 6418 return userInfo != null && userInfo.isEnabled(); 6419 } finally { 6420 Binder.restoreCallingIdentity(callingId); 6421 } 6422 } 6423 6424 /** 6425 * Filter out activities with systemUserOnly flag set, when current user is not System. 6426 * 6427 * @return filtered list 6428 */ 6429 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6430 if (userId == UserHandle.USER_SYSTEM) { 6431 return resolveInfos; 6432 } 6433 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6434 ResolveInfo info = resolveInfos.get(i); 6435 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6436 resolveInfos.remove(i); 6437 } 6438 } 6439 return resolveInfos; 6440 } 6441 6442 /** 6443 * Filters out ephemeral activities. 6444 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6445 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6446 * 6447 * @param resolveInfos The pre-filtered list of resolved activities 6448 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6449 * is performed. 6450 * @return A filtered list of resolved activities. 6451 */ 6452 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6453 String ephemeralPkgName) { 6454 // TODO: When adding on-demand split support for non-instant apps, remove this check 6455 // and always apply post filtering 6456 if (ephemeralPkgName == null) { 6457 return resolveInfos; 6458 } 6459 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6460 final ResolveInfo info = resolveInfos.get(i); 6461 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6462 // allow activities that are defined in the provided package 6463 if (isEphemeralApp && ephemeralPkgName.equals(info.activityInfo.packageName)) { 6464 if (info.activityInfo.splitName != null 6465 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6466 info.activityInfo.splitName)) { 6467 // requested activity is defined in a split that hasn't been installed yet. 6468 // add the installer to the resolve list 6469 if (DEBUG_EPHEMERAL) { 6470 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6471 } 6472 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6473 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6474 info.activityInfo.packageName, info.activityInfo.splitName, 6475 info.activityInfo.applicationInfo.versionCode); 6476 // make sure this resolver is the default 6477 installerInfo.isDefault = true; 6478 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6479 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6480 // add a non-generic filter 6481 installerInfo.filter = new IntentFilter(); 6482 // load resources from the correct package 6483 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6484 resolveInfos.set(i, installerInfo); 6485 } 6486 continue; 6487 } 6488 // allow activities that have been explicitly exposed to ephemeral apps 6489 if (!isEphemeralApp 6490 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 6491 continue; 6492 } 6493 resolveInfos.remove(i); 6494 } 6495 return resolveInfos; 6496 } 6497 6498 /** 6499 * @param resolveInfos list of resolve infos in descending priority order 6500 * @return if the list contains a resolve info with non-negative priority 6501 */ 6502 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6503 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6504 } 6505 6506 private static boolean hasWebURI(Intent intent) { 6507 if (intent.getData() == null) { 6508 return false; 6509 } 6510 final String scheme = intent.getScheme(); 6511 if (TextUtils.isEmpty(scheme)) { 6512 return false; 6513 } 6514 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6515 } 6516 6517 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6518 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6519 int userId) { 6520 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6521 6522 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6523 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6524 candidates.size()); 6525 } 6526 6527 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6528 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6529 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6530 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6531 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6532 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6533 6534 synchronized (mPackages) { 6535 final int count = candidates.size(); 6536 // First, try to use linked apps. Partition the candidates into four lists: 6537 // one for the final results, one for the "do not use ever", one for "undefined status" 6538 // and finally one for "browser app type". 6539 for (int n=0; n<count; n++) { 6540 ResolveInfo info = candidates.get(n); 6541 String packageName = info.activityInfo.packageName; 6542 PackageSetting ps = mSettings.mPackages.get(packageName); 6543 if (ps != null) { 6544 // Add to the special match all list (Browser use case) 6545 if (info.handleAllWebDataURI) { 6546 matchAllList.add(info); 6547 continue; 6548 } 6549 // Try to get the status from User settings first 6550 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6551 int status = (int)(packedStatus >> 32); 6552 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6553 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6554 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6555 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6556 + " : linkgen=" + linkGeneration); 6557 } 6558 // Use link-enabled generation as preferredOrder, i.e. 6559 // prefer newly-enabled over earlier-enabled. 6560 info.preferredOrder = linkGeneration; 6561 alwaysList.add(info); 6562 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6563 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6564 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6565 } 6566 neverList.add(info); 6567 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6568 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6569 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6570 } 6571 alwaysAskList.add(info); 6572 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6573 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6574 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6575 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6576 } 6577 undefinedList.add(info); 6578 } 6579 } 6580 } 6581 6582 // We'll want to include browser possibilities in a few cases 6583 boolean includeBrowser = false; 6584 6585 // First try to add the "always" resolution(s) for the current user, if any 6586 if (alwaysList.size() > 0) { 6587 result.addAll(alwaysList); 6588 } else { 6589 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6590 result.addAll(undefinedList); 6591 // Maybe add one for the other profile. 6592 if (xpDomainInfo != null && ( 6593 xpDomainInfo.bestDomainVerificationStatus 6594 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6595 result.add(xpDomainInfo.resolveInfo); 6596 } 6597 includeBrowser = true; 6598 } 6599 6600 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6601 // If there were 'always' entries their preferred order has been set, so we also 6602 // back that off to make the alternatives equivalent 6603 if (alwaysAskList.size() > 0) { 6604 for (ResolveInfo i : result) { 6605 i.preferredOrder = 0; 6606 } 6607 result.addAll(alwaysAskList); 6608 includeBrowser = true; 6609 } 6610 6611 if (includeBrowser) { 6612 // Also add browsers (all of them or only the default one) 6613 if (DEBUG_DOMAIN_VERIFICATION) { 6614 Slog.v(TAG, " ...including browsers in candidate set"); 6615 } 6616 if ((matchFlags & MATCH_ALL) != 0) { 6617 result.addAll(matchAllList); 6618 } else { 6619 // Browser/generic handling case. If there's a default browser, go straight 6620 // to that (but only if there is no other higher-priority match). 6621 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6622 int maxMatchPrio = 0; 6623 ResolveInfo defaultBrowserMatch = null; 6624 final int numCandidates = matchAllList.size(); 6625 for (int n = 0; n < numCandidates; n++) { 6626 ResolveInfo info = matchAllList.get(n); 6627 // track the highest overall match priority... 6628 if (info.priority > maxMatchPrio) { 6629 maxMatchPrio = info.priority; 6630 } 6631 // ...and the highest-priority default browser match 6632 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6633 if (defaultBrowserMatch == null 6634 || (defaultBrowserMatch.priority < info.priority)) { 6635 if (debug) { 6636 Slog.v(TAG, "Considering default browser match " + info); 6637 } 6638 defaultBrowserMatch = info; 6639 } 6640 } 6641 } 6642 if (defaultBrowserMatch != null 6643 && defaultBrowserMatch.priority >= maxMatchPrio 6644 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6645 { 6646 if (debug) { 6647 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6648 } 6649 result.add(defaultBrowserMatch); 6650 } else { 6651 result.addAll(matchAllList); 6652 } 6653 } 6654 6655 // If there is nothing selected, add all candidates and remove the ones that the user 6656 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6657 if (result.size() == 0) { 6658 result.addAll(candidates); 6659 result.removeAll(neverList); 6660 } 6661 } 6662 } 6663 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6664 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6665 result.size()); 6666 for (ResolveInfo info : result) { 6667 Slog.v(TAG, " + " + info.activityInfo); 6668 } 6669 } 6670 return result; 6671 } 6672 6673 // Returns a packed value as a long: 6674 // 6675 // high 'int'-sized word: link status: undefined/ask/never/always. 6676 // low 'int'-sized word: relative priority among 'always' results. 6677 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6678 long result = ps.getDomainVerificationStatusForUser(userId); 6679 // if none available, get the master status 6680 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6681 if (ps.getIntentFilterVerificationInfo() != null) { 6682 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6683 } 6684 } 6685 return result; 6686 } 6687 6688 private ResolveInfo querySkipCurrentProfileIntents( 6689 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6690 int flags, int sourceUserId) { 6691 if (matchingFilters != null) { 6692 int size = matchingFilters.size(); 6693 for (int i = 0; i < size; i ++) { 6694 CrossProfileIntentFilter filter = matchingFilters.get(i); 6695 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6696 // Checking if there are activities in the target user that can handle the 6697 // intent. 6698 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6699 resolvedType, flags, sourceUserId); 6700 if (resolveInfo != null) { 6701 return resolveInfo; 6702 } 6703 } 6704 } 6705 } 6706 return null; 6707 } 6708 6709 // Return matching ResolveInfo in target user if any. 6710 private ResolveInfo queryCrossProfileIntents( 6711 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6712 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6713 if (matchingFilters != null) { 6714 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6715 // match the same intent. For performance reasons, it is better not to 6716 // run queryIntent twice for the same userId 6717 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6718 int size = matchingFilters.size(); 6719 for (int i = 0; i < size; i++) { 6720 CrossProfileIntentFilter filter = matchingFilters.get(i); 6721 int targetUserId = filter.getTargetUserId(); 6722 boolean skipCurrentProfile = 6723 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6724 boolean skipCurrentProfileIfNoMatchFound = 6725 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6726 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6727 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6728 // Checking if there are activities in the target user that can handle the 6729 // intent. 6730 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6731 resolvedType, flags, sourceUserId); 6732 if (resolveInfo != null) return resolveInfo; 6733 alreadyTriedUserIds.put(targetUserId, true); 6734 } 6735 } 6736 } 6737 return null; 6738 } 6739 6740 /** 6741 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6742 * will forward the intent to the filter's target user. 6743 * Otherwise, returns null. 6744 */ 6745 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6746 String resolvedType, int flags, int sourceUserId) { 6747 int targetUserId = filter.getTargetUserId(); 6748 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6749 resolvedType, flags, targetUserId); 6750 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 6751 // If all the matches in the target profile are suspended, return null. 6752 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 6753 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 6754 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 6755 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 6756 targetUserId); 6757 } 6758 } 6759 } 6760 return null; 6761 } 6762 6763 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 6764 int sourceUserId, int targetUserId) { 6765 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 6766 long ident = Binder.clearCallingIdentity(); 6767 boolean targetIsProfile; 6768 try { 6769 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 6770 } finally { 6771 Binder.restoreCallingIdentity(ident); 6772 } 6773 String className; 6774 if (targetIsProfile) { 6775 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 6776 } else { 6777 className = FORWARD_INTENT_TO_PARENT; 6778 } 6779 ComponentName forwardingActivityComponentName = new ComponentName( 6780 mAndroidApplication.packageName, className); 6781 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 6782 sourceUserId); 6783 if (!targetIsProfile) { 6784 forwardingActivityInfo.showUserIcon = targetUserId; 6785 forwardingResolveInfo.noResourceId = true; 6786 } 6787 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 6788 forwardingResolveInfo.priority = 0; 6789 forwardingResolveInfo.preferredOrder = 0; 6790 forwardingResolveInfo.match = 0; 6791 forwardingResolveInfo.isDefault = true; 6792 forwardingResolveInfo.filter = filter; 6793 forwardingResolveInfo.targetUserId = targetUserId; 6794 return forwardingResolveInfo; 6795 } 6796 6797 @Override 6798 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 6799 Intent[] specifics, String[] specificTypes, Intent intent, 6800 String resolvedType, int flags, int userId) { 6801 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 6802 specificTypes, intent, resolvedType, flags, userId)); 6803 } 6804 6805 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6806 Intent[] specifics, String[] specificTypes, Intent intent, 6807 String resolvedType, int flags, int userId) { 6808 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6809 final int callingUid = Binder.getCallingUid(); 6810 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6811 false /*includeInstantApps*/); 6812 enforceCrossUserPermission(callingUid, userId, 6813 false /*requireFullPermission*/, false /*checkShell*/, 6814 "query intent activity options"); 6815 final String resultsAction = intent.getAction(); 6816 6817 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6818 | PackageManager.GET_RESOLVED_FILTER, userId); 6819 6820 if (DEBUG_INTENT_MATCHING) { 6821 Log.v(TAG, "Query " + intent + ": " + results); 6822 } 6823 6824 int specificsPos = 0; 6825 int N; 6826 6827 // todo: note that the algorithm used here is O(N^2). This 6828 // isn't a problem in our current environment, but if we start running 6829 // into situations where we have more than 5 or 10 matches then this 6830 // should probably be changed to something smarter... 6831 6832 // First we go through and resolve each of the specific items 6833 // that were supplied, taking care of removing any corresponding 6834 // duplicate items in the generic resolve list. 6835 if (specifics != null) { 6836 for (int i=0; i<specifics.length; i++) { 6837 final Intent sintent = specifics[i]; 6838 if (sintent == null) { 6839 continue; 6840 } 6841 6842 if (DEBUG_INTENT_MATCHING) { 6843 Log.v(TAG, "Specific #" + i + ": " + sintent); 6844 } 6845 6846 String action = sintent.getAction(); 6847 if (resultsAction != null && resultsAction.equals(action)) { 6848 // If this action was explicitly requested, then don't 6849 // remove things that have it. 6850 action = null; 6851 } 6852 6853 ResolveInfo ri = null; 6854 ActivityInfo ai = null; 6855 6856 ComponentName comp = sintent.getComponent(); 6857 if (comp == null) { 6858 ri = resolveIntent( 6859 sintent, 6860 specificTypes != null ? specificTypes[i] : null, 6861 flags, userId); 6862 if (ri == null) { 6863 continue; 6864 } 6865 if (ri == mResolveInfo) { 6866 // ACK! Must do something better with this. 6867 } 6868 ai = ri.activityInfo; 6869 comp = new ComponentName(ai.applicationInfo.packageName, 6870 ai.name); 6871 } else { 6872 ai = getActivityInfo(comp, flags, userId); 6873 if (ai == null) { 6874 continue; 6875 } 6876 } 6877 6878 // Look for any generic query activities that are duplicates 6879 // of this specific one, and remove them from the results. 6880 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6881 N = results.size(); 6882 int j; 6883 for (j=specificsPos; j<N; j++) { 6884 ResolveInfo sri = results.get(j); 6885 if ((sri.activityInfo.name.equals(comp.getClassName()) 6886 && sri.activityInfo.applicationInfo.packageName.equals( 6887 comp.getPackageName())) 6888 || (action != null && sri.filter.matchAction(action))) { 6889 results.remove(j); 6890 if (DEBUG_INTENT_MATCHING) Log.v( 6891 TAG, "Removing duplicate item from " + j 6892 + " due to specific " + specificsPos); 6893 if (ri == null) { 6894 ri = sri; 6895 } 6896 j--; 6897 N--; 6898 } 6899 } 6900 6901 // Add this specific item to its proper place. 6902 if (ri == null) { 6903 ri = new ResolveInfo(); 6904 ri.activityInfo = ai; 6905 } 6906 results.add(specificsPos, ri); 6907 ri.specificIndex = i; 6908 specificsPos++; 6909 } 6910 } 6911 6912 // Now we go through the remaining generic results and remove any 6913 // duplicate actions that are found here. 6914 N = results.size(); 6915 for (int i=specificsPos; i<N-1; i++) { 6916 final ResolveInfo rii = results.get(i); 6917 if (rii.filter == null) { 6918 continue; 6919 } 6920 6921 // Iterate over all of the actions of this result's intent 6922 // filter... typically this should be just one. 6923 final Iterator<String> it = rii.filter.actionsIterator(); 6924 if (it == null) { 6925 continue; 6926 } 6927 while (it.hasNext()) { 6928 final String action = it.next(); 6929 if (resultsAction != null && resultsAction.equals(action)) { 6930 // If this action was explicitly requested, then don't 6931 // remove things that have it. 6932 continue; 6933 } 6934 for (int j=i+1; j<N; j++) { 6935 final ResolveInfo rij = results.get(j); 6936 if (rij.filter != null && rij.filter.hasAction(action)) { 6937 results.remove(j); 6938 if (DEBUG_INTENT_MATCHING) Log.v( 6939 TAG, "Removing duplicate item from " + j 6940 + " due to action " + action + " at " + i); 6941 j--; 6942 N--; 6943 } 6944 } 6945 } 6946 6947 // If the caller didn't request filter information, drop it now 6948 // so we don't have to marshall/unmarshall it. 6949 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6950 rii.filter = null; 6951 } 6952 } 6953 6954 // Filter out the caller activity if so requested. 6955 if (caller != null) { 6956 N = results.size(); 6957 for (int i=0; i<N; i++) { 6958 ActivityInfo ainfo = results.get(i).activityInfo; 6959 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6960 && caller.getClassName().equals(ainfo.name)) { 6961 results.remove(i); 6962 break; 6963 } 6964 } 6965 } 6966 6967 // If the caller didn't request filter information, 6968 // drop them now so we don't have to 6969 // marshall/unmarshall it. 6970 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6971 N = results.size(); 6972 for (int i=0; i<N; i++) { 6973 results.get(i).filter = null; 6974 } 6975 } 6976 6977 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6978 return results; 6979 } 6980 6981 @Override 6982 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6983 String resolvedType, int flags, int userId) { 6984 return new ParceledListSlice<>( 6985 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6986 } 6987 6988 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6989 String resolvedType, int flags, int userId) { 6990 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6991 final int callingUid = Binder.getCallingUid(); 6992 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 6993 false /*includeInstantApps*/); 6994 ComponentName comp = intent.getComponent(); 6995 if (comp == null) { 6996 if (intent.getSelector() != null) { 6997 intent = intent.getSelector(); 6998 comp = intent.getComponent(); 6999 } 7000 } 7001 if (comp != null) { 7002 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7003 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7004 if (ai != null) { 7005 ResolveInfo ri = new ResolveInfo(); 7006 ri.activityInfo = ai; 7007 list.add(ri); 7008 } 7009 return list; 7010 } 7011 7012 // reader 7013 synchronized (mPackages) { 7014 String pkgName = intent.getPackage(); 7015 if (pkgName == null) { 7016 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 7017 } 7018 final PackageParser.Package pkg = mPackages.get(pkgName); 7019 if (pkg != null) { 7020 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 7021 userId); 7022 } 7023 return Collections.emptyList(); 7024 } 7025 } 7026 7027 @Override 7028 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7029 final int callingUid = Binder.getCallingUid(); 7030 return resolveServiceInternal( 7031 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7032 } 7033 7034 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7035 int userId, int callingUid, boolean includeInstantApps) { 7036 if (!sUserManager.exists(userId)) return null; 7037 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7038 List<ResolveInfo> query = queryIntentServicesInternal( 7039 intent, resolvedType, flags, userId, callingUid, includeInstantApps); 7040 if (query != null) { 7041 if (query.size() >= 1) { 7042 // If there is more than one service with the same priority, 7043 // just arbitrarily pick the first one. 7044 return query.get(0); 7045 } 7046 } 7047 return null; 7048 } 7049 7050 @Override 7051 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7052 String resolvedType, int flags, int userId) { 7053 final int callingUid = Binder.getCallingUid(); 7054 return new ParceledListSlice<>(queryIntentServicesInternal( 7055 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7056 } 7057 7058 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7059 String resolvedType, int flags, int userId, int callingUid, 7060 boolean includeInstantApps) { 7061 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7062 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7063 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7064 ComponentName comp = intent.getComponent(); 7065 if (comp == null) { 7066 if (intent.getSelector() != null) { 7067 intent = intent.getSelector(); 7068 comp = intent.getComponent(); 7069 } 7070 } 7071 if (comp != null) { 7072 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7073 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7074 if (si != null) { 7075 // When specifying an explicit component, we prevent the service from being 7076 // used when either 1) the service is in an instant application and the 7077 // caller is not the same instant application or 2) the calling package is 7078 // ephemeral and the activity is not visible to ephemeral applications. 7079 final boolean matchVisibleToInstantAppOnly = 7080 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7081 final boolean isCallerInstantApp = 7082 instantAppPkgName != null; 7083 final boolean isTargetSameInstantApp = 7084 comp.getPackageName().equals(instantAppPkgName); 7085 final boolean isTargetHiddenFromInstantApp = 7086 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_EPHEMERAL) == 0; 7087 final boolean blockResolution = 7088 !isTargetSameInstantApp 7089 && ((matchVisibleToInstantAppOnly && isCallerInstantApp 7090 && isTargetHiddenFromInstantApp)); 7091 if (!blockResolution) { 7092 final ResolveInfo ri = new ResolveInfo(); 7093 ri.serviceInfo = si; 7094 list.add(ri); 7095 } 7096 } 7097 return list; 7098 } 7099 7100 // reader 7101 synchronized (mPackages) { 7102 String pkgName = intent.getPackage(); 7103 if (pkgName == null) { 7104 return applyPostServiceResolutionFilter( 7105 mServices.queryIntent(intent, resolvedType, flags, userId), 7106 instantAppPkgName); 7107 } 7108 final PackageParser.Package pkg = mPackages.get(pkgName); 7109 if (pkg != null) { 7110 return applyPostServiceResolutionFilter( 7111 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7112 userId), 7113 instantAppPkgName); 7114 } 7115 return Collections.emptyList(); 7116 } 7117 } 7118 7119 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7120 String instantAppPkgName) { 7121 // TODO: When adding on-demand split support for non-instant apps, remove this check 7122 // and always apply post filtering 7123 if (instantAppPkgName == null) { 7124 return resolveInfos; 7125 } 7126 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7127 final ResolveInfo info = resolveInfos.get(i); 7128 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7129 // allow services that are defined in the provided package 7130 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7131 if (info.serviceInfo.splitName != null 7132 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7133 info.serviceInfo.splitName)) { 7134 // requested service is defined in a split that hasn't been installed yet. 7135 // add the installer to the resolve list 7136 if (DEBUG_EPHEMERAL) { 7137 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7138 } 7139 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7140 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7141 info.serviceInfo.packageName, info.serviceInfo.splitName, 7142 info.serviceInfo.applicationInfo.versionCode); 7143 // make sure this resolver is the default 7144 installerInfo.isDefault = true; 7145 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7146 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7147 // add a non-generic filter 7148 installerInfo.filter = new IntentFilter(); 7149 // load resources from the correct package 7150 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7151 resolveInfos.set(i, installerInfo); 7152 } 7153 continue; 7154 } 7155 // allow services that have been explicitly exposed to ephemeral apps 7156 if (!isEphemeralApp 7157 && ((info.serviceInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_EPHEMERAL) != 0)) { 7158 continue; 7159 } 7160 resolveInfos.remove(i); 7161 } 7162 return resolveInfos; 7163 } 7164 7165 @Override 7166 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7167 String resolvedType, int flags, int userId) { 7168 return new ParceledListSlice<>( 7169 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7170 } 7171 7172 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7173 Intent intent, String resolvedType, int flags, int userId) { 7174 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7175 final int callingUid = Binder.getCallingUid(); 7176 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7177 false /*includeInstantApps*/); 7178 ComponentName comp = intent.getComponent(); 7179 if (comp == null) { 7180 if (intent.getSelector() != null) { 7181 intent = intent.getSelector(); 7182 comp = intent.getComponent(); 7183 } 7184 } 7185 if (comp != null) { 7186 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7187 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7188 if (pi != null) { 7189 final ResolveInfo ri = new ResolveInfo(); 7190 ri.providerInfo = pi; 7191 list.add(ri); 7192 } 7193 return list; 7194 } 7195 7196 // reader 7197 synchronized (mPackages) { 7198 String pkgName = intent.getPackage(); 7199 if (pkgName == null) { 7200 return mProviders.queryIntent(intent, resolvedType, flags, userId); 7201 } 7202 final PackageParser.Package pkg = mPackages.get(pkgName); 7203 if (pkg != null) { 7204 return mProviders.queryIntentForPackage( 7205 intent, resolvedType, flags, pkg.providers, userId); 7206 } 7207 return Collections.emptyList(); 7208 } 7209 } 7210 7211 @Override 7212 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7213 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7214 flags = updateFlagsForPackage(flags, userId, null); 7215 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7216 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7217 true /* requireFullPermission */, false /* checkShell */, 7218 "get installed packages"); 7219 7220 // writer 7221 synchronized (mPackages) { 7222 ArrayList<PackageInfo> list; 7223 if (listUninstalled) { 7224 list = new ArrayList<>(mSettings.mPackages.size()); 7225 for (PackageSetting ps : mSettings.mPackages.values()) { 7226 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7227 continue; 7228 } 7229 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7230 if (pi != null) { 7231 list.add(pi); 7232 } 7233 } 7234 } else { 7235 list = new ArrayList<>(mPackages.size()); 7236 for (PackageParser.Package p : mPackages.values()) { 7237 if (filterSharedLibPackageLPr((PackageSetting) p.mExtras, 7238 Binder.getCallingUid(), userId)) { 7239 continue; 7240 } 7241 final PackageInfo pi = generatePackageInfo((PackageSetting) 7242 p.mExtras, flags, userId); 7243 if (pi != null) { 7244 list.add(pi); 7245 } 7246 } 7247 } 7248 7249 return new ParceledListSlice<>(list); 7250 } 7251 } 7252 7253 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7254 String[] permissions, boolean[] tmp, int flags, int userId) { 7255 int numMatch = 0; 7256 final PermissionsState permissionsState = ps.getPermissionsState(); 7257 for (int i=0; i<permissions.length; i++) { 7258 final String permission = permissions[i]; 7259 if (permissionsState.hasPermission(permission, userId)) { 7260 tmp[i] = true; 7261 numMatch++; 7262 } else { 7263 tmp[i] = false; 7264 } 7265 } 7266 if (numMatch == 0) { 7267 return; 7268 } 7269 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7270 7271 // The above might return null in cases of uninstalled apps or install-state 7272 // skew across users/profiles. 7273 if (pi != null) { 7274 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7275 if (numMatch == permissions.length) { 7276 pi.requestedPermissions = permissions; 7277 } else { 7278 pi.requestedPermissions = new String[numMatch]; 7279 numMatch = 0; 7280 for (int i=0; i<permissions.length; i++) { 7281 if (tmp[i]) { 7282 pi.requestedPermissions[numMatch] = permissions[i]; 7283 numMatch++; 7284 } 7285 } 7286 } 7287 } 7288 list.add(pi); 7289 } 7290 } 7291 7292 @Override 7293 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7294 String[] permissions, int flags, int userId) { 7295 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7296 flags = updateFlagsForPackage(flags, userId, permissions); 7297 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7298 true /* requireFullPermission */, false /* checkShell */, 7299 "get packages holding permissions"); 7300 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7301 7302 // writer 7303 synchronized (mPackages) { 7304 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7305 boolean[] tmpBools = new boolean[permissions.length]; 7306 if (listUninstalled) { 7307 for (PackageSetting ps : mSettings.mPackages.values()) { 7308 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7309 userId); 7310 } 7311 } else { 7312 for (PackageParser.Package pkg : mPackages.values()) { 7313 PackageSetting ps = (PackageSetting)pkg.mExtras; 7314 if (ps != null) { 7315 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7316 userId); 7317 } 7318 } 7319 } 7320 7321 return new ParceledListSlice<PackageInfo>(list); 7322 } 7323 } 7324 7325 @Override 7326 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7327 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7328 flags = updateFlagsForApplication(flags, userId, null); 7329 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7330 7331 // writer 7332 synchronized (mPackages) { 7333 ArrayList<ApplicationInfo> list; 7334 if (listUninstalled) { 7335 list = new ArrayList<>(mSettings.mPackages.size()); 7336 for (PackageSetting ps : mSettings.mPackages.values()) { 7337 ApplicationInfo ai; 7338 int effectiveFlags = flags; 7339 if (ps.isSystem()) { 7340 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7341 } 7342 if (ps.pkg != null) { 7343 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7344 continue; 7345 } 7346 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7347 ps.readUserState(userId), userId); 7348 if (ai != null) { 7349 rebaseEnabledOverlays(ai, userId); 7350 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7351 } 7352 } else { 7353 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7354 // and already converts to externally visible package name 7355 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7356 Binder.getCallingUid(), effectiveFlags, userId); 7357 } 7358 if (ai != null) { 7359 list.add(ai); 7360 } 7361 } 7362 } else { 7363 list = new ArrayList<>(mPackages.size()); 7364 for (PackageParser.Package p : mPackages.values()) { 7365 if (p.mExtras != null) { 7366 PackageSetting ps = (PackageSetting) p.mExtras; 7367 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId)) { 7368 continue; 7369 } 7370 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7371 ps.readUserState(userId), userId); 7372 if (ai != null) { 7373 rebaseEnabledOverlays(ai, userId); 7374 ai.packageName = resolveExternalPackageNameLPr(p); 7375 list.add(ai); 7376 } 7377 } 7378 } 7379 } 7380 7381 return new ParceledListSlice<>(list); 7382 } 7383 } 7384 7385 @Override 7386 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7387 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7388 return null; 7389 } 7390 7391 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7392 "getEphemeralApplications"); 7393 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7394 true /* requireFullPermission */, false /* checkShell */, 7395 "getEphemeralApplications"); 7396 synchronized (mPackages) { 7397 List<InstantAppInfo> instantApps = mInstantAppRegistry 7398 .getInstantAppsLPr(userId); 7399 if (instantApps != null) { 7400 return new ParceledListSlice<>(instantApps); 7401 } 7402 } 7403 return null; 7404 } 7405 7406 @Override 7407 public boolean isInstantApp(String packageName, int userId) { 7408 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7409 true /* requireFullPermission */, false /* checkShell */, 7410 "isInstantApp"); 7411 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7412 return false; 7413 } 7414 int uid = Binder.getCallingUid(); 7415 if (Process.isIsolated(uid)) { 7416 uid = mIsolatedOwners.get(uid); 7417 } 7418 7419 synchronized (mPackages) { 7420 final PackageSetting ps = mSettings.mPackages.get(packageName); 7421 PackageParser.Package pkg = mPackages.get(packageName); 7422 final boolean returnAllowed = 7423 ps != null 7424 && (isCallerSameApp(packageName, uid) 7425 || mContext.checkCallingOrSelfPermission( 7426 android.Manifest.permission.ACCESS_INSTANT_APPS) 7427 == PERMISSION_GRANTED 7428 || mInstantAppRegistry.isInstantAccessGranted( 7429 userId, UserHandle.getAppId(uid), ps.appId)); 7430 if (returnAllowed) { 7431 return ps.getInstantApp(userId); 7432 } 7433 } 7434 return false; 7435 } 7436 7437 @Override 7438 public byte[] getInstantAppCookie(String packageName, int userId) { 7439 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7440 return null; 7441 } 7442 7443 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7444 true /* requireFullPermission */, false /* checkShell */, 7445 "getInstantAppCookie"); 7446 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7447 return null; 7448 } 7449 synchronized (mPackages) { 7450 return mInstantAppRegistry.getInstantAppCookieLPw( 7451 packageName, userId); 7452 } 7453 } 7454 7455 @Override 7456 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7457 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7458 return true; 7459 } 7460 7461 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7462 true /* requireFullPermission */, true /* checkShell */, 7463 "setInstantAppCookie"); 7464 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7465 return false; 7466 } 7467 synchronized (mPackages) { 7468 return mInstantAppRegistry.setInstantAppCookieLPw( 7469 packageName, cookie, userId); 7470 } 7471 } 7472 7473 @Override 7474 public Bitmap getInstantAppIcon(String packageName, int userId) { 7475 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7476 return null; 7477 } 7478 7479 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7480 "getInstantAppIcon"); 7481 7482 enforceCrossUserPermission(Binder.getCallingUid(), userId, 7483 true /* requireFullPermission */, false /* checkShell */, 7484 "getInstantAppIcon"); 7485 7486 synchronized (mPackages) { 7487 return mInstantAppRegistry.getInstantAppIconLPw( 7488 packageName, userId); 7489 } 7490 } 7491 7492 private boolean isCallerSameApp(String packageName, int uid) { 7493 PackageParser.Package pkg = mPackages.get(packageName); 7494 return pkg != null 7495 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7496 } 7497 7498 @Override 7499 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7500 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7501 } 7502 7503 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7504 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7505 7506 // reader 7507 synchronized (mPackages) { 7508 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7509 final int userId = UserHandle.getCallingUserId(); 7510 while (i.hasNext()) { 7511 final PackageParser.Package p = i.next(); 7512 if (p.applicationInfo == null) continue; 7513 7514 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7515 && !p.applicationInfo.isDirectBootAware(); 7516 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7517 && p.applicationInfo.isDirectBootAware(); 7518 7519 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7520 && (!mSafeMode || isSystemApp(p)) 7521 && (matchesUnaware || matchesAware)) { 7522 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7523 if (ps != null) { 7524 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7525 ps.readUserState(userId), userId); 7526 if (ai != null) { 7527 rebaseEnabledOverlays(ai, userId); 7528 finalList.add(ai); 7529 } 7530 } 7531 } 7532 } 7533 } 7534 7535 return finalList; 7536 } 7537 7538 @Override 7539 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7540 if (!sUserManager.exists(userId)) return null; 7541 flags = updateFlagsForComponent(flags, userId, name); 7542 // reader 7543 synchronized (mPackages) { 7544 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7545 PackageSetting ps = provider != null 7546 ? mSettings.mPackages.get(provider.owner.packageName) 7547 : null; 7548 return ps != null 7549 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 7550 ? PackageParser.generateProviderInfo(provider, flags, 7551 ps.readUserState(userId), userId) 7552 : null; 7553 } 7554 } 7555 7556 /** 7557 * @deprecated 7558 */ 7559 @Deprecated 7560 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7561 // reader 7562 synchronized (mPackages) { 7563 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7564 .entrySet().iterator(); 7565 final int userId = UserHandle.getCallingUserId(); 7566 while (i.hasNext()) { 7567 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7568 PackageParser.Provider p = entry.getValue(); 7569 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7570 7571 if (ps != null && p.syncable 7572 && (!mSafeMode || (p.info.applicationInfo.flags 7573 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7574 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 7575 ps.readUserState(userId), userId); 7576 if (info != null) { 7577 outNames.add(entry.getKey()); 7578 outInfo.add(info); 7579 } 7580 } 7581 } 7582 } 7583 } 7584 7585 @Override 7586 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 7587 int uid, int flags, String metaDataKey) { 7588 final int userId = processName != null ? UserHandle.getUserId(uid) 7589 : UserHandle.getCallingUserId(); 7590 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7591 flags = updateFlagsForComponent(flags, userId, processName); 7592 7593 ArrayList<ProviderInfo> finalList = null; 7594 // reader 7595 synchronized (mPackages) { 7596 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 7597 while (i.hasNext()) { 7598 final PackageParser.Provider p = i.next(); 7599 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7600 if (ps != null && p.info.authority != null 7601 && (processName == null 7602 || (p.info.processName.equals(processName) 7603 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 7604 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 7605 7606 // See PM.queryContentProviders()'s javadoc for why we have the metaData 7607 // parameter. 7608 if (metaDataKey != null 7609 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 7610 continue; 7611 } 7612 7613 if (finalList == null) { 7614 finalList = new ArrayList<ProviderInfo>(3); 7615 } 7616 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 7617 ps.readUserState(userId), userId); 7618 if (info != null) { 7619 finalList.add(info); 7620 } 7621 } 7622 } 7623 } 7624 7625 if (finalList != null) { 7626 Collections.sort(finalList, mProviderInitOrderSorter); 7627 return new ParceledListSlice<ProviderInfo>(finalList); 7628 } 7629 7630 return ParceledListSlice.emptyList(); 7631 } 7632 7633 @Override 7634 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 7635 // reader 7636 synchronized (mPackages) { 7637 final PackageParser.Instrumentation i = mInstrumentation.get(name); 7638 return PackageParser.generateInstrumentationInfo(i, flags); 7639 } 7640 } 7641 7642 @Override 7643 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 7644 String targetPackage, int flags) { 7645 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 7646 } 7647 7648 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 7649 int flags) { 7650 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 7651 7652 // reader 7653 synchronized (mPackages) { 7654 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 7655 while (i.hasNext()) { 7656 final PackageParser.Instrumentation p = i.next(); 7657 if (targetPackage == null 7658 || targetPackage.equals(p.info.targetPackage)) { 7659 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 7660 flags); 7661 if (ii != null) { 7662 finalList.add(ii); 7663 } 7664 } 7665 } 7666 } 7667 7668 return finalList; 7669 } 7670 7671 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 7672 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 7673 try { 7674 scanDirLI(dir, parseFlags, scanFlags, currentTime); 7675 } finally { 7676 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7677 } 7678 } 7679 7680 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 7681 final File[] files = dir.listFiles(); 7682 if (ArrayUtils.isEmpty(files)) { 7683 Log.d(TAG, "No files in app dir " + dir); 7684 return; 7685 } 7686 7687 if (DEBUG_PACKAGE_SCANNING) { 7688 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 7689 + " flags=0x" + Integer.toHexString(parseFlags)); 7690 } 7691 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 7692 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, mPackageParserCallback); 7693 7694 // Submit files for parsing in parallel 7695 int fileCount = 0; 7696 for (File file : files) { 7697 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 7698 && !PackageInstallerService.isStageName(file.getName()); 7699 if (!isPackage) { 7700 // Ignore entries which are not packages 7701 continue; 7702 } 7703 parallelPackageParser.submit(file, parseFlags); 7704 fileCount++; 7705 } 7706 7707 // Process results one by one 7708 for (; fileCount > 0; fileCount--) { 7709 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 7710 Throwable throwable = parseResult.throwable; 7711 int errorCode = PackageManager.INSTALL_SUCCEEDED; 7712 7713 if (throwable == null) { 7714 // Static shared libraries have synthetic package names 7715 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 7716 renameStaticSharedLibraryPackage(parseResult.pkg); 7717 } 7718 try { 7719 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 7720 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 7721 currentTime, null); 7722 } 7723 } catch (PackageManagerException e) { 7724 errorCode = e.error; 7725 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 7726 } 7727 } else if (throwable instanceof PackageParser.PackageParserException) { 7728 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 7729 throwable; 7730 errorCode = e.error; 7731 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 7732 } else { 7733 throw new IllegalStateException("Unexpected exception occurred while parsing " 7734 + parseResult.scanFile, throwable); 7735 } 7736 7737 // Delete invalid userdata apps 7738 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 7739 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 7740 logCriticalInfo(Log.WARN, 7741 "Deleting invalid package at " + parseResult.scanFile); 7742 removeCodePathLI(parseResult.scanFile); 7743 } 7744 } 7745 parallelPackageParser.close(); 7746 } 7747 7748 private static File getSettingsProblemFile() { 7749 File dataDir = Environment.getDataDirectory(); 7750 File systemDir = new File(dataDir, "system"); 7751 File fname = new File(systemDir, "uiderrors.txt"); 7752 return fname; 7753 } 7754 7755 static void reportSettingsProblem(int priority, String msg) { 7756 logCriticalInfo(priority, msg); 7757 } 7758 7759 public static void logCriticalInfo(int priority, String msg) { 7760 Slog.println(priority, TAG, msg); 7761 EventLogTags.writePmCriticalInfo(msg); 7762 try { 7763 File fname = getSettingsProblemFile(); 7764 FileOutputStream out = new FileOutputStream(fname, true); 7765 PrintWriter pw = new FastPrintWriter(out); 7766 SimpleDateFormat formatter = new SimpleDateFormat(); 7767 String dateString = formatter.format(new Date(System.currentTimeMillis())); 7768 pw.println(dateString + ": " + msg); 7769 pw.close(); 7770 FileUtils.setPermissions( 7771 fname.toString(), 7772 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 7773 -1, -1); 7774 } catch (java.io.IOException e) { 7775 } 7776 } 7777 7778 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 7779 if (srcFile.isDirectory()) { 7780 final File baseFile = new File(pkg.baseCodePath); 7781 long maxModifiedTime = baseFile.lastModified(); 7782 if (pkg.splitCodePaths != null) { 7783 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 7784 final File splitFile = new File(pkg.splitCodePaths[i]); 7785 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 7786 } 7787 } 7788 return maxModifiedTime; 7789 } 7790 return srcFile.lastModified(); 7791 } 7792 7793 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 7794 final int policyFlags) throws PackageManagerException { 7795 // When upgrading from pre-N MR1, verify the package time stamp using the package 7796 // directory and not the APK file. 7797 final long lastModifiedTime = mIsPreNMR1Upgrade 7798 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 7799 if (ps != null 7800 && ps.codePath.equals(srcFile) 7801 && ps.timeStamp == lastModifiedTime 7802 && !isCompatSignatureUpdateNeeded(pkg) 7803 && !isRecoverSignatureUpdateNeeded(pkg)) { 7804 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 7805 KeySetManagerService ksms = mSettings.mKeySetManagerService; 7806 ArraySet<PublicKey> signingKs; 7807 synchronized (mPackages) { 7808 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 7809 } 7810 if (ps.signatures.mSignatures != null 7811 && ps.signatures.mSignatures.length != 0 7812 && signingKs != null) { 7813 // Optimization: reuse the existing cached certificates 7814 // if the package appears to be unchanged. 7815 pkg.mSignatures = ps.signatures.mSignatures; 7816 pkg.mSigningKeys = signingKs; 7817 return; 7818 } 7819 7820 Slog.w(TAG, "PackageSetting for " + ps.name 7821 + " is missing signatures. Collecting certs again to recover them."); 7822 } else { 7823 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 7824 } 7825 7826 try { 7827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 7828 PackageParser.collectCertificates(pkg, policyFlags); 7829 } catch (PackageParserException e) { 7830 throw PackageManagerException.from(e); 7831 } finally { 7832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7833 } 7834 } 7835 7836 /** 7837 * Traces a package scan. 7838 * @see #scanPackageLI(File, int, int, long, UserHandle) 7839 */ 7840 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 7841 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7842 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 7843 try { 7844 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 7845 } finally { 7846 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7847 } 7848 } 7849 7850 /** 7851 * Scans a package and returns the newly parsed package. 7852 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 7853 */ 7854 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 7855 long currentTime, UserHandle user) throws PackageManagerException { 7856 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 7857 PackageParser pp = new PackageParser(); 7858 pp.setSeparateProcesses(mSeparateProcesses); 7859 pp.setOnlyCoreApps(mOnlyCore); 7860 pp.setDisplayMetrics(mMetrics); 7861 pp.setCallback(mPackageParserCallback); 7862 7863 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 7864 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 7865 } 7866 7867 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 7868 final PackageParser.Package pkg; 7869 try { 7870 pkg = pp.parsePackage(scanFile, parseFlags); 7871 } catch (PackageParserException e) { 7872 throw PackageManagerException.from(e); 7873 } finally { 7874 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7875 } 7876 7877 // Static shared libraries have synthetic package names 7878 if (pkg.applicationInfo.isStaticSharedLibrary()) { 7879 renameStaticSharedLibraryPackage(pkg); 7880 } 7881 7882 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7883 } 7884 7885 /** 7886 * Scans a package and returns the newly parsed package. 7887 * @throws PackageManagerException on a parse error. 7888 */ 7889 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7890 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7891 throws PackageManagerException { 7892 // If the package has children and this is the first dive in the function 7893 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7894 // packages (parent and children) would be successfully scanned before the 7895 // actual scan since scanning mutates internal state and we want to atomically 7896 // install the package and its children. 7897 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7898 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7899 scanFlags |= SCAN_CHECK_ONLY; 7900 } 7901 } else { 7902 scanFlags &= ~SCAN_CHECK_ONLY; 7903 } 7904 7905 // Scan the parent 7906 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7907 scanFlags, currentTime, user); 7908 7909 // Scan the children 7910 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7911 for (int i = 0; i < childCount; i++) { 7912 PackageParser.Package childPackage = pkg.childPackages.get(i); 7913 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7914 currentTime, user); 7915 } 7916 7917 7918 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7919 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7920 } 7921 7922 return scannedPkg; 7923 } 7924 7925 /** 7926 * Scans a package and returns the newly parsed package. 7927 * @throws PackageManagerException on a parse error. 7928 */ 7929 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7930 int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 7931 throws PackageManagerException { 7932 PackageSetting ps = null; 7933 PackageSetting updatedPkg; 7934 // reader 7935 synchronized (mPackages) { 7936 // Look to see if we already know about this package. 7937 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7938 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7939 // This package has been renamed to its original name. Let's 7940 // use that. 7941 ps = mSettings.getPackageLPr(oldName); 7942 } 7943 // If there was no original package, see one for the real package name. 7944 if (ps == null) { 7945 ps = mSettings.getPackageLPr(pkg.packageName); 7946 } 7947 // Check to see if this package could be hiding/updating a system 7948 // package. Must look for it either under the original or real 7949 // package name depending on our state. 7950 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7951 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7952 7953 // If this is a package we don't know about on the system partition, we 7954 // may need to remove disabled child packages on the system partition 7955 // or may need to not add child packages if the parent apk is updated 7956 // on the data partition and no longer defines this child package. 7957 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7958 // If this is a parent package for an updated system app and this system 7959 // app got an OTA update which no longer defines some of the child packages 7960 // we have to prune them from the disabled system packages. 7961 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7962 if (disabledPs != null) { 7963 final int scannedChildCount = (pkg.childPackages != null) 7964 ? pkg.childPackages.size() : 0; 7965 final int disabledChildCount = disabledPs.childPackageNames != null 7966 ? disabledPs.childPackageNames.size() : 0; 7967 for (int i = 0; i < disabledChildCount; i++) { 7968 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7969 boolean disabledPackageAvailable = false; 7970 for (int j = 0; j < scannedChildCount; j++) { 7971 PackageParser.Package childPkg = pkg.childPackages.get(j); 7972 if (childPkg.packageName.equals(disabledChildPackageName)) { 7973 disabledPackageAvailable = true; 7974 break; 7975 } 7976 } 7977 if (!disabledPackageAvailable) { 7978 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7979 } 7980 } 7981 } 7982 } 7983 } 7984 7985 boolean updatedPkgBetter = false; 7986 // First check if this is a system package that may involve an update 7987 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7988 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7989 // it needs to drop FLAG_PRIVILEGED. 7990 if (locationIsPrivileged(scanFile)) { 7991 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7992 } else { 7993 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7994 } 7995 7996 if (ps != null && !ps.codePath.equals(scanFile)) { 7997 // The path has changed from what was last scanned... check the 7998 // version of the new path against what we have stored to determine 7999 // what to do. 8000 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 8001 if (pkg.mVersionCode <= ps.versionCode) { 8002 // The system package has been updated and the code path does not match 8003 // Ignore entry. Skip it. 8004 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 8005 + " ignored: updated version " + ps.versionCode 8006 + " better than this " + pkg.mVersionCode); 8007 if (!updatedPkg.codePath.equals(scanFile)) { 8008 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 8009 + ps.name + " changing from " + updatedPkg.codePathString 8010 + " to " + scanFile); 8011 updatedPkg.codePath = scanFile; 8012 updatedPkg.codePathString = scanFile.toString(); 8013 updatedPkg.resourcePath = scanFile; 8014 updatedPkg.resourcePathString = scanFile.toString(); 8015 } 8016 updatedPkg.pkg = pkg; 8017 updatedPkg.versionCode = pkg.mVersionCode; 8018 8019 // Update the disabled system child packages to point to the package too. 8020 final int childCount = updatedPkg.childPackageNames != null 8021 ? updatedPkg.childPackageNames.size() : 0; 8022 for (int i = 0; i < childCount; i++) { 8023 String childPackageName = updatedPkg.childPackageNames.get(i); 8024 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 8025 childPackageName); 8026 if (updatedChildPkg != null) { 8027 updatedChildPkg.pkg = pkg; 8028 updatedChildPkg.versionCode = pkg.mVersionCode; 8029 } 8030 } 8031 8032 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 8033 + scanFile + " ignored: updated version " + ps.versionCode 8034 + " better than this " + pkg.mVersionCode); 8035 } else { 8036 // The current app on the system partition is better than 8037 // what we have updated to on the data partition; switch 8038 // back to the system partition version. 8039 // At this point, its safely assumed that package installation for 8040 // apps in system partition will go through. If not there won't be a working 8041 // version of the app 8042 // writer 8043 synchronized (mPackages) { 8044 // Just remove the loaded entries from package lists. 8045 mPackages.remove(ps.name); 8046 } 8047 8048 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8049 + " reverting from " + ps.codePathString 8050 + ": new version " + pkg.mVersionCode 8051 + " better than installed " + ps.versionCode); 8052 8053 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8054 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8055 synchronized (mInstallLock) { 8056 args.cleanUpResourcesLI(); 8057 } 8058 synchronized (mPackages) { 8059 mSettings.enableSystemPackageLPw(ps.name); 8060 } 8061 updatedPkgBetter = true; 8062 } 8063 } 8064 } 8065 8066 if (updatedPkg != null) { 8067 // An updated system app will not have the PARSE_IS_SYSTEM flag set 8068 // initially 8069 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 8070 8071 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 8072 // flag set initially 8073 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 8074 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 8075 } 8076 } 8077 8078 // Verify certificates against what was last scanned 8079 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 8080 8081 /* 8082 * A new system app appeared, but we already had a non-system one of the 8083 * same name installed earlier. 8084 */ 8085 boolean shouldHideSystemApp = false; 8086 if (updatedPkg == null && ps != null 8087 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 8088 /* 8089 * Check to make sure the signatures match first. If they don't, 8090 * wipe the installed application and its data. 8091 */ 8092 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 8093 != PackageManager.SIGNATURE_MATCH) { 8094 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 8095 + " signatures don't match existing userdata copy; removing"); 8096 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8097 "scanPackageInternalLI")) { 8098 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8099 } 8100 ps = null; 8101 } else { 8102 /* 8103 * If the newly-added system app is an older version than the 8104 * already installed version, hide it. It will be scanned later 8105 * and re-added like an update. 8106 */ 8107 if (pkg.mVersionCode <= ps.versionCode) { 8108 shouldHideSystemApp = true; 8109 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 8110 + " but new version " + pkg.mVersionCode + " better than installed " 8111 + ps.versionCode + "; hiding system"); 8112 } else { 8113 /* 8114 * The newly found system app is a newer version that the 8115 * one previously installed. Simply remove the 8116 * already-installed application and replace it with our own 8117 * while keeping the application data. 8118 */ 8119 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 8120 + " reverting from " + ps.codePathString + ": new version " 8121 + pkg.mVersionCode + " better than installed " + ps.versionCode); 8122 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 8123 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 8124 synchronized (mInstallLock) { 8125 args.cleanUpResourcesLI(); 8126 } 8127 } 8128 } 8129 } 8130 8131 // The apk is forward locked (not public) if its code and resources 8132 // are kept in different files. (except for app in either system or 8133 // vendor path). 8134 // TODO grab this value from PackageSettings 8135 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8136 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 8137 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 8138 } 8139 } 8140 8141 // TODO: extend to support forward-locked splits 8142 String resourcePath = null; 8143 String baseResourcePath = null; 8144 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 8145 if (ps != null && ps.resourcePathString != null) { 8146 resourcePath = ps.resourcePathString; 8147 baseResourcePath = ps.resourcePathString; 8148 } else { 8149 // Should not happen at all. Just log an error. 8150 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 8151 } 8152 } else { 8153 resourcePath = pkg.codePath; 8154 baseResourcePath = pkg.baseCodePath; 8155 } 8156 8157 // Set application objects path explicitly. 8158 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8159 pkg.setApplicationInfoCodePath(pkg.codePath); 8160 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8161 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8162 pkg.setApplicationInfoResourcePath(resourcePath); 8163 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 8164 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8165 8166 final int userId = ((user == null) ? 0 : user.getIdentifier()); 8167 if (ps != null && ps.getInstantApp(userId)) { 8168 scanFlags |= SCAN_AS_INSTANT_APP; 8169 } 8170 8171 // Note that we invoke the following method only if we are about to unpack an application 8172 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 8173 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8174 8175 /* 8176 * If the system app should be overridden by a previously installed 8177 * data, hide the system app now and let the /data/app scan pick it up 8178 * again. 8179 */ 8180 if (shouldHideSystemApp) { 8181 synchronized (mPackages) { 8182 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8183 } 8184 } 8185 8186 return scannedPkg; 8187 } 8188 8189 private void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8190 // Derive the new package synthetic package name 8191 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8192 + pkg.staticSharedLibVersion); 8193 } 8194 8195 private static String fixProcessName(String defProcessName, 8196 String processName) { 8197 if (processName == null) { 8198 return defProcessName; 8199 } 8200 return processName; 8201 } 8202 8203 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 8204 throws PackageManagerException { 8205 if (pkgSetting.signatures.mSignatures != null) { 8206 // Already existing package. Make sure signatures match 8207 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 8208 == PackageManager.SIGNATURE_MATCH; 8209 if (!match) { 8210 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 8211 == PackageManager.SIGNATURE_MATCH; 8212 } 8213 if (!match) { 8214 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 8215 == PackageManager.SIGNATURE_MATCH; 8216 } 8217 if (!match) { 8218 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 8219 + pkg.packageName + " signatures do not match the " 8220 + "previously installed version; ignoring!"); 8221 } 8222 } 8223 8224 // Check for shared user signatures 8225 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 8226 // Already existing package. Make sure signatures match 8227 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8228 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 8229 if (!match) { 8230 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 8231 == PackageManager.SIGNATURE_MATCH; 8232 } 8233 if (!match) { 8234 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 8235 == PackageManager.SIGNATURE_MATCH; 8236 } 8237 if (!match) { 8238 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 8239 "Package " + pkg.packageName 8240 + " has no signatures that match those in shared user " 8241 + pkgSetting.sharedUser.name + "; ignoring!"); 8242 } 8243 } 8244 } 8245 8246 /** 8247 * Enforces that only the system UID or root's UID can call a method exposed 8248 * via Binder. 8249 * 8250 * @param message used as message if SecurityException is thrown 8251 * @throws SecurityException if the caller is not system or root 8252 */ 8253 private static final void enforceSystemOrRoot(String message) { 8254 final int uid = Binder.getCallingUid(); 8255 if (uid != Process.SYSTEM_UID && uid != 0) { 8256 throw new SecurityException(message); 8257 } 8258 } 8259 8260 @Override 8261 public void performFstrimIfNeeded() { 8262 enforceSystemOrRoot("Only the system can request fstrim"); 8263 8264 // Before everything else, see whether we need to fstrim. 8265 try { 8266 IStorageManager sm = PackageHelper.getStorageManager(); 8267 if (sm != null) { 8268 boolean doTrim = false; 8269 final long interval = android.provider.Settings.Global.getLong( 8270 mContext.getContentResolver(), 8271 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8272 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8273 if (interval > 0) { 8274 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8275 if (timeSinceLast > interval) { 8276 doTrim = true; 8277 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8278 + "; running immediately"); 8279 } 8280 } 8281 if (doTrim) { 8282 final boolean dexOptDialogShown; 8283 synchronized (mPackages) { 8284 dexOptDialogShown = mDexOptDialogShown; 8285 } 8286 if (!isFirstBoot() && dexOptDialogShown) { 8287 try { 8288 ActivityManager.getService().showBootMessage( 8289 mContext.getResources().getString( 8290 R.string.android_upgrading_fstrim), true); 8291 } catch (RemoteException e) { 8292 } 8293 } 8294 sm.runMaintenance(); 8295 } 8296 } else { 8297 Slog.e(TAG, "storageManager service unavailable!"); 8298 } 8299 } catch (RemoteException e) { 8300 // Can't happen; StorageManagerService is local 8301 } 8302 } 8303 8304 @Override 8305 public void updatePackagesIfNeeded() { 8306 enforceSystemOrRoot("Only the system can request package update"); 8307 8308 // We need to re-extract after an OTA. 8309 boolean causeUpgrade = isUpgrade(); 8310 8311 // First boot or factory reset. 8312 // Note: we also handle devices that are upgrading to N right now as if it is their 8313 // first boot, as they do not have profile data. 8314 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8315 8316 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8317 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8318 8319 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8320 return; 8321 } 8322 8323 List<PackageParser.Package> pkgs; 8324 synchronized (mPackages) { 8325 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8326 } 8327 8328 final long startTime = System.nanoTime(); 8329 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8330 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 8331 8332 final int elapsedTimeSeconds = 8333 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8334 8335 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8336 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8337 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8338 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8339 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8340 } 8341 8342 /** 8343 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8344 * containing statistics about the invocation. The array consists of three elements, 8345 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8346 * and {@code numberOfPackagesFailed}. 8347 */ 8348 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8349 String compilerFilter) { 8350 8351 int numberOfPackagesVisited = 0; 8352 int numberOfPackagesOptimized = 0; 8353 int numberOfPackagesSkipped = 0; 8354 int numberOfPackagesFailed = 0; 8355 final int numberOfPackagesToDexopt = pkgs.size(); 8356 8357 for (PackageParser.Package pkg : pkgs) { 8358 numberOfPackagesVisited++; 8359 8360 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8361 if (DEBUG_DEXOPT) { 8362 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8363 } 8364 numberOfPackagesSkipped++; 8365 continue; 8366 } 8367 8368 if (DEBUG_DEXOPT) { 8369 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8370 numberOfPackagesToDexopt + ": " + pkg.packageName); 8371 } 8372 8373 if (showDialog) { 8374 try { 8375 ActivityManager.getService().showBootMessage( 8376 mContext.getResources().getString(R.string.android_upgrading_apk, 8377 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8378 } catch (RemoteException e) { 8379 } 8380 synchronized (mPackages) { 8381 mDexOptDialogShown = true; 8382 } 8383 } 8384 8385 // If the OTA updates a system app which was previously preopted to a non-preopted state 8386 // the app might end up being verified at runtime. That's because by default the apps 8387 // are verify-profile but for preopted apps there's no profile. 8388 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 8389 // that before the OTA the app was preopted) the app gets compiled with a non-profile 8390 // filter (by default interpret-only). 8391 // Note that at this stage unused apps are already filtered. 8392 if (isSystemApp(pkg) && 8393 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 8394 !Environment.getReferenceProfile(pkg.packageName).exists()) { 8395 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 8396 } 8397 8398 // checkProfiles is false to avoid merging profiles during boot which 8399 // might interfere with background compilation (b/28612421). 8400 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8401 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8402 // trade-off worth doing to save boot time work. 8403 int dexOptStatus = performDexOptTraced(pkg.packageName, 8404 false /* checkProfiles */, 8405 compilerFilter, 8406 false /* force */); 8407 switch (dexOptStatus) { 8408 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8409 numberOfPackagesOptimized++; 8410 break; 8411 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8412 numberOfPackagesSkipped++; 8413 break; 8414 case PackageDexOptimizer.DEX_OPT_FAILED: 8415 numberOfPackagesFailed++; 8416 break; 8417 default: 8418 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 8419 break; 8420 } 8421 } 8422 8423 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8424 numberOfPackagesFailed }; 8425 } 8426 8427 @Override 8428 public void notifyPackageUse(String packageName, int reason) { 8429 synchronized (mPackages) { 8430 PackageParser.Package p = mPackages.get(packageName); 8431 if (p == null) { 8432 return; 8433 } 8434 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8435 } 8436 } 8437 8438 @Override 8439 public void notifyDexLoad(String loadingPackageName, List<String> dexPaths, String loaderIsa) { 8440 int userId = UserHandle.getCallingUserId(); 8441 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8442 if (ai == null) { 8443 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8444 + loadingPackageName + ", user=" + userId); 8445 return; 8446 } 8447 mDexManager.notifyDexLoad(ai, dexPaths, loaderIsa, userId); 8448 } 8449 8450 // TODO: this is not used nor needed. Delete it. 8451 @Override 8452 public boolean performDexOptIfNeeded(String packageName) { 8453 int dexOptStatus = performDexOptTraced(packageName, 8454 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 8455 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8456 } 8457 8458 @Override 8459 public boolean performDexOpt(String packageName, 8460 boolean checkProfiles, int compileReason, boolean force) { 8461 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8462 getCompilerFilterForReason(compileReason), force); 8463 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8464 } 8465 8466 @Override 8467 public boolean performDexOptMode(String packageName, 8468 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8469 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 8470 targetCompilerFilter, force); 8471 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 8472 } 8473 8474 private int performDexOptTraced(String packageName, 8475 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8476 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8477 try { 8478 return performDexOptInternal(packageName, checkProfiles, 8479 targetCompilerFilter, force); 8480 } finally { 8481 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8482 } 8483 } 8484 8485 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 8486 // if the package can now be considered up to date for the given filter. 8487 private int performDexOptInternal(String packageName, 8488 boolean checkProfiles, String targetCompilerFilter, boolean force) { 8489 PackageParser.Package p; 8490 synchronized (mPackages) { 8491 p = mPackages.get(packageName); 8492 if (p == null) { 8493 // Package could not be found. Report failure. 8494 return PackageDexOptimizer.DEX_OPT_FAILED; 8495 } 8496 mPackageUsage.maybeWriteAsync(mPackages); 8497 mCompilerStats.maybeWriteAsync(); 8498 } 8499 long callingId = Binder.clearCallingIdentity(); 8500 try { 8501 synchronized (mInstallLock) { 8502 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 8503 targetCompilerFilter, force); 8504 } 8505 } finally { 8506 Binder.restoreCallingIdentity(callingId); 8507 } 8508 } 8509 8510 public ArraySet<String> getOptimizablePackages() { 8511 ArraySet<String> pkgs = new ArraySet<String>(); 8512 synchronized (mPackages) { 8513 for (PackageParser.Package p : mPackages.values()) { 8514 if (PackageDexOptimizer.canOptimizePackage(p)) { 8515 pkgs.add(p.packageName); 8516 } 8517 } 8518 } 8519 return pkgs; 8520 } 8521 8522 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 8523 boolean checkProfiles, String targetCompilerFilter, 8524 boolean force) { 8525 // Select the dex optimizer based on the force parameter. 8526 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 8527 // allocate an object here. 8528 PackageDexOptimizer pdo = force 8529 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 8530 : mPackageDexOptimizer; 8531 8532 // Dexopt all dependencies first. Note: we ignore the return value and march on 8533 // on errors. 8534 // Note that we are going to call performDexOpt on those libraries as many times as 8535 // they are referenced in packages. When we do a batch of performDexOpt (for example 8536 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 8537 // and the first package that uses the library will dexopt it. The 8538 // others will see that the compiled code for the library is up to date. 8539 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 8540 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 8541 if (!deps.isEmpty()) { 8542 for (PackageParser.Package depPackage : deps) { 8543 // TODO: Analyze and investigate if we (should) profile libraries. 8544 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 8545 false /* checkProfiles */, 8546 targetCompilerFilter, 8547 getOrCreateCompilerPackageStats(depPackage), 8548 true /* isUsedByOtherApps */); 8549 } 8550 } 8551 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 8552 targetCompilerFilter, getOrCreateCompilerPackageStats(p), 8553 mDexManager.isUsedByOtherApps(p.packageName)); 8554 } 8555 8556 // Performs dexopt on the used secondary dex files belonging to the given package. 8557 // Returns true if all dex files were process successfully (which could mean either dexopt or 8558 // skip). Returns false if any of the files caused errors. 8559 @Override 8560 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8561 boolean force) { 8562 mDexManager.reconcileSecondaryDexFiles(packageName); 8563 return mDexManager.dexoptSecondaryDex(packageName, compilerFilter, force); 8564 } 8565 8566 public boolean performDexOptSecondary(String packageName, int compileReason, 8567 boolean force) { 8568 return mDexManager.dexoptSecondaryDex(packageName, compileReason, force); 8569 } 8570 8571 /** 8572 * Reconcile the information we have about the secondary dex files belonging to 8573 * {@code packagName} and the actual dex files. For all dex files that were 8574 * deleted, update the internal records and delete the generated oat files. 8575 */ 8576 @Override 8577 public void reconcileSecondaryDexFiles(String packageName) { 8578 mDexManager.reconcileSecondaryDexFiles(packageName); 8579 } 8580 8581 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 8582 // a reference there. 8583 /*package*/ DexManager getDexManager() { 8584 return mDexManager; 8585 } 8586 8587 /** 8588 * Execute the background dexopt job immediately. 8589 */ 8590 @Override 8591 public boolean runBackgroundDexoptJob() { 8592 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext); 8593 } 8594 8595 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 8596 if (p.usesLibraries != null || p.usesOptionalLibraries != null 8597 || p.usesStaticLibraries != null) { 8598 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 8599 Set<String> collectedNames = new HashSet<>(); 8600 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 8601 8602 retValue.remove(p); 8603 8604 return retValue; 8605 } else { 8606 return Collections.emptyList(); 8607 } 8608 } 8609 8610 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 8611 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8612 if (!collectedNames.contains(p.packageName)) { 8613 collectedNames.add(p.packageName); 8614 collected.add(p); 8615 8616 if (p.usesLibraries != null) { 8617 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 8618 null, collected, collectedNames); 8619 } 8620 if (p.usesOptionalLibraries != null) { 8621 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 8622 null, collected, collectedNames); 8623 } 8624 if (p.usesStaticLibraries != null) { 8625 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 8626 p.usesStaticLibrariesVersions, collected, collectedNames); 8627 } 8628 } 8629 } 8630 8631 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, int[] versions, 8632 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 8633 final int libNameCount = libs.size(); 8634 for (int i = 0; i < libNameCount; i++) { 8635 String libName = libs.get(i); 8636 int version = (versions != null && versions.length == libNameCount) 8637 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 8638 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 8639 if (libPkg != null) { 8640 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 8641 } 8642 } 8643 } 8644 8645 private PackageParser.Package findSharedNonSystemLibrary(String name, int version) { 8646 synchronized (mPackages) { 8647 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 8648 if (libEntry != null) { 8649 return mPackages.get(libEntry.apk); 8650 } 8651 return null; 8652 } 8653 } 8654 8655 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, int version) { 8656 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 8657 if (versionedLib == null) { 8658 return null; 8659 } 8660 return versionedLib.get(version); 8661 } 8662 8663 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 8664 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 8665 pkg.staticSharedLibName); 8666 if (versionedLib == null) { 8667 return null; 8668 } 8669 int previousLibVersion = -1; 8670 final int versionCount = versionedLib.size(); 8671 for (int i = 0; i < versionCount; i++) { 8672 final int libVersion = versionedLib.keyAt(i); 8673 if (libVersion < pkg.staticSharedLibVersion) { 8674 previousLibVersion = Math.max(previousLibVersion, libVersion); 8675 } 8676 } 8677 if (previousLibVersion >= 0) { 8678 return versionedLib.get(previousLibVersion); 8679 } 8680 return null; 8681 } 8682 8683 public void shutdown() { 8684 mPackageUsage.writeNow(mPackages); 8685 mCompilerStats.writeNow(); 8686 } 8687 8688 @Override 8689 public void dumpProfiles(String packageName) { 8690 PackageParser.Package pkg; 8691 synchronized (mPackages) { 8692 pkg = mPackages.get(packageName); 8693 if (pkg == null) { 8694 throw new IllegalArgumentException("Unknown package: " + packageName); 8695 } 8696 } 8697 /* Only the shell, root, or the app user should be able to dump profiles. */ 8698 int callingUid = Binder.getCallingUid(); 8699 if (callingUid != Process.SHELL_UID && 8700 callingUid != Process.ROOT_UID && 8701 callingUid != pkg.applicationInfo.uid) { 8702 throw new SecurityException("dumpProfiles"); 8703 } 8704 8705 synchronized (mInstallLock) { 8706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 8707 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 8708 try { 8709 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 8710 String codePaths = TextUtils.join(";", allCodePaths); 8711 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 8712 } catch (InstallerException e) { 8713 Slog.w(TAG, "Failed to dump profiles", e); 8714 } 8715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8716 } 8717 } 8718 8719 @Override 8720 public void forceDexOpt(String packageName) { 8721 enforceSystemOrRoot("forceDexOpt"); 8722 8723 PackageParser.Package pkg; 8724 synchronized (mPackages) { 8725 pkg = mPackages.get(packageName); 8726 if (pkg == null) { 8727 throw new IllegalArgumentException("Unknown package: " + packageName); 8728 } 8729 } 8730 8731 synchronized (mInstallLock) { 8732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 8733 8734 // Whoever is calling forceDexOpt wants a fully compiled package. 8735 // Don't use profiles since that may cause compilation to be skipped. 8736 final int res = performDexOptInternalWithDependenciesLI(pkg, 8737 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 8738 true /* force */); 8739 8740 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8741 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 8742 throw new IllegalStateException("Failed to dexopt: " + res); 8743 } 8744 } 8745 } 8746 8747 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 8748 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 8749 Slog.w(TAG, "Unable to update from " + oldPkg.name 8750 + " to " + newPkg.packageName 8751 + ": old package not in system partition"); 8752 return false; 8753 } else if (mPackages.get(oldPkg.name) != null) { 8754 Slog.w(TAG, "Unable to update from " + oldPkg.name 8755 + " to " + newPkg.packageName 8756 + ": old package still exists"); 8757 return false; 8758 } 8759 return true; 8760 } 8761 8762 void removeCodePathLI(File codePath) { 8763 if (codePath.isDirectory()) { 8764 try { 8765 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 8766 } catch (InstallerException e) { 8767 Slog.w(TAG, "Failed to remove code path", e); 8768 } 8769 } else { 8770 codePath.delete(); 8771 } 8772 } 8773 8774 private int[] resolveUserIds(int userId) { 8775 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 8776 } 8777 8778 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8779 if (pkg == null) { 8780 Slog.wtf(TAG, "Package was null!", new Throwable()); 8781 return; 8782 } 8783 clearAppDataLeafLIF(pkg, userId, flags); 8784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8785 for (int i = 0; i < childCount; i++) { 8786 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8787 } 8788 } 8789 8790 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8791 final PackageSetting ps; 8792 synchronized (mPackages) { 8793 ps = mSettings.mPackages.get(pkg.packageName); 8794 } 8795 for (int realUserId : resolveUserIds(userId)) { 8796 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8797 try { 8798 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8799 ceDataInode); 8800 } catch (InstallerException e) { 8801 Slog.w(TAG, String.valueOf(e)); 8802 } 8803 } 8804 } 8805 8806 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 8807 if (pkg == null) { 8808 Slog.wtf(TAG, "Package was null!", new Throwable()); 8809 return; 8810 } 8811 destroyAppDataLeafLIF(pkg, userId, flags); 8812 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8813 for (int i = 0; i < childCount; i++) { 8814 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 8815 } 8816 } 8817 8818 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 8819 final PackageSetting ps; 8820 synchronized (mPackages) { 8821 ps = mSettings.mPackages.get(pkg.packageName); 8822 } 8823 for (int realUserId : resolveUserIds(userId)) { 8824 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 8825 try { 8826 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 8827 ceDataInode); 8828 } catch (InstallerException e) { 8829 Slog.w(TAG, String.valueOf(e)); 8830 } 8831 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 8832 } 8833 } 8834 8835 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 8836 if (pkg == null) { 8837 Slog.wtf(TAG, "Package was null!", new Throwable()); 8838 return; 8839 } 8840 destroyAppProfilesLeafLIF(pkg); 8841 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8842 for (int i = 0; i < childCount; i++) { 8843 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 8844 } 8845 } 8846 8847 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 8848 try { 8849 mInstaller.destroyAppProfiles(pkg.packageName); 8850 } catch (InstallerException e) { 8851 Slog.w(TAG, String.valueOf(e)); 8852 } 8853 } 8854 8855 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 8856 if (pkg == null) { 8857 Slog.wtf(TAG, "Package was null!", new Throwable()); 8858 return; 8859 } 8860 clearAppProfilesLeafLIF(pkg); 8861 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8862 for (int i = 0; i < childCount; i++) { 8863 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 8864 } 8865 } 8866 8867 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 8868 try { 8869 mInstaller.clearAppProfiles(pkg.packageName); 8870 } catch (InstallerException e) { 8871 Slog.w(TAG, String.valueOf(e)); 8872 } 8873 } 8874 8875 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 8876 long lastUpdateTime) { 8877 // Set parent install/update time 8878 PackageSetting ps = (PackageSetting) pkg.mExtras; 8879 if (ps != null) { 8880 ps.firstInstallTime = firstInstallTime; 8881 ps.lastUpdateTime = lastUpdateTime; 8882 } 8883 // Set children install/update time 8884 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8885 for (int i = 0; i < childCount; i++) { 8886 PackageParser.Package childPkg = pkg.childPackages.get(i); 8887 ps = (PackageSetting) childPkg.mExtras; 8888 if (ps != null) { 8889 ps.firstInstallTime = firstInstallTime; 8890 ps.lastUpdateTime = lastUpdateTime; 8891 } 8892 } 8893 } 8894 8895 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 8896 PackageParser.Package changingLib) { 8897 if (file.path != null) { 8898 usesLibraryFiles.add(file.path); 8899 return; 8900 } 8901 PackageParser.Package p = mPackages.get(file.apk); 8902 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 8903 // If we are doing this while in the middle of updating a library apk, 8904 // then we need to make sure to use that new apk for determining the 8905 // dependencies here. (We haven't yet finished committing the new apk 8906 // to the package manager state.) 8907 if (p == null || p.packageName.equals(changingLib.packageName)) { 8908 p = changingLib; 8909 } 8910 } 8911 if (p != null) { 8912 usesLibraryFiles.addAll(p.getAllCodePaths()); 8913 } 8914 } 8915 8916 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 8917 PackageParser.Package changingLib) throws PackageManagerException { 8918 if (pkg == null) { 8919 return; 8920 } 8921 ArraySet<String> usesLibraryFiles = null; 8922 if (pkg.usesLibraries != null) { 8923 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 8924 null, null, pkg.packageName, changingLib, true, null); 8925 } 8926 if (pkg.usesStaticLibraries != null) { 8927 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 8928 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 8929 pkg.packageName, changingLib, true, usesLibraryFiles); 8930 } 8931 if (pkg.usesOptionalLibraries != null) { 8932 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 8933 null, null, pkg.packageName, changingLib, false, usesLibraryFiles); 8934 } 8935 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 8936 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 8937 } else { 8938 pkg.usesLibraryFiles = null; 8939 } 8940 } 8941 8942 private ArraySet<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 8943 @Nullable int[] requiredVersions, @Nullable String[] requiredCertDigests, 8944 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 8945 boolean required, @Nullable ArraySet<String> outUsedLibraries) 8946 throws PackageManagerException { 8947 final int libCount = requestedLibraries.size(); 8948 for (int i = 0; i < libCount; i++) { 8949 final String libName = requestedLibraries.get(i); 8950 final int libVersion = requiredVersions != null ? requiredVersions[i] 8951 : SharedLibraryInfo.VERSION_UNDEFINED; 8952 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 8953 if (libEntry == null) { 8954 if (required) { 8955 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8956 "Package " + packageName + " requires unavailable shared library " 8957 + libName + "; failing!"); 8958 } else { 8959 Slog.w(TAG, "Package " + packageName 8960 + " desires unavailable shared library " 8961 + libName + "; ignoring!"); 8962 } 8963 } else { 8964 if (requiredVersions != null && requiredCertDigests != null) { 8965 if (libEntry.info.getVersion() != requiredVersions[i]) { 8966 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8967 "Package " + packageName + " requires unavailable static shared" 8968 + " library " + libName + " version " 8969 + libEntry.info.getVersion() + "; failing!"); 8970 } 8971 8972 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 8973 if (libPkg == null) { 8974 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8975 "Package " + packageName + " requires unavailable static shared" 8976 + " library; failing!"); 8977 } 8978 8979 String expectedCertDigest = requiredCertDigests[i]; 8980 String libCertDigest = PackageUtils.computeCertSha256Digest( 8981 libPkg.mSignatures[0]); 8982 if (!libCertDigest.equalsIgnoreCase(expectedCertDigest)) { 8983 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8984 "Package " + packageName + " requires differently signed" + 8985 " static shared library; failing!"); 8986 } 8987 } 8988 8989 if (outUsedLibraries == null) { 8990 outUsedLibraries = new ArraySet<>(); 8991 } 8992 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 8993 } 8994 } 8995 return outUsedLibraries; 8996 } 8997 8998 private static boolean hasString(List<String> list, List<String> which) { 8999 if (list == null) { 9000 return false; 9001 } 9002 for (int i=list.size()-1; i>=0; i--) { 9003 for (int j=which.size()-1; j>=0; j--) { 9004 if (which.get(j).equals(list.get(i))) { 9005 return true; 9006 } 9007 } 9008 } 9009 return false; 9010 } 9011 9012 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9013 PackageParser.Package changingPkg) { 9014 ArrayList<PackageParser.Package> res = null; 9015 for (PackageParser.Package pkg : mPackages.values()) { 9016 if (changingPkg != null 9017 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9018 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9019 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9020 changingPkg.staticSharedLibName)) { 9021 return null; 9022 } 9023 if (res == null) { 9024 res = new ArrayList<>(); 9025 } 9026 res.add(pkg); 9027 try { 9028 updateSharedLibrariesLPr(pkg, changingPkg); 9029 } catch (PackageManagerException e) { 9030 // If a system app update or an app and a required lib missing we 9031 // delete the package and for updated system apps keep the data as 9032 // it is better for the user to reinstall than to be in an limbo 9033 // state. Also libs disappearing under an app should never happen 9034 // - just in case. 9035 if (!pkg.isSystemApp() || pkg.isUpdatedSystemApp()) { 9036 final int flags = pkg.isUpdatedSystemApp() 9037 ? PackageManager.DELETE_KEEP_DATA : 0; 9038 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9039 flags , null, true, null); 9040 } 9041 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9042 } 9043 } 9044 return res; 9045 } 9046 9047 /** 9048 * Derive the value of the {@code cpuAbiOverride} based on the provided 9049 * value and an optional stored value from the package settings. 9050 */ 9051 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 9052 String cpuAbiOverride = null; 9053 9054 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 9055 cpuAbiOverride = null; 9056 } else if (abiOverride != null) { 9057 cpuAbiOverride = abiOverride; 9058 } else if (settings != null) { 9059 cpuAbiOverride = settings.cpuAbiOverrideString; 9060 } 9061 9062 return cpuAbiOverride; 9063 } 9064 9065 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9066 final int policyFlags, int scanFlags, long currentTime, @Nullable UserHandle user) 9067 throws PackageManagerException { 9068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9069 // If the package has children and this is the first dive in the function 9070 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9071 // whether all packages (parent and children) would be successfully scanned 9072 // before the actual scan since scanning mutates internal state and we want 9073 // to atomically install the package and its children. 9074 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9075 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9076 scanFlags |= SCAN_CHECK_ONLY; 9077 } 9078 } else { 9079 scanFlags &= ~SCAN_CHECK_ONLY; 9080 } 9081 9082 final PackageParser.Package scannedPkg; 9083 try { 9084 // Scan the parent 9085 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 9086 // Scan the children 9087 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9088 for (int i = 0; i < childCount; i++) { 9089 PackageParser.Package childPkg = pkg.childPackages.get(i); 9090 scanPackageLI(childPkg, policyFlags, 9091 scanFlags, currentTime, user); 9092 } 9093 } finally { 9094 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9095 } 9096 9097 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9098 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 9099 } 9100 9101 return scannedPkg; 9102 } 9103 9104 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 9105 int scanFlags, long currentTime, @Nullable UserHandle user) 9106 throws PackageManagerException { 9107 boolean success = false; 9108 try { 9109 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 9110 currentTime, user); 9111 success = true; 9112 return res; 9113 } finally { 9114 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9115 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9116 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9117 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9118 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9119 } 9120 } 9121 } 9122 9123 /** 9124 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 9125 */ 9126 private static boolean apkHasCode(String fileName) { 9127 StrictJarFile jarFile = null; 9128 try { 9129 jarFile = new StrictJarFile(fileName, 9130 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 9131 return jarFile.findEntry("classes.dex") != null; 9132 } catch (IOException ignore) { 9133 } finally { 9134 try { 9135 if (jarFile != null) { 9136 jarFile.close(); 9137 } 9138 } catch (IOException ignore) {} 9139 } 9140 return false; 9141 } 9142 9143 /** 9144 * Enforces code policy for the package. This ensures that if an APK has 9145 * declared hasCode="true" in its manifest that the APK actually contains 9146 * code. 9147 * 9148 * @throws PackageManagerException If bytecode could not be found when it should exist 9149 */ 9150 private static void assertCodePolicy(PackageParser.Package pkg) 9151 throws PackageManagerException { 9152 final boolean shouldHaveCode = 9153 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 9154 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 9155 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9156 "Package " + pkg.baseCodePath + " code is missing"); 9157 } 9158 9159 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9160 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9161 final boolean splitShouldHaveCode = 9162 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 9163 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 9164 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9165 "Package " + pkg.splitCodePaths[i] + " code is missing"); 9166 } 9167 } 9168 } 9169 } 9170 9171 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 9172 final int policyFlags, final int scanFlags, long currentTime, @Nullable UserHandle user) 9173 throws PackageManagerException { 9174 if (DEBUG_PACKAGE_SCANNING) { 9175 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9176 Log.d(TAG, "Scanning package " + pkg.packageName); 9177 } 9178 9179 applyPolicy(pkg, policyFlags); 9180 9181 assertPackageIsValid(pkg, policyFlags, scanFlags); 9182 9183 // Initialize package source and resource directories 9184 final File scanFile = new File(pkg.codePath); 9185 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 9186 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 9187 9188 SharedUserSetting suid = null; 9189 PackageSetting pkgSetting = null; 9190 9191 // Getting the package setting may have a side-effect, so if we 9192 // are only checking if scan would succeed, stash a copy of the 9193 // old setting to restore at the end. 9194 PackageSetting nonMutatedPs = null; 9195 9196 // We keep references to the derived CPU Abis from settings in oder to reuse 9197 // them in the case where we're not upgrading or booting for the first time. 9198 String primaryCpuAbiFromSettings = null; 9199 String secondaryCpuAbiFromSettings = null; 9200 9201 // writer 9202 synchronized (mPackages) { 9203 if (pkg.mSharedUserId != null) { 9204 // SIDE EFFECTS; may potentially allocate a new shared user 9205 suid = mSettings.getSharedUserLPw( 9206 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9207 if (DEBUG_PACKAGE_SCANNING) { 9208 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 9209 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 9210 + "): packages=" + suid.packages); 9211 } 9212 } 9213 9214 // Check if we are renaming from an original package name. 9215 PackageSetting origPackage = null; 9216 String realName = null; 9217 if (pkg.mOriginalPackages != null) { 9218 // This package may need to be renamed to a previously 9219 // installed name. Let's check on that... 9220 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9221 if (pkg.mOriginalPackages.contains(renamed)) { 9222 // This package had originally been installed as the 9223 // original name, and we have already taken care of 9224 // transitioning to the new one. Just update the new 9225 // one to continue using the old name. 9226 realName = pkg.mRealPackage; 9227 if (!pkg.packageName.equals(renamed)) { 9228 // Callers into this function may have already taken 9229 // care of renaming the package; only do it here if 9230 // it is not already done. 9231 pkg.setPackageName(renamed); 9232 } 9233 } else { 9234 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 9235 if ((origPackage = mSettings.getPackageLPr( 9236 pkg.mOriginalPackages.get(i))) != null) { 9237 // We do have the package already installed under its 9238 // original name... should we use it? 9239 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 9240 // New package is not compatible with original. 9241 origPackage = null; 9242 continue; 9243 } else if (origPackage.sharedUser != null) { 9244 // Make sure uid is compatible between packages. 9245 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 9246 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 9247 + " to " + pkg.packageName + ": old uid " 9248 + origPackage.sharedUser.name 9249 + " differs from " + pkg.mSharedUserId); 9250 origPackage = null; 9251 continue; 9252 } 9253 // TODO: Add case when shared user id is added [b/28144775] 9254 } else { 9255 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 9256 + pkg.packageName + " to old name " + origPackage.name); 9257 } 9258 break; 9259 } 9260 } 9261 } 9262 } 9263 9264 if (mTransferedPackages.contains(pkg.packageName)) { 9265 Slog.w(TAG, "Package " + pkg.packageName 9266 + " was transferred to another, but its .apk remains"); 9267 } 9268 9269 // See comments in nonMutatedPs declaration 9270 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9271 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9272 if (foundPs != null) { 9273 nonMutatedPs = new PackageSetting(foundPs); 9274 } 9275 } 9276 9277 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 9278 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 9279 if (foundPs != null) { 9280 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 9281 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 9282 } 9283 } 9284 9285 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9286 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 9287 PackageManagerService.reportSettingsProblem(Log.WARN, 9288 "Package " + pkg.packageName + " shared user changed from " 9289 + (pkgSetting.sharedUser != null 9290 ? pkgSetting.sharedUser.name : "<nothing>") 9291 + " to " 9292 + (suid != null ? suid.name : "<nothing>") 9293 + "; replacing with new"); 9294 pkgSetting = null; 9295 } 9296 final PackageSetting oldPkgSetting = 9297 pkgSetting == null ? null : new PackageSetting(pkgSetting); 9298 final PackageSetting disabledPkgSetting = 9299 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9300 9301 String[] usesStaticLibraries = null; 9302 if (pkg.usesStaticLibraries != null) { 9303 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 9304 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 9305 } 9306 9307 if (pkgSetting == null) { 9308 final String parentPackageName = (pkg.parentPackage != null) 9309 ? pkg.parentPackage.packageName : null; 9310 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 9311 // REMOVE SharedUserSetting from method; update in a separate call 9312 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 9313 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 9314 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 9315 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 9316 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 9317 true /*allowInstall*/, instantApp, parentPackageName, 9318 pkg.getChildPackageNames(), UserManagerService.getInstance(), 9319 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 9320 // SIDE EFFECTS; updates system state; move elsewhere 9321 if (origPackage != null) { 9322 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 9323 } 9324 mSettings.addUserToSettingLPw(pkgSetting); 9325 } else { 9326 // REMOVE SharedUserSetting from method; update in a separate call. 9327 // 9328 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 9329 // secondaryCpuAbi are not known at this point so we always update them 9330 // to null here, only to reset them at a later point. 9331 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 9332 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 9333 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 9334 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 9335 UserManagerService.getInstance(), usesStaticLibraries, 9336 pkg.usesStaticLibrariesVersions); 9337 } 9338 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 9339 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9340 9341 // SIDE EFFECTS; modifies system state; move elsewhere 9342 if (pkgSetting.origPackage != null) { 9343 // If we are first transitioning from an original package, 9344 // fix up the new package's name now. We need to do this after 9345 // looking up the package under its new name, so getPackageLP 9346 // can take care of fiddling things correctly. 9347 pkg.setPackageName(origPackage.name); 9348 9349 // File a report about this. 9350 String msg = "New package " + pkgSetting.realName 9351 + " renamed to replace old package " + pkgSetting.name; 9352 reportSettingsProblem(Log.WARN, msg); 9353 9354 // Make a note of it. 9355 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9356 mTransferedPackages.add(origPackage.name); 9357 } 9358 9359 // No longer need to retain this. 9360 pkgSetting.origPackage = null; 9361 } 9362 9363 // SIDE EFFECTS; modifies system state; move elsewhere 9364 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 9365 // Make a note of it. 9366 mTransferedPackages.add(pkg.packageName); 9367 } 9368 9369 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 9370 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 9371 } 9372 9373 if ((scanFlags & SCAN_BOOTING) == 0 9374 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9375 // Check all shared libraries and map to their actual file path. 9376 // We only do this here for apps not on a system dir, because those 9377 // are the only ones that can fail an install due to this. We 9378 // will take care of the system apps by updating all of their 9379 // library paths after the scan is done. Also during the initial 9380 // scan don't update any libs as we do this wholesale after all 9381 // apps are scanned to avoid dependency based scanning. 9382 updateSharedLibrariesLPr(pkg, null); 9383 } 9384 9385 if (mFoundPolicyFile) { 9386 SELinuxMMAC.assignSeInfoValue(pkg); 9387 } 9388 pkg.applicationInfo.uid = pkgSetting.appId; 9389 pkg.mExtras = pkgSetting; 9390 9391 9392 // Static shared libs have same package with different versions where 9393 // we internally use a synthetic package name to allow multiple versions 9394 // of the same package, therefore we need to compare signatures against 9395 // the package setting for the latest library version. 9396 PackageSetting signatureCheckPs = pkgSetting; 9397 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9398 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9399 if (libraryEntry != null) { 9400 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9401 } 9402 } 9403 9404 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 9405 if (checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 9406 // We just determined the app is signed correctly, so bring 9407 // over the latest parsed certs. 9408 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9409 } else { 9410 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9411 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9412 "Package " + pkg.packageName + " upgrade keys do not match the " 9413 + "previously installed version"); 9414 } else { 9415 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9416 String msg = "System package " + pkg.packageName 9417 + " signature changed; retaining data."; 9418 reportSettingsProblem(Log.WARN, msg); 9419 } 9420 } 9421 } else { 9422 try { 9423 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 9424 verifySignaturesLP(signatureCheckPs, pkg); 9425 // We just determined the app is signed correctly, so bring 9426 // over the latest parsed certs. 9427 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9428 } catch (PackageManagerException e) { 9429 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9430 throw e; 9431 } 9432 // The signature has changed, but this package is in the system 9433 // image... let's recover! 9434 pkgSetting.signatures.mSignatures = pkg.mSignatures; 9435 // However... if this package is part of a shared user, but it 9436 // doesn't match the signature of the shared user, let's fail. 9437 // What this means is that you can't change the signatures 9438 // associated with an overall shared user, which doesn't seem all 9439 // that unreasonable. 9440 if (signatureCheckPs.sharedUser != null) { 9441 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9442 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 9443 throw new PackageManagerException( 9444 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9445 "Signature mismatch for shared user: " 9446 + pkgSetting.sharedUser); 9447 } 9448 } 9449 // File a report about this. 9450 String msg = "System package " + pkg.packageName 9451 + " signature changed; retaining data."; 9452 reportSettingsProblem(Log.WARN, msg); 9453 } 9454 } 9455 9456 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9457 // This package wants to adopt ownership of permissions from 9458 // another package. 9459 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9460 final String origName = pkg.mAdoptPermissions.get(i); 9461 final PackageSetting orig = mSettings.getPackageLPr(origName); 9462 if (orig != null) { 9463 if (verifyPackageUpdateLPr(orig, pkg)) { 9464 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9465 + pkg.packageName); 9466 // SIDE EFFECTS; updates permissions system state; move elsewhere 9467 mSettings.transferPermissionsLPw(origName, pkg.packageName); 9468 } 9469 } 9470 } 9471 } 9472 } 9473 9474 pkg.applicationInfo.processName = fixProcessName( 9475 pkg.applicationInfo.packageName, 9476 pkg.applicationInfo.processName); 9477 9478 if (pkg != mPlatformPackage) { 9479 // Get all of our default paths setup 9480 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 9481 } 9482 9483 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 9484 9485 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 9486 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 9487 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 9488 derivePackageAbi( 9489 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 9490 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9491 9492 // Some system apps still use directory structure for native libraries 9493 // in which case we might end up not detecting abi solely based on apk 9494 // structure. Try to detect abi based on directory structure. 9495 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 9496 pkg.applicationInfo.primaryCpuAbi == null) { 9497 setBundledAppAbisAndRoots(pkg, pkgSetting); 9498 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9499 } 9500 } else { 9501 // This is not a first boot or an upgrade, don't bother deriving the 9502 // ABI during the scan. Instead, trust the value that was stored in the 9503 // package setting. 9504 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 9505 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 9506 9507 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9508 9509 if (DEBUG_ABI_SELECTION) { 9510 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 9511 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 9512 pkg.applicationInfo.secondaryCpuAbi); 9513 } 9514 } 9515 } else { 9516 if ((scanFlags & SCAN_MOVE) != 0) { 9517 // We haven't run dex-opt for this move (since we've moved the compiled output too) 9518 // but we already have this packages package info in the PackageSetting. We just 9519 // use that and derive the native library path based on the new codepath. 9520 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 9521 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 9522 } 9523 9524 // Set native library paths again. For moves, the path will be updated based on the 9525 // ABIs we've determined above. For non-moves, the path will be updated based on the 9526 // ABIs we determined during compilation, but the path will depend on the final 9527 // package path (after the rename away from the stage path). 9528 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 9529 } 9530 9531 // This is a special case for the "system" package, where the ABI is 9532 // dictated by the zygote configuration (and init.rc). We should keep track 9533 // of this ABI so that we can deal with "normal" applications that run under 9534 // the same UID correctly. 9535 if (mPlatformPackage == pkg) { 9536 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 9537 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 9538 } 9539 9540 // If there's a mismatch between the abi-override in the package setting 9541 // and the abiOverride specified for the install. Warn about this because we 9542 // would've already compiled the app without taking the package setting into 9543 // account. 9544 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 9545 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 9546 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 9547 " for package " + pkg.packageName); 9548 } 9549 } 9550 9551 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9552 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9553 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 9554 9555 // Copy the derived override back to the parsed package, so that we can 9556 // update the package settings accordingly. 9557 pkg.cpuAbiOverride = cpuAbiOverride; 9558 9559 if (DEBUG_ABI_SELECTION) { 9560 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 9561 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 9562 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 9563 } 9564 9565 // Push the derived path down into PackageSettings so we know what to 9566 // clean up at uninstall time. 9567 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 9568 9569 if (DEBUG_ABI_SELECTION) { 9570 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 9571 " primary=" + pkg.applicationInfo.primaryCpuAbi + 9572 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 9573 } 9574 9575 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 9576 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 9577 // We don't do this here during boot because we can do it all 9578 // at once after scanning all existing packages. 9579 // 9580 // We also do this *before* we perform dexopt on this package, so that 9581 // we can avoid redundant dexopts, and also to make sure we've got the 9582 // code and package path correct. 9583 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 9584 } 9585 9586 if (mFactoryTest && pkg.requestedPermissions.contains( 9587 android.Manifest.permission.FACTORY_TEST)) { 9588 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 9589 } 9590 9591 if (isSystemApp(pkg)) { 9592 pkgSetting.isOrphaned = true; 9593 } 9594 9595 // Take care of first install / last update times. 9596 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 9597 if (currentTime != 0) { 9598 if (pkgSetting.firstInstallTime == 0) { 9599 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 9600 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 9601 pkgSetting.lastUpdateTime = currentTime; 9602 } 9603 } else if (pkgSetting.firstInstallTime == 0) { 9604 // We need *something*. Take time time stamp of the file. 9605 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 9606 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 9607 if (scanFileTime != pkgSetting.timeStamp) { 9608 // A package on the system image has changed; consider this 9609 // to be an update. 9610 pkgSetting.lastUpdateTime = scanFileTime; 9611 } 9612 } 9613 pkgSetting.setTimeStamp(scanFileTime); 9614 9615 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9616 if (nonMutatedPs != null) { 9617 synchronized (mPackages) { 9618 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 9619 } 9620 } 9621 } else { 9622 final int userId = user == null ? 0 : user.getIdentifier(); 9623 // Modify state for the given package setting 9624 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 9625 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 9626 if (pkgSetting.getInstantApp(userId)) { 9627 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 9628 } 9629 } 9630 return pkg; 9631 } 9632 9633 /** 9634 * Applies policy to the parsed package based upon the given policy flags. 9635 * Ensures the package is in a good state. 9636 * <p> 9637 * Implementation detail: This method must NOT have any side effect. It would 9638 * ideally be static, but, it requires locks to read system state. 9639 */ 9640 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 9641 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 9642 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 9643 if (pkg.applicationInfo.isDirectBootAware()) { 9644 // we're direct boot aware; set for all components 9645 for (PackageParser.Service s : pkg.services) { 9646 s.info.encryptionAware = s.info.directBootAware = true; 9647 } 9648 for (PackageParser.Provider p : pkg.providers) { 9649 p.info.encryptionAware = p.info.directBootAware = true; 9650 } 9651 for (PackageParser.Activity a : pkg.activities) { 9652 a.info.encryptionAware = a.info.directBootAware = true; 9653 } 9654 for (PackageParser.Activity r : pkg.receivers) { 9655 r.info.encryptionAware = r.info.directBootAware = true; 9656 } 9657 } 9658 } else { 9659 // Only allow system apps to be flagged as core apps. 9660 pkg.coreApp = false; 9661 // clear flags not applicable to regular apps 9662 pkg.applicationInfo.privateFlags &= 9663 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 9664 pkg.applicationInfo.privateFlags &= 9665 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 9666 } 9667 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 9668 9669 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 9670 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 9671 } 9672 9673 if (!isSystemApp(pkg)) { 9674 // Only system apps can use these features. 9675 pkg.mOriginalPackages = null; 9676 pkg.mRealPackage = null; 9677 pkg.mAdoptPermissions = null; 9678 } 9679 } 9680 9681 /** 9682 * Asserts the parsed package is valid according to the given policy. If the 9683 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 9684 * <p> 9685 * Implementation detail: This method must NOT have any side effects. It would 9686 * ideally be static, but, it requires locks to read system state. 9687 * 9688 * @throws PackageManagerException If the package fails any of the validation checks 9689 */ 9690 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 9691 throws PackageManagerException { 9692 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 9693 assertCodePolicy(pkg); 9694 } 9695 9696 if (pkg.applicationInfo.getCodePath() == null || 9697 pkg.applicationInfo.getResourcePath() == null) { 9698 // Bail out. The resource and code paths haven't been set. 9699 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 9700 "Code and resource paths haven't been set correctly"); 9701 } 9702 9703 // Make sure we're not adding any bogus keyset info 9704 KeySetManagerService ksms = mSettings.mKeySetManagerService; 9705 ksms.assertScannedPackageValid(pkg); 9706 9707 synchronized (mPackages) { 9708 // The special "android" package can only be defined once 9709 if (pkg.packageName.equals("android")) { 9710 if (mAndroidApplication != null) { 9711 Slog.w(TAG, "*************************************************"); 9712 Slog.w(TAG, "Core android package being redefined. Skipping."); 9713 Slog.w(TAG, " codePath=" + pkg.codePath); 9714 Slog.w(TAG, "*************************************************"); 9715 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9716 "Core android package being redefined. Skipping."); 9717 } 9718 } 9719 9720 // A package name must be unique; don't allow duplicates 9721 if (mPackages.containsKey(pkg.packageName)) { 9722 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 9723 "Application package " + pkg.packageName 9724 + " already installed. Skipping duplicate."); 9725 } 9726 9727 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9728 // Static libs have a synthetic package name containing the version 9729 // but we still want the base name to be unique. 9730 if (mPackages.containsKey(pkg.manifestPackageName)) { 9731 throw new PackageManagerException( 9732 "Duplicate static shared lib provider package"); 9733 } 9734 9735 // Static shared libraries should have at least O target SDK 9736 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 9737 throw new PackageManagerException( 9738 "Packages declaring static-shared libs must target O SDK or higher"); 9739 } 9740 9741 // Package declaring static a shared lib cannot be instant apps 9742 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 9743 throw new PackageManagerException( 9744 "Packages declaring static-shared libs cannot be instant apps"); 9745 } 9746 9747 // Package declaring static a shared lib cannot be renamed since the package 9748 // name is synthetic and apps can't code around package manager internals. 9749 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 9750 throw new PackageManagerException( 9751 "Packages declaring static-shared libs cannot be renamed"); 9752 } 9753 9754 // Package declaring static a shared lib cannot declare child packages 9755 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 9756 throw new PackageManagerException( 9757 "Packages declaring static-shared libs cannot have child packages"); 9758 } 9759 9760 // Package declaring static a shared lib cannot declare dynamic libs 9761 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 9762 throw new PackageManagerException( 9763 "Packages declaring static-shared libs cannot declare dynamic libs"); 9764 } 9765 9766 // Package declaring static a shared lib cannot declare shared users 9767 if (pkg.mSharedUserId != null) { 9768 throw new PackageManagerException( 9769 "Packages declaring static-shared libs cannot declare shared users"); 9770 } 9771 9772 // Static shared libs cannot declare activities 9773 if (!pkg.activities.isEmpty()) { 9774 throw new PackageManagerException( 9775 "Static shared libs cannot declare activities"); 9776 } 9777 9778 // Static shared libs cannot declare services 9779 if (!pkg.services.isEmpty()) { 9780 throw new PackageManagerException( 9781 "Static shared libs cannot declare services"); 9782 } 9783 9784 // Static shared libs cannot declare providers 9785 if (!pkg.providers.isEmpty()) { 9786 throw new PackageManagerException( 9787 "Static shared libs cannot declare content providers"); 9788 } 9789 9790 // Static shared libs cannot declare receivers 9791 if (!pkg.receivers.isEmpty()) { 9792 throw new PackageManagerException( 9793 "Static shared libs cannot declare broadcast receivers"); 9794 } 9795 9796 // Static shared libs cannot declare permission groups 9797 if (!pkg.permissionGroups.isEmpty()) { 9798 throw new PackageManagerException( 9799 "Static shared libs cannot declare permission groups"); 9800 } 9801 9802 // Static shared libs cannot declare permissions 9803 if (!pkg.permissions.isEmpty()) { 9804 throw new PackageManagerException( 9805 "Static shared libs cannot declare permissions"); 9806 } 9807 9808 // Static shared libs cannot declare protected broadcasts 9809 if (pkg.protectedBroadcasts != null) { 9810 throw new PackageManagerException( 9811 "Static shared libs cannot declare protected broadcasts"); 9812 } 9813 9814 // Static shared libs cannot be overlay targets 9815 if (pkg.mOverlayTarget != null) { 9816 throw new PackageManagerException( 9817 "Static shared libs cannot be overlay targets"); 9818 } 9819 9820 // The version codes must be ordered as lib versions 9821 int minVersionCode = Integer.MIN_VALUE; 9822 int maxVersionCode = Integer.MAX_VALUE; 9823 9824 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9825 pkg.staticSharedLibName); 9826 if (versionedLib != null) { 9827 final int versionCount = versionedLib.size(); 9828 for (int i = 0; i < versionCount; i++) { 9829 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 9830 // TODO: We will change version code to long, so in the new API it is long 9831 final int libVersionCode = (int) libInfo.getDeclaringPackage() 9832 .getVersionCode(); 9833 if (libInfo.getVersion() < pkg.staticSharedLibVersion) { 9834 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 9835 } else if (libInfo.getVersion() > pkg.staticSharedLibVersion) { 9836 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 9837 } else { 9838 minVersionCode = maxVersionCode = libVersionCode; 9839 break; 9840 } 9841 } 9842 } 9843 if (pkg.mVersionCode < minVersionCode || pkg.mVersionCode > maxVersionCode) { 9844 throw new PackageManagerException("Static shared" 9845 + " lib version codes must be ordered as lib versions"); 9846 } 9847 } 9848 9849 // Only privileged apps and updated privileged apps can add child packages. 9850 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 9851 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 9852 throw new PackageManagerException("Only privileged apps can add child " 9853 + "packages. Ignoring package " + pkg.packageName); 9854 } 9855 final int childCount = pkg.childPackages.size(); 9856 for (int i = 0; i < childCount; i++) { 9857 PackageParser.Package childPkg = pkg.childPackages.get(i); 9858 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 9859 childPkg.packageName)) { 9860 throw new PackageManagerException("Can't override child of " 9861 + "another disabled app. Ignoring package " + pkg.packageName); 9862 } 9863 } 9864 } 9865 9866 // If we're only installing presumed-existing packages, require that the 9867 // scanned APK is both already known and at the path previously established 9868 // for it. Previously unknown packages we pick up normally, but if we have an 9869 // a priori expectation about this package's install presence, enforce it. 9870 // With a singular exception for new system packages. When an OTA contains 9871 // a new system package, we allow the codepath to change from a system location 9872 // to the user-installed location. If we don't allow this change, any newer, 9873 // user-installed version of the application will be ignored. 9874 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 9875 if (mExpectingBetter.containsKey(pkg.packageName)) { 9876 logCriticalInfo(Log.WARN, 9877 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 9878 } else { 9879 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 9880 if (known != null) { 9881 if (DEBUG_PACKAGE_SCANNING) { 9882 Log.d(TAG, "Examining " + pkg.codePath 9883 + " and requiring known paths " + known.codePathString 9884 + " & " + known.resourcePathString); 9885 } 9886 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 9887 || !pkg.applicationInfo.getResourcePath().equals( 9888 known.resourcePathString)) { 9889 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 9890 "Application package " + pkg.packageName 9891 + " found at " + pkg.applicationInfo.getCodePath() 9892 + " but expected at " + known.codePathString 9893 + "; ignoring."); 9894 } 9895 } 9896 } 9897 } 9898 9899 // Verify that this new package doesn't have any content providers 9900 // that conflict with existing packages. Only do this if the 9901 // package isn't already installed, since we don't want to break 9902 // things that are installed. 9903 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 9904 final int N = pkg.providers.size(); 9905 int i; 9906 for (i=0; i<N; i++) { 9907 PackageParser.Provider p = pkg.providers.get(i); 9908 if (p.info.authority != null) { 9909 String names[] = p.info.authority.split(";"); 9910 for (int j = 0; j < names.length; j++) { 9911 if (mProvidersByAuthority.containsKey(names[j])) { 9912 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9913 final String otherPackageName = 9914 ((other != null && other.getComponentName() != null) ? 9915 other.getComponentName().getPackageName() : "?"); 9916 throw new PackageManagerException( 9917 INSTALL_FAILED_CONFLICTING_PROVIDER, 9918 "Can't install because provider name " + names[j] 9919 + " (in package " + pkg.applicationInfo.packageName 9920 + ") is already used by " + otherPackageName); 9921 } 9922 } 9923 } 9924 } 9925 } 9926 } 9927 } 9928 9929 private boolean addSharedLibraryLPw(String path, String apk, String name, int version, 9930 int type, String declaringPackageName, int declaringVersionCode) { 9931 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9932 if (versionedLib == null) { 9933 versionedLib = new SparseArray<>(); 9934 mSharedLibraries.put(name, versionedLib); 9935 if (type == SharedLibraryInfo.TYPE_STATIC) { 9936 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 9937 } 9938 } else if (versionedLib.indexOfKey(version) >= 0) { 9939 return false; 9940 } 9941 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 9942 version, type, declaringPackageName, declaringVersionCode); 9943 versionedLib.put(version, libEntry); 9944 return true; 9945 } 9946 9947 private boolean removeSharedLibraryLPw(String name, int version) { 9948 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9949 if (versionedLib == null) { 9950 return false; 9951 } 9952 final int libIdx = versionedLib.indexOfKey(version); 9953 if (libIdx < 0) { 9954 return false; 9955 } 9956 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 9957 versionedLib.remove(version); 9958 if (versionedLib.size() <= 0) { 9959 mSharedLibraries.remove(name); 9960 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 9961 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 9962 .getPackageName()); 9963 } 9964 } 9965 return true; 9966 } 9967 9968 /** 9969 * Adds a scanned package to the system. When this method is finished, the package will 9970 * be available for query, resolution, etc... 9971 */ 9972 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 9973 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 9974 final String pkgName = pkg.packageName; 9975 if (mCustomResolverComponentName != null && 9976 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 9977 setUpCustomResolverActivity(pkg); 9978 } 9979 9980 if (pkg.packageName.equals("android")) { 9981 synchronized (mPackages) { 9982 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9983 // Set up information for our fall-back user intent resolution activity. 9984 mPlatformPackage = pkg; 9985 pkg.mVersionCode = mSdkVersion; 9986 mAndroidApplication = pkg.applicationInfo; 9987 if (!mResolverReplaced) { 9988 mResolveActivity.applicationInfo = mAndroidApplication; 9989 mResolveActivity.name = ResolverActivity.class.getName(); 9990 mResolveActivity.packageName = mAndroidApplication.packageName; 9991 mResolveActivity.processName = "system:ui"; 9992 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9993 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 9994 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 9995 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 9996 mResolveActivity.exported = true; 9997 mResolveActivity.enabled = true; 9998 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 9999 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10000 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10001 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10002 | ActivityInfo.CONFIG_ORIENTATION 10003 | ActivityInfo.CONFIG_KEYBOARD 10004 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10005 mResolveInfo.activityInfo = mResolveActivity; 10006 mResolveInfo.priority = 0; 10007 mResolveInfo.preferredOrder = 0; 10008 mResolveInfo.match = 0; 10009 mResolveComponentName = new ComponentName( 10010 mAndroidApplication.packageName, mResolveActivity.name); 10011 } 10012 } 10013 } 10014 } 10015 10016 ArrayList<PackageParser.Package> clientLibPkgs = null; 10017 // writer 10018 synchronized (mPackages) { 10019 boolean hasStaticSharedLibs = false; 10020 10021 // Any app can add new static shared libraries 10022 if (pkg.staticSharedLibName != null) { 10023 // Static shared libs don't allow renaming as they have synthetic package 10024 // names to allow install of multiple versions, so use name from manifest. 10025 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10026 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10027 pkg.manifestPackageName, pkg.mVersionCode)) { 10028 hasStaticSharedLibs = true; 10029 } else { 10030 Slog.w(TAG, "Package " + pkg.packageName + " library " 10031 + pkg.staticSharedLibName + " already exists; skipping"); 10032 } 10033 // Static shared libs cannot be updated once installed since they 10034 // use synthetic package name which includes the version code, so 10035 // not need to update other packages's shared lib dependencies. 10036 } 10037 10038 if (!hasStaticSharedLibs 10039 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10040 // Only system apps can add new dynamic shared libraries. 10041 if (pkg.libraryNames != null) { 10042 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10043 String name = pkg.libraryNames.get(i); 10044 boolean allowed = false; 10045 if (pkg.isUpdatedSystemApp()) { 10046 // New library entries can only be added through the 10047 // system image. This is important to get rid of a lot 10048 // of nasty edge cases: for example if we allowed a non- 10049 // system update of the app to add a library, then uninstalling 10050 // the update would make the library go away, and assumptions 10051 // we made such as through app install filtering would now 10052 // have allowed apps on the device which aren't compatible 10053 // with it. Better to just have the restriction here, be 10054 // conservative, and create many fewer cases that can negatively 10055 // impact the user experience. 10056 final PackageSetting sysPs = mSettings 10057 .getDisabledSystemPkgLPr(pkg.packageName); 10058 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10059 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10060 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10061 allowed = true; 10062 break; 10063 } 10064 } 10065 } 10066 } else { 10067 allowed = true; 10068 } 10069 if (allowed) { 10070 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10071 SharedLibraryInfo.VERSION_UNDEFINED, 10072 SharedLibraryInfo.TYPE_DYNAMIC, 10073 pkg.packageName, pkg.mVersionCode)) { 10074 Slog.w(TAG, "Package " + pkg.packageName + " library " 10075 + name + " already exists; skipping"); 10076 } 10077 } else { 10078 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10079 + name + " that is not declared on system image; skipping"); 10080 } 10081 } 10082 10083 if ((scanFlags & SCAN_BOOTING) == 0) { 10084 // If we are not booting, we need to update any applications 10085 // that are clients of our shared library. If we are booting, 10086 // this will all be done once the scan is complete. 10087 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10088 } 10089 } 10090 } 10091 } 10092 10093 if ((scanFlags & SCAN_BOOTING) != 0) { 10094 // No apps can run during boot scan, so they don't need to be frozen 10095 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10096 // Caller asked to not kill app, so it's probably not frozen 10097 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10098 // Caller asked us to ignore frozen check for some reason; they 10099 // probably didn't know the package name 10100 } else { 10101 // We're doing major surgery on this package, so it better be frozen 10102 // right now to keep it from launching 10103 checkPackageFrozen(pkgName); 10104 } 10105 10106 // Also need to kill any apps that are dependent on the library. 10107 if (clientLibPkgs != null) { 10108 for (int i=0; i<clientLibPkgs.size(); i++) { 10109 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10110 killApplication(clientPkg.applicationInfo.packageName, 10111 clientPkg.applicationInfo.uid, "update lib"); 10112 } 10113 } 10114 10115 // writer 10116 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10117 10118 synchronized (mPackages) { 10119 // We don't expect installation to fail beyond this point 10120 10121 // Add the new setting to mSettings 10122 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10123 // Add the new setting to mPackages 10124 mPackages.put(pkg.applicationInfo.packageName, pkg); 10125 // Make sure we don't accidentally delete its data. 10126 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10127 while (iter.hasNext()) { 10128 PackageCleanItem item = iter.next(); 10129 if (pkgName.equals(item.packageName)) { 10130 iter.remove(); 10131 } 10132 } 10133 10134 // Add the package's KeySets to the global KeySetManagerService 10135 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10136 ksms.addScannedPackageLPw(pkg); 10137 10138 int N = pkg.providers.size(); 10139 StringBuilder r = null; 10140 int i; 10141 for (i=0; i<N; i++) { 10142 PackageParser.Provider p = pkg.providers.get(i); 10143 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10144 p.info.processName); 10145 mProviders.addProvider(p); 10146 p.syncable = p.info.isSyncable; 10147 if (p.info.authority != null) { 10148 String names[] = p.info.authority.split(";"); 10149 p.info.authority = null; 10150 for (int j = 0; j < names.length; j++) { 10151 if (j == 1 && p.syncable) { 10152 // We only want the first authority for a provider to possibly be 10153 // syncable, so if we already added this provider using a different 10154 // authority clear the syncable flag. We copy the provider before 10155 // changing it because the mProviders object contains a reference 10156 // to a provider that we don't want to change. 10157 // Only do this for the second authority since the resulting provider 10158 // object can be the same for all future authorities for this provider. 10159 p = new PackageParser.Provider(p); 10160 p.syncable = false; 10161 } 10162 if (!mProvidersByAuthority.containsKey(names[j])) { 10163 mProvidersByAuthority.put(names[j], p); 10164 if (p.info.authority == null) { 10165 p.info.authority = names[j]; 10166 } else { 10167 p.info.authority = p.info.authority + ";" + names[j]; 10168 } 10169 if (DEBUG_PACKAGE_SCANNING) { 10170 if (chatty) 10171 Log.d(TAG, "Registered content provider: " + names[j] 10172 + ", className = " + p.info.name + ", isSyncable = " 10173 + p.info.isSyncable); 10174 } 10175 } else { 10176 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10177 Slog.w(TAG, "Skipping provider name " + names[j] + 10178 " (in package " + pkg.applicationInfo.packageName + 10179 "): name already used by " 10180 + ((other != null && other.getComponentName() != null) 10181 ? other.getComponentName().getPackageName() : "?")); 10182 } 10183 } 10184 } 10185 if (chatty) { 10186 if (r == null) { 10187 r = new StringBuilder(256); 10188 } else { 10189 r.append(' '); 10190 } 10191 r.append(p.info.name); 10192 } 10193 } 10194 if (r != null) { 10195 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 10196 } 10197 10198 N = pkg.services.size(); 10199 r = null; 10200 for (i=0; i<N; i++) { 10201 PackageParser.Service s = pkg.services.get(i); 10202 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 10203 s.info.processName); 10204 mServices.addService(s); 10205 if (chatty) { 10206 if (r == null) { 10207 r = new StringBuilder(256); 10208 } else { 10209 r.append(' '); 10210 } 10211 r.append(s.info.name); 10212 } 10213 } 10214 if (r != null) { 10215 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 10216 } 10217 10218 N = pkg.receivers.size(); 10219 r = null; 10220 for (i=0; i<N; i++) { 10221 PackageParser.Activity a = pkg.receivers.get(i); 10222 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10223 a.info.processName); 10224 mReceivers.addActivity(a, "receiver"); 10225 if (chatty) { 10226 if (r == null) { 10227 r = new StringBuilder(256); 10228 } else { 10229 r.append(' '); 10230 } 10231 r.append(a.info.name); 10232 } 10233 } 10234 if (r != null) { 10235 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 10236 } 10237 10238 N = pkg.activities.size(); 10239 r = null; 10240 for (i=0; i<N; i++) { 10241 PackageParser.Activity a = pkg.activities.get(i); 10242 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 10243 a.info.processName); 10244 mActivities.addActivity(a, "activity"); 10245 if (chatty) { 10246 if (r == null) { 10247 r = new StringBuilder(256); 10248 } else { 10249 r.append(' '); 10250 } 10251 r.append(a.info.name); 10252 } 10253 } 10254 if (r != null) { 10255 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 10256 } 10257 10258 N = pkg.permissionGroups.size(); 10259 r = null; 10260 for (i=0; i<N; i++) { 10261 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 10262 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 10263 final String curPackageName = cur == null ? null : cur.info.packageName; 10264 // Dont allow ephemeral apps to define new permission groups. 10265 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10266 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10267 + pg.info.packageName 10268 + " ignored: instant apps cannot define new permission groups."); 10269 continue; 10270 } 10271 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 10272 if (cur == null || isPackageUpdate) { 10273 mPermissionGroups.put(pg.info.name, pg); 10274 if (chatty) { 10275 if (r == null) { 10276 r = new StringBuilder(256); 10277 } else { 10278 r.append(' '); 10279 } 10280 if (isPackageUpdate) { 10281 r.append("UPD:"); 10282 } 10283 r.append(pg.info.name); 10284 } 10285 } else { 10286 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 10287 + pg.info.packageName + " ignored: original from " 10288 + cur.info.packageName); 10289 if (chatty) { 10290 if (r == null) { 10291 r = new StringBuilder(256); 10292 } else { 10293 r.append(' '); 10294 } 10295 r.append("DUP:"); 10296 r.append(pg.info.name); 10297 } 10298 } 10299 } 10300 if (r != null) { 10301 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 10302 } 10303 10304 N = pkg.permissions.size(); 10305 r = null; 10306 for (i=0; i<N; i++) { 10307 PackageParser.Permission p = pkg.permissions.get(i); 10308 10309 // Dont allow ephemeral apps to define new permissions. 10310 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10311 Slog.w(TAG, "Permission " + p.info.name + " from package " 10312 + p.info.packageName 10313 + " ignored: instant apps cannot define new permissions."); 10314 continue; 10315 } 10316 10317 // Assume by default that we did not install this permission into the system. 10318 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 10319 10320 // Now that permission groups have a special meaning, we ignore permission 10321 // groups for legacy apps to prevent unexpected behavior. In particular, 10322 // permissions for one app being granted to someone just becase they happen 10323 // to be in a group defined by another app (before this had no implications). 10324 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 10325 p.group = mPermissionGroups.get(p.info.group); 10326 // Warn for a permission in an unknown group. 10327 if (p.info.group != null && p.group == null) { 10328 Slog.w(TAG, "Permission " + p.info.name + " from package " 10329 + p.info.packageName + " in an unknown group " + p.info.group); 10330 } 10331 } 10332 10333 ArrayMap<String, BasePermission> permissionMap = 10334 p.tree ? mSettings.mPermissionTrees 10335 : mSettings.mPermissions; 10336 BasePermission bp = permissionMap.get(p.info.name); 10337 10338 // Allow system apps to redefine non-system permissions 10339 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 10340 final boolean currentOwnerIsSystem = (bp.perm != null 10341 && isSystemApp(bp.perm.owner)); 10342 if (isSystemApp(p.owner)) { 10343 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 10344 // It's a built-in permission and no owner, take ownership now 10345 bp.packageSetting = pkgSetting; 10346 bp.perm = p; 10347 bp.uid = pkg.applicationInfo.uid; 10348 bp.sourcePackage = p.info.packageName; 10349 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10350 } else if (!currentOwnerIsSystem) { 10351 String msg = "New decl " + p.owner + " of permission " 10352 + p.info.name + " is system; overriding " + bp.sourcePackage; 10353 reportSettingsProblem(Log.WARN, msg); 10354 bp = null; 10355 } 10356 } 10357 } 10358 10359 if (bp == null) { 10360 bp = new BasePermission(p.info.name, p.info.packageName, 10361 BasePermission.TYPE_NORMAL); 10362 permissionMap.put(p.info.name, bp); 10363 } 10364 10365 if (bp.perm == null) { 10366 if (bp.sourcePackage == null 10367 || bp.sourcePackage.equals(p.info.packageName)) { 10368 BasePermission tree = findPermissionTreeLP(p.info.name); 10369 if (tree == null 10370 || tree.sourcePackage.equals(p.info.packageName)) { 10371 bp.packageSetting = pkgSetting; 10372 bp.perm = p; 10373 bp.uid = pkg.applicationInfo.uid; 10374 bp.sourcePackage = p.info.packageName; 10375 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 10376 if (chatty) { 10377 if (r == null) { 10378 r = new StringBuilder(256); 10379 } else { 10380 r.append(' '); 10381 } 10382 r.append(p.info.name); 10383 } 10384 } else { 10385 Slog.w(TAG, "Permission " + p.info.name + " from package " 10386 + p.info.packageName + " ignored: base tree " 10387 + tree.name + " is from package " 10388 + tree.sourcePackage); 10389 } 10390 } else { 10391 Slog.w(TAG, "Permission " + p.info.name + " from package " 10392 + p.info.packageName + " ignored: original from " 10393 + bp.sourcePackage); 10394 } 10395 } else if (chatty) { 10396 if (r == null) { 10397 r = new StringBuilder(256); 10398 } else { 10399 r.append(' '); 10400 } 10401 r.append("DUP:"); 10402 r.append(p.info.name); 10403 } 10404 if (bp.perm == p) { 10405 bp.protectionLevel = p.info.protectionLevel; 10406 } 10407 } 10408 10409 if (r != null) { 10410 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 10411 } 10412 10413 N = pkg.instrumentation.size(); 10414 r = null; 10415 for (i=0; i<N; i++) { 10416 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10417 a.info.packageName = pkg.applicationInfo.packageName; 10418 a.info.sourceDir = pkg.applicationInfo.sourceDir; 10419 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 10420 a.info.splitNames = pkg.splitNames; 10421 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 10422 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 10423 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 10424 a.info.dataDir = pkg.applicationInfo.dataDir; 10425 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 10426 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 10427 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 10428 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 10429 mInstrumentation.put(a.getComponentName(), a); 10430 if (chatty) { 10431 if (r == null) { 10432 r = new StringBuilder(256); 10433 } else { 10434 r.append(' '); 10435 } 10436 r.append(a.info.name); 10437 } 10438 } 10439 if (r != null) { 10440 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 10441 } 10442 10443 if (pkg.protectedBroadcasts != null) { 10444 N = pkg.protectedBroadcasts.size(); 10445 for (i=0; i<N; i++) { 10446 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 10447 } 10448 } 10449 } 10450 10451 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10452 } 10453 10454 /** 10455 * Derive the ABI of a non-system package located at {@code scanFile}. This information 10456 * is derived purely on the basis of the contents of {@code scanFile} and 10457 * {@code cpuAbiOverride}. 10458 * 10459 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 10460 */ 10461 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 10462 String cpuAbiOverride, boolean extractLibs, 10463 File appLib32InstallDir) 10464 throws PackageManagerException { 10465 // Give ourselves some initial paths; we'll come back for another 10466 // pass once we've determined ABI below. 10467 setNativeLibraryPaths(pkg, appLib32InstallDir); 10468 10469 // We would never need to extract libs for forward-locked and external packages, 10470 // since the container service will do it for us. We shouldn't attempt to 10471 // extract libs from system app when it was not updated. 10472 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 10473 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 10474 extractLibs = false; 10475 } 10476 10477 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 10478 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 10479 10480 NativeLibraryHelper.Handle handle = null; 10481 try { 10482 handle = NativeLibraryHelper.Handle.create(pkg); 10483 // TODO(multiArch): This can be null for apps that didn't go through the 10484 // usual installation process. We can calculate it again, like we 10485 // do during install time. 10486 // 10487 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 10488 // unnecessary. 10489 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 10490 10491 // Null out the abis so that they can be recalculated. 10492 pkg.applicationInfo.primaryCpuAbi = null; 10493 pkg.applicationInfo.secondaryCpuAbi = null; 10494 if (isMultiArch(pkg.applicationInfo)) { 10495 // Warn if we've set an abiOverride for multi-lib packages.. 10496 // By definition, we need to copy both 32 and 64 bit libraries for 10497 // such packages. 10498 if (pkg.cpuAbiOverride != null 10499 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 10500 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 10501 } 10502 10503 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 10504 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 10505 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 10506 if (extractLibs) { 10507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10508 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10509 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 10510 useIsaSpecificSubdirs); 10511 } else { 10512 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10513 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 10514 } 10515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10516 } 10517 10518 maybeThrowExceptionForMultiArchCopy( 10519 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 10520 10521 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 10522 if (extractLibs) { 10523 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10524 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10525 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 10526 useIsaSpecificSubdirs); 10527 } else { 10528 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10529 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 10530 } 10531 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10532 } 10533 10534 maybeThrowExceptionForMultiArchCopy( 10535 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 10536 10537 if (abi64 >= 0) { 10538 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 10539 } 10540 10541 if (abi32 >= 0) { 10542 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 10543 if (abi64 >= 0) { 10544 if (pkg.use32bitAbi) { 10545 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 10546 pkg.applicationInfo.primaryCpuAbi = abi; 10547 } else { 10548 pkg.applicationInfo.secondaryCpuAbi = abi; 10549 } 10550 } else { 10551 pkg.applicationInfo.primaryCpuAbi = abi; 10552 } 10553 } 10554 10555 } else { 10556 String[] abiList = (cpuAbiOverride != null) ? 10557 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 10558 10559 // Enable gross and lame hacks for apps that are built with old 10560 // SDK tools. We must scan their APKs for renderscript bitcode and 10561 // not launch them if it's present. Don't bother checking on devices 10562 // that don't have 64 bit support. 10563 boolean needsRenderScriptOverride = false; 10564 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 10565 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 10566 abiList = Build.SUPPORTED_32_BIT_ABIS; 10567 needsRenderScriptOverride = true; 10568 } 10569 10570 final int copyRet; 10571 if (extractLibs) { 10572 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 10573 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 10574 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 10575 } else { 10576 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 10577 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 10578 } 10579 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10580 10581 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 10582 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 10583 "Error unpackaging native libs for app, errorCode=" + copyRet); 10584 } 10585 10586 if (copyRet >= 0) { 10587 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 10588 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 10589 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 10590 } else if (needsRenderScriptOverride) { 10591 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 10592 } 10593 } 10594 } catch (IOException ioe) { 10595 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 10596 } finally { 10597 IoUtils.closeQuietly(handle); 10598 } 10599 10600 // Now that we've calculated the ABIs and determined if it's an internal app, 10601 // we will go ahead and populate the nativeLibraryPath. 10602 setNativeLibraryPaths(pkg, appLib32InstallDir); 10603 } 10604 10605 /** 10606 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 10607 * i.e, so that all packages can be run inside a single process if required. 10608 * 10609 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 10610 * this function will either try and make the ABI for all packages in {@code packagesForUser} 10611 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 10612 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 10613 * updating a package that belongs to a shared user. 10614 * 10615 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 10616 * adds unnecessary complexity. 10617 */ 10618 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 10619 PackageParser.Package scannedPackage) { 10620 String requiredInstructionSet = null; 10621 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 10622 requiredInstructionSet = VMRuntime.getInstructionSet( 10623 scannedPackage.applicationInfo.primaryCpuAbi); 10624 } 10625 10626 PackageSetting requirer = null; 10627 for (PackageSetting ps : packagesForUser) { 10628 // If packagesForUser contains scannedPackage, we skip it. This will happen 10629 // when scannedPackage is an update of an existing package. Without this check, 10630 // we will never be able to change the ABI of any package belonging to a shared 10631 // user, even if it's compatible with other packages. 10632 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10633 if (ps.primaryCpuAbiString == null) { 10634 continue; 10635 } 10636 10637 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 10638 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 10639 // We have a mismatch between instruction sets (say arm vs arm64) warn about 10640 // this but there's not much we can do. 10641 String errorMessage = "Instruction set mismatch, " 10642 + ((requirer == null) ? "[caller]" : requirer) 10643 + " requires " + requiredInstructionSet + " whereas " + ps 10644 + " requires " + instructionSet; 10645 Slog.w(TAG, errorMessage); 10646 } 10647 10648 if (requiredInstructionSet == null) { 10649 requiredInstructionSet = instructionSet; 10650 requirer = ps; 10651 } 10652 } 10653 } 10654 10655 if (requiredInstructionSet != null) { 10656 String adjustedAbi; 10657 if (requirer != null) { 10658 // requirer != null implies that either scannedPackage was null or that scannedPackage 10659 // did not require an ABI, in which case we have to adjust scannedPackage to match 10660 // the ABI of the set (which is the same as requirer's ABI) 10661 adjustedAbi = requirer.primaryCpuAbiString; 10662 if (scannedPackage != null) { 10663 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 10664 } 10665 } else { 10666 // requirer == null implies that we're updating all ABIs in the set to 10667 // match scannedPackage. 10668 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 10669 } 10670 10671 for (PackageSetting ps : packagesForUser) { 10672 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 10673 if (ps.primaryCpuAbiString != null) { 10674 continue; 10675 } 10676 10677 ps.primaryCpuAbiString = adjustedAbi; 10678 if (ps.pkg != null && ps.pkg.applicationInfo != null && 10679 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 10680 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 10681 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 10682 + " (requirer=" 10683 + (requirer != null ? requirer.pkg : "null") 10684 + ", scannedPackage=" 10685 + (scannedPackage != null ? scannedPackage : "null") 10686 + ")"); 10687 try { 10688 mInstaller.rmdex(ps.codePathString, 10689 getDexCodeInstructionSet(getPreferredInstructionSet())); 10690 } catch (InstallerException ignored) { 10691 } 10692 } 10693 } 10694 } 10695 } 10696 } 10697 10698 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 10699 synchronized (mPackages) { 10700 mResolverReplaced = true; 10701 // Set up information for custom user intent resolution activity. 10702 mResolveActivity.applicationInfo = pkg.applicationInfo; 10703 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 10704 mResolveActivity.packageName = pkg.applicationInfo.packageName; 10705 mResolveActivity.processName = pkg.applicationInfo.packageName; 10706 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10707 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 10708 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10709 mResolveActivity.theme = 0; 10710 mResolveActivity.exported = true; 10711 mResolveActivity.enabled = true; 10712 mResolveInfo.activityInfo = mResolveActivity; 10713 mResolveInfo.priority = 0; 10714 mResolveInfo.preferredOrder = 0; 10715 mResolveInfo.match = 0; 10716 mResolveComponentName = mCustomResolverComponentName; 10717 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 10718 mResolveComponentName); 10719 } 10720 } 10721 10722 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 10723 if (installerActivity == null) { 10724 if (DEBUG_EPHEMERAL) { 10725 Slog.d(TAG, "Clear ephemeral installer activity"); 10726 } 10727 mInstantAppInstallerActivity = null; 10728 return; 10729 } 10730 10731 if (DEBUG_EPHEMERAL) { 10732 Slog.d(TAG, "Set ephemeral installer activity: " 10733 + installerActivity.getComponentName()); 10734 } 10735 // Set up information for ephemeral installer activity 10736 mInstantAppInstallerActivity = installerActivity; 10737 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 10738 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 10739 mInstantAppInstallerActivity.exported = true; 10740 mInstantAppInstallerActivity.enabled = true; 10741 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 10742 mInstantAppInstallerInfo.priority = 0; 10743 mInstantAppInstallerInfo.preferredOrder = 1; 10744 mInstantAppInstallerInfo.isDefault = true; 10745 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 10746 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 10747 } 10748 10749 private static String calculateBundledApkRoot(final String codePathString) { 10750 final File codePath = new File(codePathString); 10751 final File codeRoot; 10752 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 10753 codeRoot = Environment.getRootDirectory(); 10754 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 10755 codeRoot = Environment.getOemDirectory(); 10756 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 10757 codeRoot = Environment.getVendorDirectory(); 10758 } else { 10759 // Unrecognized code path; take its top real segment as the apk root: 10760 // e.g. /something/app/blah.apk => /something 10761 try { 10762 File f = codePath.getCanonicalFile(); 10763 File parent = f.getParentFile(); // non-null because codePath is a file 10764 File tmp; 10765 while ((tmp = parent.getParentFile()) != null) { 10766 f = parent; 10767 parent = tmp; 10768 } 10769 codeRoot = f; 10770 Slog.w(TAG, "Unrecognized code path " 10771 + codePath + " - using " + codeRoot); 10772 } catch (IOException e) { 10773 // Can't canonicalize the code path -- shenanigans? 10774 Slog.w(TAG, "Can't canonicalize code path " + codePath); 10775 return Environment.getRootDirectory().getPath(); 10776 } 10777 } 10778 return codeRoot.getPath(); 10779 } 10780 10781 /** 10782 * Derive and set the location of native libraries for the given package, 10783 * which varies depending on where and how the package was installed. 10784 */ 10785 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 10786 final ApplicationInfo info = pkg.applicationInfo; 10787 final String codePath = pkg.codePath; 10788 final File codeFile = new File(codePath); 10789 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 10790 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 10791 10792 info.nativeLibraryRootDir = null; 10793 info.nativeLibraryRootRequiresIsa = false; 10794 info.nativeLibraryDir = null; 10795 info.secondaryNativeLibraryDir = null; 10796 10797 if (isApkFile(codeFile)) { 10798 // Monolithic install 10799 if (bundledApp) { 10800 // If "/system/lib64/apkname" exists, assume that is the per-package 10801 // native library directory to use; otherwise use "/system/lib/apkname". 10802 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 10803 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 10804 getPrimaryInstructionSet(info)); 10805 10806 // This is a bundled system app so choose the path based on the ABI. 10807 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 10808 // is just the default path. 10809 final String apkName = deriveCodePathName(codePath); 10810 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 10811 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 10812 apkName).getAbsolutePath(); 10813 10814 if (info.secondaryCpuAbi != null) { 10815 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 10816 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 10817 secondaryLibDir, apkName).getAbsolutePath(); 10818 } 10819 } else if (asecApp) { 10820 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 10821 .getAbsolutePath(); 10822 } else { 10823 final String apkName = deriveCodePathName(codePath); 10824 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 10825 .getAbsolutePath(); 10826 } 10827 10828 info.nativeLibraryRootRequiresIsa = false; 10829 info.nativeLibraryDir = info.nativeLibraryRootDir; 10830 } else { 10831 // Cluster install 10832 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 10833 info.nativeLibraryRootRequiresIsa = true; 10834 10835 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 10836 getPrimaryInstructionSet(info)).getAbsolutePath(); 10837 10838 if (info.secondaryCpuAbi != null) { 10839 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 10840 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 10841 } 10842 } 10843 } 10844 10845 /** 10846 * Calculate the abis and roots for a bundled app. These can uniquely 10847 * be determined from the contents of the system partition, i.e whether 10848 * it contains 64 or 32 bit shared libraries etc. We do not validate any 10849 * of this information, and instead assume that the system was built 10850 * sensibly. 10851 */ 10852 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 10853 PackageSetting pkgSetting) { 10854 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 10855 10856 // If "/system/lib64/apkname" exists, assume that is the per-package 10857 // native library directory to use; otherwise use "/system/lib/apkname". 10858 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 10859 setBundledAppAbi(pkg, apkRoot, apkName); 10860 // pkgSetting might be null during rescan following uninstall of updates 10861 // to a bundled app, so accommodate that possibility. The settings in 10862 // that case will be established later from the parsed package. 10863 // 10864 // If the settings aren't null, sync them up with what we've just derived. 10865 // note that apkRoot isn't stored in the package settings. 10866 if (pkgSetting != null) { 10867 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10868 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10869 } 10870 } 10871 10872 /** 10873 * Deduces the ABI of a bundled app and sets the relevant fields on the 10874 * parsed pkg object. 10875 * 10876 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 10877 * under which system libraries are installed. 10878 * @param apkName the name of the installed package. 10879 */ 10880 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 10881 final File codeFile = new File(pkg.codePath); 10882 10883 final boolean has64BitLibs; 10884 final boolean has32BitLibs; 10885 if (isApkFile(codeFile)) { 10886 // Monolithic install 10887 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 10888 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 10889 } else { 10890 // Cluster install 10891 final File rootDir = new File(codeFile, LIB_DIR_NAME); 10892 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 10893 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 10894 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 10895 has64BitLibs = (new File(rootDir, isa)).exists(); 10896 } else { 10897 has64BitLibs = false; 10898 } 10899 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 10900 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 10901 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 10902 has32BitLibs = (new File(rootDir, isa)).exists(); 10903 } else { 10904 has32BitLibs = false; 10905 } 10906 } 10907 10908 if (has64BitLibs && !has32BitLibs) { 10909 // The package has 64 bit libs, but not 32 bit libs. Its primary 10910 // ABI should be 64 bit. We can safely assume here that the bundled 10911 // native libraries correspond to the most preferred ABI in the list. 10912 10913 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10914 pkg.applicationInfo.secondaryCpuAbi = null; 10915 } else if (has32BitLibs && !has64BitLibs) { 10916 // The package has 32 bit libs but not 64 bit libs. Its primary 10917 // ABI should be 32 bit. 10918 10919 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10920 pkg.applicationInfo.secondaryCpuAbi = null; 10921 } else if (has32BitLibs && has64BitLibs) { 10922 // The application has both 64 and 32 bit bundled libraries. We check 10923 // here that the app declares multiArch support, and warn if it doesn't. 10924 // 10925 // We will be lenient here and record both ABIs. The primary will be the 10926 // ABI that's higher on the list, i.e, a device that's configured to prefer 10927 // 64 bit apps will see a 64 bit primary ABI, 10928 10929 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 10930 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 10931 } 10932 10933 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 10934 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10935 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10936 } else { 10937 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 10938 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 10939 } 10940 } else { 10941 pkg.applicationInfo.primaryCpuAbi = null; 10942 pkg.applicationInfo.secondaryCpuAbi = null; 10943 } 10944 } 10945 10946 private void killApplication(String pkgName, int appId, String reason) { 10947 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 10948 } 10949 10950 private void killApplication(String pkgName, int appId, int userId, String reason) { 10951 // Request the ActivityManager to kill the process(only for existing packages) 10952 // so that we do not end up in a confused state while the user is still using the older 10953 // version of the application while the new one gets installed. 10954 final long token = Binder.clearCallingIdentity(); 10955 try { 10956 IActivityManager am = ActivityManager.getService(); 10957 if (am != null) { 10958 try { 10959 am.killApplication(pkgName, appId, userId, reason); 10960 } catch (RemoteException e) { 10961 } 10962 } 10963 } finally { 10964 Binder.restoreCallingIdentity(token); 10965 } 10966 } 10967 10968 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 10969 // Remove the parent package setting 10970 PackageSetting ps = (PackageSetting) pkg.mExtras; 10971 if (ps != null) { 10972 removePackageLI(ps, chatty); 10973 } 10974 // Remove the child package setting 10975 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10976 for (int i = 0; i < childCount; i++) { 10977 PackageParser.Package childPkg = pkg.childPackages.get(i); 10978 ps = (PackageSetting) childPkg.mExtras; 10979 if (ps != null) { 10980 removePackageLI(ps, chatty); 10981 } 10982 } 10983 } 10984 10985 void removePackageLI(PackageSetting ps, boolean chatty) { 10986 if (DEBUG_INSTALL) { 10987 if (chatty) 10988 Log.d(TAG, "Removing package " + ps.name); 10989 } 10990 10991 // writer 10992 synchronized (mPackages) { 10993 mPackages.remove(ps.name); 10994 final PackageParser.Package pkg = ps.pkg; 10995 if (pkg != null) { 10996 cleanPackageDataStructuresLILPw(pkg, chatty); 10997 } 10998 } 10999 } 11000 11001 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11002 if (DEBUG_INSTALL) { 11003 if (chatty) 11004 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11005 } 11006 11007 // writer 11008 synchronized (mPackages) { 11009 // Remove the parent package 11010 mPackages.remove(pkg.applicationInfo.packageName); 11011 cleanPackageDataStructuresLILPw(pkg, chatty); 11012 11013 // Remove the child packages 11014 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11015 for (int i = 0; i < childCount; i++) { 11016 PackageParser.Package childPkg = pkg.childPackages.get(i); 11017 mPackages.remove(childPkg.applicationInfo.packageName); 11018 cleanPackageDataStructuresLILPw(childPkg, chatty); 11019 } 11020 } 11021 } 11022 11023 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11024 int N = pkg.providers.size(); 11025 StringBuilder r = null; 11026 int i; 11027 for (i=0; i<N; i++) { 11028 PackageParser.Provider p = pkg.providers.get(i); 11029 mProviders.removeProvider(p); 11030 if (p.info.authority == null) { 11031 11032 /* There was another ContentProvider with this authority when 11033 * this app was installed so this authority is null, 11034 * Ignore it as we don't have to unregister the provider. 11035 */ 11036 continue; 11037 } 11038 String names[] = p.info.authority.split(";"); 11039 for (int j = 0; j < names.length; j++) { 11040 if (mProvidersByAuthority.get(names[j]) == p) { 11041 mProvidersByAuthority.remove(names[j]); 11042 if (DEBUG_REMOVE) { 11043 if (chatty) 11044 Log.d(TAG, "Unregistered content provider: " + names[j] 11045 + ", className = " + p.info.name + ", isSyncable = " 11046 + p.info.isSyncable); 11047 } 11048 } 11049 } 11050 if (DEBUG_REMOVE && chatty) { 11051 if (r == null) { 11052 r = new StringBuilder(256); 11053 } else { 11054 r.append(' '); 11055 } 11056 r.append(p.info.name); 11057 } 11058 } 11059 if (r != null) { 11060 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11061 } 11062 11063 N = pkg.services.size(); 11064 r = null; 11065 for (i=0; i<N; i++) { 11066 PackageParser.Service s = pkg.services.get(i); 11067 mServices.removeService(s); 11068 if (chatty) { 11069 if (r == null) { 11070 r = new StringBuilder(256); 11071 } else { 11072 r.append(' '); 11073 } 11074 r.append(s.info.name); 11075 } 11076 } 11077 if (r != null) { 11078 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11079 } 11080 11081 N = pkg.receivers.size(); 11082 r = null; 11083 for (i=0; i<N; i++) { 11084 PackageParser.Activity a = pkg.receivers.get(i); 11085 mReceivers.removeActivity(a, "receiver"); 11086 if (DEBUG_REMOVE && chatty) { 11087 if (r == null) { 11088 r = new StringBuilder(256); 11089 } else { 11090 r.append(' '); 11091 } 11092 r.append(a.info.name); 11093 } 11094 } 11095 if (r != null) { 11096 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11097 } 11098 11099 N = pkg.activities.size(); 11100 r = null; 11101 for (i=0; i<N; i++) { 11102 PackageParser.Activity a = pkg.activities.get(i); 11103 mActivities.removeActivity(a, "activity"); 11104 if (DEBUG_REMOVE && chatty) { 11105 if (r == null) { 11106 r = new StringBuilder(256); 11107 } else { 11108 r.append(' '); 11109 } 11110 r.append(a.info.name); 11111 } 11112 } 11113 if (r != null) { 11114 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11115 } 11116 11117 N = pkg.permissions.size(); 11118 r = null; 11119 for (i=0; i<N; i++) { 11120 PackageParser.Permission p = pkg.permissions.get(i); 11121 BasePermission bp = mSettings.mPermissions.get(p.info.name); 11122 if (bp == null) { 11123 bp = mSettings.mPermissionTrees.get(p.info.name); 11124 } 11125 if (bp != null && bp.perm == p) { 11126 bp.perm = null; 11127 if (DEBUG_REMOVE && chatty) { 11128 if (r == null) { 11129 r = new StringBuilder(256); 11130 } else { 11131 r.append(' '); 11132 } 11133 r.append(p.info.name); 11134 } 11135 } 11136 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11137 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 11138 if (appOpPkgs != null) { 11139 appOpPkgs.remove(pkg.packageName); 11140 } 11141 } 11142 } 11143 if (r != null) { 11144 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11145 } 11146 11147 N = pkg.requestedPermissions.size(); 11148 r = null; 11149 for (i=0; i<N; i++) { 11150 String perm = pkg.requestedPermissions.get(i); 11151 BasePermission bp = mSettings.mPermissions.get(perm); 11152 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11153 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 11154 if (appOpPkgs != null) { 11155 appOpPkgs.remove(pkg.packageName); 11156 if (appOpPkgs.isEmpty()) { 11157 mAppOpPermissionPackages.remove(perm); 11158 } 11159 } 11160 } 11161 } 11162 if (r != null) { 11163 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 11164 } 11165 11166 N = pkg.instrumentation.size(); 11167 r = null; 11168 for (i=0; i<N; i++) { 11169 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11170 mInstrumentation.remove(a.getComponentName()); 11171 if (DEBUG_REMOVE && chatty) { 11172 if (r == null) { 11173 r = new StringBuilder(256); 11174 } else { 11175 r.append(' '); 11176 } 11177 r.append(a.info.name); 11178 } 11179 } 11180 if (r != null) { 11181 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11182 } 11183 11184 r = null; 11185 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11186 // Only system apps can hold shared libraries. 11187 if (pkg.libraryNames != null) { 11188 for (i = 0; i < pkg.libraryNames.size(); i++) { 11189 String name = pkg.libraryNames.get(i); 11190 if (removeSharedLibraryLPw(name, 0)) { 11191 if (DEBUG_REMOVE && chatty) { 11192 if (r == null) { 11193 r = new StringBuilder(256); 11194 } else { 11195 r.append(' '); 11196 } 11197 r.append(name); 11198 } 11199 } 11200 } 11201 } 11202 } 11203 11204 r = null; 11205 11206 // Any package can hold static shared libraries. 11207 if (pkg.staticSharedLibName != null) { 11208 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11209 if (DEBUG_REMOVE && chatty) { 11210 if (r == null) { 11211 r = new StringBuilder(256); 11212 } else { 11213 r.append(' '); 11214 } 11215 r.append(pkg.staticSharedLibName); 11216 } 11217 } 11218 } 11219 11220 if (r != null) { 11221 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11222 } 11223 } 11224 11225 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 11226 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 11227 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 11228 return true; 11229 } 11230 } 11231 return false; 11232 } 11233 11234 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 11235 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 11236 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 11237 11238 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 11239 // Update the parent permissions 11240 updatePermissionsLPw(pkg.packageName, pkg, flags); 11241 // Update the child permissions 11242 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11243 for (int i = 0; i < childCount; i++) { 11244 PackageParser.Package childPkg = pkg.childPackages.get(i); 11245 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 11246 } 11247 } 11248 11249 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 11250 int flags) { 11251 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 11252 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 11253 } 11254 11255 private void updatePermissionsLPw(String changingPkg, 11256 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 11257 // Make sure there are no dangling permission trees. 11258 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 11259 while (it.hasNext()) { 11260 final BasePermission bp = it.next(); 11261 if (bp.packageSetting == null) { 11262 // We may not yet have parsed the package, so just see if 11263 // we still know about its settings. 11264 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11265 } 11266 if (bp.packageSetting == null) { 11267 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 11268 + " from package " + bp.sourcePackage); 11269 it.remove(); 11270 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11271 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11272 Slog.i(TAG, "Removing old permission tree: " + bp.name 11273 + " from package " + bp.sourcePackage); 11274 flags |= UPDATE_PERMISSIONS_ALL; 11275 it.remove(); 11276 } 11277 } 11278 } 11279 11280 // Make sure all dynamic permissions have been assigned to a package, 11281 // and make sure there are no dangling permissions. 11282 it = mSettings.mPermissions.values().iterator(); 11283 while (it.hasNext()) { 11284 final BasePermission bp = it.next(); 11285 if (bp.type == BasePermission.TYPE_DYNAMIC) { 11286 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 11287 + bp.name + " pkg=" + bp.sourcePackage 11288 + " info=" + bp.pendingInfo); 11289 if (bp.packageSetting == null && bp.pendingInfo != null) { 11290 final BasePermission tree = findPermissionTreeLP(bp.name); 11291 if (tree != null && tree.perm != null) { 11292 bp.packageSetting = tree.packageSetting; 11293 bp.perm = new PackageParser.Permission(tree.perm.owner, 11294 new PermissionInfo(bp.pendingInfo)); 11295 bp.perm.info.packageName = tree.perm.info.packageName; 11296 bp.perm.info.name = bp.name; 11297 bp.uid = tree.uid; 11298 } 11299 } 11300 } 11301 if (bp.packageSetting == null) { 11302 // We may not yet have parsed the package, so just see if 11303 // we still know about its settings. 11304 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 11305 } 11306 if (bp.packageSetting == null) { 11307 Slog.w(TAG, "Removing dangling permission: " + bp.name 11308 + " from package " + bp.sourcePackage); 11309 it.remove(); 11310 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 11311 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 11312 Slog.i(TAG, "Removing old permission: " + bp.name 11313 + " from package " + bp.sourcePackage); 11314 flags |= UPDATE_PERMISSIONS_ALL; 11315 it.remove(); 11316 } 11317 } 11318 } 11319 11320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 11321 // Now update the permissions for all packages, in particular 11322 // replace the granted permissions of the system packages. 11323 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 11324 for (PackageParser.Package pkg : mPackages.values()) { 11325 if (pkg != pkgInfo) { 11326 // Only replace for packages on requested volume 11327 final String volumeUuid = getVolumeUuidForPackage(pkg); 11328 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 11329 && Objects.equals(replaceVolumeUuid, volumeUuid); 11330 grantPermissionsLPw(pkg, replace, changingPkg); 11331 } 11332 } 11333 } 11334 11335 if (pkgInfo != null) { 11336 // Only replace for packages on requested volume 11337 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 11338 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 11339 && Objects.equals(replaceVolumeUuid, volumeUuid); 11340 grantPermissionsLPw(pkgInfo, replace, changingPkg); 11341 } 11342 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11343 } 11344 11345 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 11346 String packageOfInterest) { 11347 // IMPORTANT: There are two types of permissions: install and runtime. 11348 // Install time permissions are granted when the app is installed to 11349 // all device users and users added in the future. Runtime permissions 11350 // are granted at runtime explicitly to specific users. Normal and signature 11351 // protected permissions are install time permissions. Dangerous permissions 11352 // are install permissions if the app's target SDK is Lollipop MR1 or older, 11353 // otherwise they are runtime permissions. This function does not manage 11354 // runtime permissions except for the case an app targeting Lollipop MR1 11355 // being upgraded to target a newer SDK, in which case dangerous permissions 11356 // are transformed from install time to runtime ones. 11357 11358 final PackageSetting ps = (PackageSetting) pkg.mExtras; 11359 if (ps == null) { 11360 return; 11361 } 11362 11363 PermissionsState permissionsState = ps.getPermissionsState(); 11364 PermissionsState origPermissions = permissionsState; 11365 11366 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 11367 11368 boolean runtimePermissionsRevoked = false; 11369 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 11370 11371 boolean changedInstallPermission = false; 11372 11373 if (replace) { 11374 ps.installPermissionsFixed = false; 11375 if (!ps.isSharedUser()) { 11376 origPermissions = new PermissionsState(permissionsState); 11377 permissionsState.reset(); 11378 } else { 11379 // We need to know only about runtime permission changes since the 11380 // calling code always writes the install permissions state but 11381 // the runtime ones are written only if changed. The only cases of 11382 // changed runtime permissions here are promotion of an install to 11383 // runtime and revocation of a runtime from a shared user. 11384 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 11385 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 11386 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 11387 runtimePermissionsRevoked = true; 11388 } 11389 } 11390 } 11391 11392 permissionsState.setGlobalGids(mGlobalGids); 11393 11394 final int N = pkg.requestedPermissions.size(); 11395 for (int i=0; i<N; i++) { 11396 final String name = pkg.requestedPermissions.get(i); 11397 final BasePermission bp = mSettings.mPermissions.get(name); 11398 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 11399 >= Build.VERSION_CODES.M; 11400 11401 if (DEBUG_INSTALL) { 11402 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 11403 } 11404 11405 if (bp == null || bp.packageSetting == null) { 11406 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11407 Slog.w(TAG, "Unknown permission " + name 11408 + " in package " + pkg.packageName); 11409 } 11410 continue; 11411 } 11412 11413 11414 // Limit ephemeral apps to ephemeral allowed permissions. 11415 if (pkg.applicationInfo.isInstantApp() && !bp.isInstant()) { 11416 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 11417 + pkg.packageName); 11418 continue; 11419 } 11420 11421 if (bp.isRuntimeOnly() && !appSupportsRuntimePermissions) { 11422 Log.i(TAG, "Denying runtime-only permission " + bp.name + " for package " 11423 + pkg.packageName); 11424 continue; 11425 } 11426 11427 final String perm = bp.name; 11428 boolean allowedSig = false; 11429 int grant = GRANT_DENIED; 11430 11431 // Keep track of app op permissions. 11432 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 11433 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 11434 if (pkgs == null) { 11435 pkgs = new ArraySet<>(); 11436 mAppOpPermissionPackages.put(bp.name, pkgs); 11437 } 11438 pkgs.add(pkg.packageName); 11439 } 11440 11441 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 11442 switch (level) { 11443 case PermissionInfo.PROTECTION_NORMAL: { 11444 // For all apps normal permissions are install time ones. 11445 grant = GRANT_INSTALL; 11446 } break; 11447 11448 case PermissionInfo.PROTECTION_DANGEROUS: { 11449 // If a permission review is required for legacy apps we represent 11450 // their permissions as always granted runtime ones since we need 11451 // to keep the review required permission flag per user while an 11452 // install permission's state is shared across all users. 11453 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 11454 // For legacy apps dangerous permissions are install time ones. 11455 grant = GRANT_INSTALL; 11456 } else if (origPermissions.hasInstallPermission(bp.name)) { 11457 // For legacy apps that became modern, install becomes runtime. 11458 grant = GRANT_UPGRADE; 11459 } else if (mPromoteSystemApps 11460 && isSystemApp(ps) 11461 && mExistingSystemPackages.contains(ps.name)) { 11462 // For legacy system apps, install becomes runtime. 11463 // We cannot check hasInstallPermission() for system apps since those 11464 // permissions were granted implicitly and not persisted pre-M. 11465 grant = GRANT_UPGRADE; 11466 } else { 11467 // For modern apps keep runtime permissions unchanged. 11468 grant = GRANT_RUNTIME; 11469 } 11470 } break; 11471 11472 case PermissionInfo.PROTECTION_SIGNATURE: { 11473 // For all apps signature permissions are install time ones. 11474 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 11475 if (allowedSig) { 11476 grant = GRANT_INSTALL; 11477 } 11478 } break; 11479 } 11480 11481 if (DEBUG_INSTALL) { 11482 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 11483 } 11484 11485 if (grant != GRANT_DENIED) { 11486 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 11487 // If this is an existing, non-system package, then 11488 // we can't add any new permissions to it. 11489 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 11490 // Except... if this is a permission that was added 11491 // to the platform (note: need to only do this when 11492 // updating the platform). 11493 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 11494 grant = GRANT_DENIED; 11495 } 11496 } 11497 } 11498 11499 switch (grant) { 11500 case GRANT_INSTALL: { 11501 // Revoke this as runtime permission to handle the case of 11502 // a runtime permission being downgraded to an install one. 11503 // Also in permission review mode we keep dangerous permissions 11504 // for legacy apps 11505 for (int userId : UserManagerService.getInstance().getUserIds()) { 11506 if (origPermissions.getRuntimePermissionState( 11507 bp.name, userId) != null) { 11508 // Revoke the runtime permission and clear the flags. 11509 origPermissions.revokeRuntimePermission(bp, userId); 11510 origPermissions.updatePermissionFlags(bp, userId, 11511 PackageManager.MASK_PERMISSION_FLAGS, 0); 11512 // If we revoked a permission permission, we have to write. 11513 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11514 changedRuntimePermissionUserIds, userId); 11515 } 11516 } 11517 // Grant an install permission. 11518 if (permissionsState.grantInstallPermission(bp) != 11519 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11520 changedInstallPermission = true; 11521 } 11522 } break; 11523 11524 case GRANT_RUNTIME: { 11525 // Grant previously granted runtime permissions. 11526 for (int userId : UserManagerService.getInstance().getUserIds()) { 11527 PermissionState permissionState = origPermissions 11528 .getRuntimePermissionState(bp.name, userId); 11529 int flags = permissionState != null 11530 ? permissionState.getFlags() : 0; 11531 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 11532 // Don't propagate the permission in a permission review mode if 11533 // the former was revoked, i.e. marked to not propagate on upgrade. 11534 // Note that in a permission review mode install permissions are 11535 // represented as constantly granted runtime ones since we need to 11536 // keep a per user state associated with the permission. Also the 11537 // revoke on upgrade flag is no longer applicable and is reset. 11538 final boolean revokeOnUpgrade = (flags & PackageManager 11539 .FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 11540 if (revokeOnUpgrade) { 11541 flags &= ~PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 11542 // Since we changed the flags, we have to write. 11543 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11544 changedRuntimePermissionUserIds, userId); 11545 } 11546 if (!mPermissionReviewRequired || !revokeOnUpgrade) { 11547 if (permissionsState.grantRuntimePermission(bp, userId) == 11548 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11549 // If we cannot put the permission as it was, 11550 // we have to write. 11551 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11552 changedRuntimePermissionUserIds, userId); 11553 } 11554 } 11555 11556 // If the app supports runtime permissions no need for a review. 11557 if (mPermissionReviewRequired 11558 && appSupportsRuntimePermissions 11559 && (flags & PackageManager 11560 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 11561 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 11562 // Since we changed the flags, we have to write. 11563 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11564 changedRuntimePermissionUserIds, userId); 11565 } 11566 } else if (mPermissionReviewRequired 11567 && !appSupportsRuntimePermissions) { 11568 // For legacy apps that need a permission review, every new 11569 // runtime permission is granted but it is pending a review. 11570 // We also need to review only platform defined runtime 11571 // permissions as these are the only ones the platform knows 11572 // how to disable the API to simulate revocation as legacy 11573 // apps don't expect to run with revoked permissions. 11574 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 11575 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 11576 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 11577 // We changed the flags, hence have to write. 11578 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11579 changedRuntimePermissionUserIds, userId); 11580 } 11581 } 11582 if (permissionsState.grantRuntimePermission(bp, userId) 11583 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11584 // We changed the permission, hence have to write. 11585 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11586 changedRuntimePermissionUserIds, userId); 11587 } 11588 } 11589 // Propagate the permission flags. 11590 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 11591 } 11592 } break; 11593 11594 case GRANT_UPGRADE: { 11595 // Grant runtime permissions for a previously held install permission. 11596 PermissionState permissionState = origPermissions 11597 .getInstallPermissionState(bp.name); 11598 final int flags = permissionState != null ? permissionState.getFlags() : 0; 11599 11600 if (origPermissions.revokeInstallPermission(bp) 11601 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 11602 // We will be transferring the permission flags, so clear them. 11603 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 11604 PackageManager.MASK_PERMISSION_FLAGS, 0); 11605 changedInstallPermission = true; 11606 } 11607 11608 // If the permission is not to be promoted to runtime we ignore it and 11609 // also its other flags as they are not applicable to install permissions. 11610 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 11611 for (int userId : currentUserIds) { 11612 if (permissionsState.grantRuntimePermission(bp, userId) != 11613 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11614 // Transfer the permission flags. 11615 permissionsState.updatePermissionFlags(bp, userId, 11616 flags, flags); 11617 // If we granted the permission, we have to write. 11618 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 11619 changedRuntimePermissionUserIds, userId); 11620 } 11621 } 11622 } 11623 } break; 11624 11625 default: { 11626 if (packageOfInterest == null 11627 || packageOfInterest.equals(pkg.packageName)) { 11628 Slog.w(TAG, "Not granting permission " + perm 11629 + " to package " + pkg.packageName 11630 + " because it was previously installed without"); 11631 } 11632 } break; 11633 } 11634 } else { 11635 if (permissionsState.revokeInstallPermission(bp) != 11636 PermissionsState.PERMISSION_OPERATION_FAILURE) { 11637 // Also drop the permission flags. 11638 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 11639 PackageManager.MASK_PERMISSION_FLAGS, 0); 11640 changedInstallPermission = true; 11641 Slog.i(TAG, "Un-granting permission " + perm 11642 + " from package " + pkg.packageName 11643 + " (protectionLevel=" + bp.protectionLevel 11644 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11645 + ")"); 11646 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 11647 // Don't print warning for app op permissions, since it is fine for them 11648 // not to be granted, there is a UI for the user to decide. 11649 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 11650 Slog.w(TAG, "Not granting permission " + perm 11651 + " to package " + pkg.packageName 11652 + " (protectionLevel=" + bp.protectionLevel 11653 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 11654 + ")"); 11655 } 11656 } 11657 } 11658 } 11659 11660 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 11661 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 11662 // This is the first that we have heard about this package, so the 11663 // permissions we have now selected are fixed until explicitly 11664 // changed. 11665 ps.installPermissionsFixed = true; 11666 } 11667 11668 // Persist the runtime permissions state for users with changes. If permissions 11669 // were revoked because no app in the shared user declares them we have to 11670 // write synchronously to avoid losing runtime permissions state. 11671 for (int userId : changedRuntimePermissionUserIds) { 11672 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 11673 } 11674 } 11675 11676 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 11677 boolean allowed = false; 11678 final int NP = PackageParser.NEW_PERMISSIONS.length; 11679 for (int ip=0; ip<NP; ip++) { 11680 final PackageParser.NewPermissionInfo npi 11681 = PackageParser.NEW_PERMISSIONS[ip]; 11682 if (npi.name.equals(perm) 11683 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 11684 allowed = true; 11685 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 11686 + pkg.packageName); 11687 break; 11688 } 11689 } 11690 return allowed; 11691 } 11692 11693 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 11694 BasePermission bp, PermissionsState origPermissions) { 11695 boolean privilegedPermission = (bp.protectionLevel 11696 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 11697 boolean privappPermissionsDisable = 11698 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 11699 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 11700 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 11701 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 11702 && !platformPackage && platformPermission) { 11703 ArraySet<String> wlPermissions = SystemConfig.getInstance() 11704 .getPrivAppPermissions(pkg.packageName); 11705 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 11706 if (!whitelisted) { 11707 Slog.w(TAG, "Privileged permission " + perm + " for package " 11708 + pkg.packageName + " - not in privapp-permissions whitelist"); 11709 // Only report violations for apps on system image 11710 if (!mSystemReady && !pkg.isUpdatedSystemApp()) { 11711 if (mPrivappPermissionsViolations == null) { 11712 mPrivappPermissionsViolations = new ArraySet<>(); 11713 } 11714 mPrivappPermissionsViolations.add(pkg.packageName + ": " + perm); 11715 } 11716 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 11717 return false; 11718 } 11719 } 11720 } 11721 boolean allowed = (compareSignatures( 11722 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 11723 == PackageManager.SIGNATURE_MATCH) 11724 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 11725 == PackageManager.SIGNATURE_MATCH); 11726 if (!allowed && privilegedPermission) { 11727 if (isSystemApp(pkg)) { 11728 // For updated system applications, a system permission 11729 // is granted only if it had been defined by the original application. 11730 if (pkg.isUpdatedSystemApp()) { 11731 final PackageSetting sysPs = mSettings 11732 .getDisabledSystemPkgLPr(pkg.packageName); 11733 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 11734 // If the original was granted this permission, we take 11735 // that grant decision as read and propagate it to the 11736 // update. 11737 if (sysPs.isPrivileged()) { 11738 allowed = true; 11739 } 11740 } else { 11741 // The system apk may have been updated with an older 11742 // version of the one on the data partition, but which 11743 // granted a new system permission that it didn't have 11744 // before. In this case we do want to allow the app to 11745 // now get the new permission if the ancestral apk is 11746 // privileged to get it. 11747 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 11748 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 11749 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 11750 allowed = true; 11751 break; 11752 } 11753 } 11754 } 11755 // Also if a privileged parent package on the system image or any of 11756 // its children requested a privileged permission, the updated child 11757 // packages can also get the permission. 11758 if (pkg.parentPackage != null) { 11759 final PackageSetting disabledSysParentPs = mSettings 11760 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 11761 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 11762 && disabledSysParentPs.isPrivileged()) { 11763 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 11764 allowed = true; 11765 } else if (disabledSysParentPs.pkg.childPackages != null) { 11766 final int count = disabledSysParentPs.pkg.childPackages.size(); 11767 for (int i = 0; i < count; i++) { 11768 PackageParser.Package disabledSysChildPkg = 11769 disabledSysParentPs.pkg.childPackages.get(i); 11770 if (isPackageRequestingPermission(disabledSysChildPkg, 11771 perm)) { 11772 allowed = true; 11773 break; 11774 } 11775 } 11776 } 11777 } 11778 } 11779 } 11780 } else { 11781 allowed = isPrivilegedApp(pkg); 11782 } 11783 } 11784 } 11785 if (!allowed) { 11786 if (!allowed && (bp.protectionLevel 11787 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 11788 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 11789 // If this was a previously normal/dangerous permission that got moved 11790 // to a system permission as part of the runtime permission redesign, then 11791 // we still want to blindly grant it to old apps. 11792 allowed = true; 11793 } 11794 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 11795 && pkg.packageName.equals(mRequiredInstallerPackage)) { 11796 // If this permission is to be granted to the system installer and 11797 // this app is an installer, then it gets the permission. 11798 allowed = true; 11799 } 11800 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 11801 && pkg.packageName.equals(mRequiredVerifierPackage)) { 11802 // If this permission is to be granted to the system verifier and 11803 // this app is a verifier, then it gets the permission. 11804 allowed = true; 11805 } 11806 if (!allowed && (bp.protectionLevel 11807 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 11808 && isSystemApp(pkg)) { 11809 // Any pre-installed system app is allowed to get this permission. 11810 allowed = true; 11811 } 11812 if (!allowed && (bp.protectionLevel 11813 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 11814 // For development permissions, a development permission 11815 // is granted only if it was already granted. 11816 allowed = origPermissions.hasInstallPermission(perm); 11817 } 11818 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 11819 && pkg.packageName.equals(mSetupWizardPackage)) { 11820 // If this permission is to be granted to the system setup wizard and 11821 // this app is a setup wizard, then it gets the permission. 11822 allowed = true; 11823 } 11824 } 11825 return allowed; 11826 } 11827 11828 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 11829 final int permCount = pkg.requestedPermissions.size(); 11830 for (int j = 0; j < permCount; j++) { 11831 String requestedPermission = pkg.requestedPermissions.get(j); 11832 if (permission.equals(requestedPermission)) { 11833 return true; 11834 } 11835 } 11836 return false; 11837 } 11838 11839 final class ActivityIntentResolver 11840 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11841 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11842 boolean defaultOnly, int userId) { 11843 if (!sUserManager.exists(userId)) return null; 11844 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11845 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11846 } 11847 11848 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11849 int userId) { 11850 if (!sUserManager.exists(userId)) return null; 11851 mFlags = flags; 11852 return super.queryIntent(intent, resolvedType, 11853 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11854 userId); 11855 } 11856 11857 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11858 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11859 if (!sUserManager.exists(userId)) return null; 11860 if (packageActivities == null) { 11861 return null; 11862 } 11863 mFlags = flags; 11864 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11865 final int N = packageActivities.size(); 11866 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11867 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11868 11869 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11870 for (int i = 0; i < N; ++i) { 11871 intentFilters = packageActivities.get(i).intents; 11872 if (intentFilters != null && intentFilters.size() > 0) { 11873 PackageParser.ActivityIntentInfo[] array = 11874 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11875 intentFilters.toArray(array); 11876 listCut.add(array); 11877 } 11878 } 11879 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11880 } 11881 11882 /** 11883 * Finds a privileged activity that matches the specified activity names. 11884 */ 11885 private PackageParser.Activity findMatchingActivity( 11886 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11887 for (PackageParser.Activity sysActivity : activityList) { 11888 if (sysActivity.info.name.equals(activityInfo.name)) { 11889 return sysActivity; 11890 } 11891 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11892 return sysActivity; 11893 } 11894 if (sysActivity.info.targetActivity != null) { 11895 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11896 return sysActivity; 11897 } 11898 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11899 return sysActivity; 11900 } 11901 } 11902 } 11903 return null; 11904 } 11905 11906 public class IterGenerator<E> { 11907 public Iterator<E> generate(ActivityIntentInfo info) { 11908 return null; 11909 } 11910 } 11911 11912 public class ActionIterGenerator extends IterGenerator<String> { 11913 @Override 11914 public Iterator<String> generate(ActivityIntentInfo info) { 11915 return info.actionsIterator(); 11916 } 11917 } 11918 11919 public class CategoriesIterGenerator extends IterGenerator<String> { 11920 @Override 11921 public Iterator<String> generate(ActivityIntentInfo info) { 11922 return info.categoriesIterator(); 11923 } 11924 } 11925 11926 public class SchemesIterGenerator extends IterGenerator<String> { 11927 @Override 11928 public Iterator<String> generate(ActivityIntentInfo info) { 11929 return info.schemesIterator(); 11930 } 11931 } 11932 11933 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11934 @Override 11935 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11936 return info.authoritiesIterator(); 11937 } 11938 } 11939 11940 /** 11941 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 11942 * MODIFIED. Do not pass in a list that should not be changed. 11943 */ 11944 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 11945 IterGenerator<T> generator, Iterator<T> searchIterator) { 11946 // loop through the set of actions; every one must be found in the intent filter 11947 while (searchIterator.hasNext()) { 11948 // we must have at least one filter in the list to consider a match 11949 if (intentList.size() == 0) { 11950 break; 11951 } 11952 11953 final T searchAction = searchIterator.next(); 11954 11955 // loop through the set of intent filters 11956 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 11957 while (intentIter.hasNext()) { 11958 final ActivityIntentInfo intentInfo = intentIter.next(); 11959 boolean selectionFound = false; 11960 11961 // loop through the intent filter's selection criteria; at least one 11962 // of them must match the searched criteria 11963 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 11964 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 11965 final T intentSelection = intentSelectionIter.next(); 11966 if (intentSelection != null && intentSelection.equals(searchAction)) { 11967 selectionFound = true; 11968 break; 11969 } 11970 } 11971 11972 // the selection criteria wasn't found in this filter's set; this filter 11973 // is not a potential match 11974 if (!selectionFound) { 11975 intentIter.remove(); 11976 } 11977 } 11978 } 11979 } 11980 11981 private boolean isProtectedAction(ActivityIntentInfo filter) { 11982 final Iterator<String> actionsIter = filter.actionsIterator(); 11983 while (actionsIter != null && actionsIter.hasNext()) { 11984 final String filterAction = actionsIter.next(); 11985 if (PROTECTED_ACTIONS.contains(filterAction)) { 11986 return true; 11987 } 11988 } 11989 return false; 11990 } 11991 11992 /** 11993 * Adjusts the priority of the given intent filter according to policy. 11994 * <p> 11995 * <ul> 11996 * <li>The priority for non privileged applications is capped to '0'</li> 11997 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 11998 * <li>The priority for unbundled updates to privileged applications is capped to the 11999 * priority defined on the system partition</li> 12000 * </ul> 12001 * <p> 12002 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12003 * allowed to obtain any priority on any action. 12004 */ 12005 private void adjustPriority( 12006 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12007 // nothing to do; priority is fine as-is 12008 if (intent.getPriority() <= 0) { 12009 return; 12010 } 12011 12012 final ActivityInfo activityInfo = intent.activity.info; 12013 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12014 12015 final boolean privilegedApp = 12016 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12017 if (!privilegedApp) { 12018 // non-privileged applications can never define a priority >0 12019 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 12020 + " package: " + applicationInfo.packageName 12021 + " activity: " + intent.activity.className 12022 + " origPrio: " + intent.getPriority()); 12023 intent.setPriority(0); 12024 return; 12025 } 12026 12027 if (systemActivities == null) { 12028 // the system package is not disabled; we're parsing the system partition 12029 if (isProtectedAction(intent)) { 12030 if (mDeferProtectedFilters) { 12031 // We can't deal with these just yet. No component should ever obtain a 12032 // >0 priority for a protected actions, with ONE exception -- the setup 12033 // wizard. The setup wizard, however, cannot be known until we're able to 12034 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12035 // until all intent filters have been processed. Chicken, meet egg. 12036 // Let the filter temporarily have a high priority and rectify the 12037 // priorities after all system packages have been scanned. 12038 mProtectedFilters.add(intent); 12039 if (DEBUG_FILTERS) { 12040 Slog.i(TAG, "Protected action; save for later;" 12041 + " package: " + applicationInfo.packageName 12042 + " activity: " + intent.activity.className 12043 + " origPrio: " + intent.getPriority()); 12044 } 12045 return; 12046 } else { 12047 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12048 Slog.i(TAG, "No setup wizard;" 12049 + " All protected intents capped to priority 0"); 12050 } 12051 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12052 if (DEBUG_FILTERS) { 12053 Slog.i(TAG, "Found setup wizard;" 12054 + " allow priority " + intent.getPriority() + ";" 12055 + " package: " + intent.activity.info.packageName 12056 + " activity: " + intent.activity.className 12057 + " priority: " + intent.getPriority()); 12058 } 12059 // setup wizard gets whatever it wants 12060 return; 12061 } 12062 Slog.w(TAG, "Protected action; cap priority to 0;" 12063 + " package: " + intent.activity.info.packageName 12064 + " activity: " + intent.activity.className 12065 + " origPrio: " + intent.getPriority()); 12066 intent.setPriority(0); 12067 return; 12068 } 12069 } 12070 // privileged apps on the system image get whatever priority they request 12071 return; 12072 } 12073 12074 // privileged app unbundled update ... try to find the same activity 12075 final PackageParser.Activity foundActivity = 12076 findMatchingActivity(systemActivities, activityInfo); 12077 if (foundActivity == null) { 12078 // this is a new activity; it cannot obtain >0 priority 12079 if (DEBUG_FILTERS) { 12080 Slog.i(TAG, "New activity; cap priority to 0;" 12081 + " package: " + applicationInfo.packageName 12082 + " activity: " + intent.activity.className 12083 + " origPrio: " + intent.getPriority()); 12084 } 12085 intent.setPriority(0); 12086 return; 12087 } 12088 12089 // found activity, now check for filter equivalence 12090 12091 // a shallow copy is enough; we modify the list, not its contents 12092 final List<ActivityIntentInfo> intentListCopy = 12093 new ArrayList<>(foundActivity.intents); 12094 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12095 12096 // find matching action subsets 12097 final Iterator<String> actionsIterator = intent.actionsIterator(); 12098 if (actionsIterator != null) { 12099 getIntentListSubset( 12100 intentListCopy, new ActionIterGenerator(), actionsIterator); 12101 if (intentListCopy.size() == 0) { 12102 // no more intents to match; we're not equivalent 12103 if (DEBUG_FILTERS) { 12104 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12105 + " package: " + applicationInfo.packageName 12106 + " activity: " + intent.activity.className 12107 + " origPrio: " + intent.getPriority()); 12108 } 12109 intent.setPriority(0); 12110 return; 12111 } 12112 } 12113 12114 // find matching category subsets 12115 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12116 if (categoriesIterator != null) { 12117 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12118 categoriesIterator); 12119 if (intentListCopy.size() == 0) { 12120 // no more intents to match; we're not equivalent 12121 if (DEBUG_FILTERS) { 12122 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12123 + " package: " + applicationInfo.packageName 12124 + " activity: " + intent.activity.className 12125 + " origPrio: " + intent.getPriority()); 12126 } 12127 intent.setPriority(0); 12128 return; 12129 } 12130 } 12131 12132 // find matching schemes subsets 12133 final Iterator<String> schemesIterator = intent.schemesIterator(); 12134 if (schemesIterator != null) { 12135 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12136 schemesIterator); 12137 if (intentListCopy.size() == 0) { 12138 // no more intents to match; we're not equivalent 12139 if (DEBUG_FILTERS) { 12140 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12141 + " package: " + applicationInfo.packageName 12142 + " activity: " + intent.activity.className 12143 + " origPrio: " + intent.getPriority()); 12144 } 12145 intent.setPriority(0); 12146 return; 12147 } 12148 } 12149 12150 // find matching authorities subsets 12151 final Iterator<IntentFilter.AuthorityEntry> 12152 authoritiesIterator = intent.authoritiesIterator(); 12153 if (authoritiesIterator != null) { 12154 getIntentListSubset(intentListCopy, 12155 new AuthoritiesIterGenerator(), 12156 authoritiesIterator); 12157 if (intentListCopy.size() == 0) { 12158 // no more intents to match; we're not equivalent 12159 if (DEBUG_FILTERS) { 12160 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12161 + " package: " + applicationInfo.packageName 12162 + " activity: " + intent.activity.className 12163 + " origPrio: " + intent.getPriority()); 12164 } 12165 intent.setPriority(0); 12166 return; 12167 } 12168 } 12169 12170 // we found matching filter(s); app gets the max priority of all intents 12171 int cappedPriority = 0; 12172 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12173 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12174 } 12175 if (intent.getPriority() > cappedPriority) { 12176 if (DEBUG_FILTERS) { 12177 Slog.i(TAG, "Found matching filter(s);" 12178 + " cap priority to " + cappedPriority + ";" 12179 + " package: " + applicationInfo.packageName 12180 + " activity: " + intent.activity.className 12181 + " origPrio: " + intent.getPriority()); 12182 } 12183 intent.setPriority(cappedPriority); 12184 return; 12185 } 12186 // all this for nothing; the requested priority was <= what was on the system 12187 } 12188 12189 public final void addActivity(PackageParser.Activity a, String type) { 12190 mActivities.put(a.getComponentName(), a); 12191 if (DEBUG_SHOW_INFO) 12192 Log.v( 12193 TAG, " " + type + " " + 12194 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12195 if (DEBUG_SHOW_INFO) 12196 Log.v(TAG, " Class=" + a.info.name); 12197 final int NI = a.intents.size(); 12198 for (int j=0; j<NI; j++) { 12199 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12200 if ("activity".equals(type)) { 12201 final PackageSetting ps = 12202 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12203 final List<PackageParser.Activity> systemActivities = 12204 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12205 adjustPriority(systemActivities, intent); 12206 } 12207 if (DEBUG_SHOW_INFO) { 12208 Log.v(TAG, " IntentFilter:"); 12209 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12210 } 12211 if (!intent.debugCheck()) { 12212 Log.w(TAG, "==> For Activity " + a.info.name); 12213 } 12214 addFilter(intent); 12215 } 12216 } 12217 12218 public final void removeActivity(PackageParser.Activity a, String type) { 12219 mActivities.remove(a.getComponentName()); 12220 if (DEBUG_SHOW_INFO) { 12221 Log.v(TAG, " " + type + " " 12222 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12223 : a.info.name) + ":"); 12224 Log.v(TAG, " Class=" + a.info.name); 12225 } 12226 final int NI = a.intents.size(); 12227 for (int j=0; j<NI; j++) { 12228 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12229 if (DEBUG_SHOW_INFO) { 12230 Log.v(TAG, " IntentFilter:"); 12231 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12232 } 12233 removeFilter(intent); 12234 } 12235 } 12236 12237 @Override 12238 protected boolean allowFilterResult( 12239 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12240 ActivityInfo filterAi = filter.activity.info; 12241 for (int i=dest.size()-1; i>=0; i--) { 12242 ActivityInfo destAi = dest.get(i).activityInfo; 12243 if (destAi.name == filterAi.name 12244 && destAi.packageName == filterAi.packageName) { 12245 return false; 12246 } 12247 } 12248 return true; 12249 } 12250 12251 @Override 12252 protected ActivityIntentInfo[] newArray(int size) { 12253 return new ActivityIntentInfo[size]; 12254 } 12255 12256 @Override 12257 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12258 if (!sUserManager.exists(userId)) return true; 12259 PackageParser.Package p = filter.activity.owner; 12260 if (p != null) { 12261 PackageSetting ps = (PackageSetting)p.mExtras; 12262 if (ps != null) { 12263 // System apps are never considered stopped for purposes of 12264 // filtering, because there may be no way for the user to 12265 // actually re-launch them. 12266 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12267 && ps.getStopped(userId); 12268 } 12269 } 12270 return false; 12271 } 12272 12273 @Override 12274 protected boolean isPackageForFilter(String packageName, 12275 PackageParser.ActivityIntentInfo info) { 12276 return packageName.equals(info.activity.owner.packageName); 12277 } 12278 12279 @Override 12280 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12281 int match, int userId) { 12282 if (!sUserManager.exists(userId)) return null; 12283 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12284 return null; 12285 } 12286 final PackageParser.Activity activity = info.activity; 12287 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12288 if (ps == null) { 12289 return null; 12290 } 12291 final PackageUserState userState = ps.readUserState(userId); 12292 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 12293 userState, userId); 12294 if (ai == null) { 12295 return null; 12296 } 12297 final boolean matchVisibleToInstantApp = 12298 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12299 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12300 // throw out filters that aren't visible to ephemeral apps 12301 if (matchVisibleToInstantApp 12302 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12303 return null; 12304 } 12305 // throw out ephemeral filters if we're not explicitly requesting them 12306 if (!isInstantApp && userState.instantApp) { 12307 return null; 12308 } 12309 // throw out instant app filters if updates are available; will trigger 12310 // instant app resolution 12311 if (userState.instantApp && ps.isUpdateAvailable()) { 12312 return null; 12313 } 12314 final ResolveInfo res = new ResolveInfo(); 12315 res.activityInfo = ai; 12316 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12317 res.filter = info; 12318 } 12319 if (info != null) { 12320 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12321 } 12322 res.priority = info.getPriority(); 12323 res.preferredOrder = activity.owner.mPreferredOrder; 12324 //System.out.println("Result: " + res.activityInfo.className + 12325 // " = " + res.priority); 12326 res.match = match; 12327 res.isDefault = info.hasDefault; 12328 res.labelRes = info.labelRes; 12329 res.nonLocalizedLabel = info.nonLocalizedLabel; 12330 if (userNeedsBadging(userId)) { 12331 res.noResourceId = true; 12332 } else { 12333 res.icon = info.icon; 12334 } 12335 res.iconResourceId = info.icon; 12336 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12337 res.instantAppAvailable = userState.instantApp; 12338 return res; 12339 } 12340 12341 @Override 12342 protected void sortResults(List<ResolveInfo> results) { 12343 Collections.sort(results, mResolvePrioritySorter); 12344 } 12345 12346 @Override 12347 protected void dumpFilter(PrintWriter out, String prefix, 12348 PackageParser.ActivityIntentInfo filter) { 12349 out.print(prefix); out.print( 12350 Integer.toHexString(System.identityHashCode(filter.activity))); 12351 out.print(' '); 12352 filter.activity.printComponentShortName(out); 12353 out.print(" filter "); 12354 out.println(Integer.toHexString(System.identityHashCode(filter))); 12355 } 12356 12357 @Override 12358 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12359 return filter.activity; 12360 } 12361 12362 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12363 PackageParser.Activity activity = (PackageParser.Activity)label; 12364 out.print(prefix); out.print( 12365 Integer.toHexString(System.identityHashCode(activity))); 12366 out.print(' '); 12367 activity.printComponentShortName(out); 12368 if (count > 1) { 12369 out.print(" ("); out.print(count); out.print(" filters)"); 12370 } 12371 out.println(); 12372 } 12373 12374 // Keys are String (activity class name), values are Activity. 12375 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12376 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12377 private int mFlags; 12378 } 12379 12380 private final class ServiceIntentResolver 12381 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12382 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12383 boolean defaultOnly, int userId) { 12384 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12385 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12386 } 12387 12388 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12389 int userId) { 12390 if (!sUserManager.exists(userId)) return null; 12391 mFlags = flags; 12392 return super.queryIntent(intent, resolvedType, 12393 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12394 userId); 12395 } 12396 12397 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12398 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12399 if (!sUserManager.exists(userId)) return null; 12400 if (packageServices == null) { 12401 return null; 12402 } 12403 mFlags = flags; 12404 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12405 final int N = packageServices.size(); 12406 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12407 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12408 12409 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12410 for (int i = 0; i < N; ++i) { 12411 intentFilters = packageServices.get(i).intents; 12412 if (intentFilters != null && intentFilters.size() > 0) { 12413 PackageParser.ServiceIntentInfo[] array = 12414 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12415 intentFilters.toArray(array); 12416 listCut.add(array); 12417 } 12418 } 12419 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12420 } 12421 12422 public final void addService(PackageParser.Service s) { 12423 mServices.put(s.getComponentName(), s); 12424 if (DEBUG_SHOW_INFO) { 12425 Log.v(TAG, " " 12426 + (s.info.nonLocalizedLabel != null 12427 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12428 Log.v(TAG, " Class=" + s.info.name); 12429 } 12430 final int NI = s.intents.size(); 12431 int j; 12432 for (j=0; j<NI; j++) { 12433 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12434 if (DEBUG_SHOW_INFO) { 12435 Log.v(TAG, " IntentFilter:"); 12436 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12437 } 12438 if (!intent.debugCheck()) { 12439 Log.w(TAG, "==> For Service " + s.info.name); 12440 } 12441 addFilter(intent); 12442 } 12443 } 12444 12445 public final void removeService(PackageParser.Service s) { 12446 mServices.remove(s.getComponentName()); 12447 if (DEBUG_SHOW_INFO) { 12448 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12449 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12450 Log.v(TAG, " Class=" + s.info.name); 12451 } 12452 final int NI = s.intents.size(); 12453 int j; 12454 for (j=0; j<NI; j++) { 12455 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12456 if (DEBUG_SHOW_INFO) { 12457 Log.v(TAG, " IntentFilter:"); 12458 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12459 } 12460 removeFilter(intent); 12461 } 12462 } 12463 12464 @Override 12465 protected boolean allowFilterResult( 12466 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12467 ServiceInfo filterSi = filter.service.info; 12468 for (int i=dest.size()-1; i>=0; i--) { 12469 ServiceInfo destAi = dest.get(i).serviceInfo; 12470 if (destAi.name == filterSi.name 12471 && destAi.packageName == filterSi.packageName) { 12472 return false; 12473 } 12474 } 12475 return true; 12476 } 12477 12478 @Override 12479 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12480 return new PackageParser.ServiceIntentInfo[size]; 12481 } 12482 12483 @Override 12484 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12485 if (!sUserManager.exists(userId)) return true; 12486 PackageParser.Package p = filter.service.owner; 12487 if (p != null) { 12488 PackageSetting ps = (PackageSetting)p.mExtras; 12489 if (ps != null) { 12490 // System apps are never considered stopped for purposes of 12491 // filtering, because there may be no way for the user to 12492 // actually re-launch them. 12493 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12494 && ps.getStopped(userId); 12495 } 12496 } 12497 return false; 12498 } 12499 12500 @Override 12501 protected boolean isPackageForFilter(String packageName, 12502 PackageParser.ServiceIntentInfo info) { 12503 return packageName.equals(info.service.owner.packageName); 12504 } 12505 12506 @Override 12507 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12508 int match, int userId) { 12509 if (!sUserManager.exists(userId)) return null; 12510 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12511 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12512 return null; 12513 } 12514 final PackageParser.Service service = info.service; 12515 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12516 if (ps == null) { 12517 return null; 12518 } 12519 final PackageUserState userState = ps.readUserState(userId); 12520 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12521 userState, userId); 12522 if (si == null) { 12523 return null; 12524 } 12525 final boolean matchVisibleToInstantApp = 12526 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12527 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12528 // throw out filters that aren't visible to ephemeral apps 12529 if (matchVisibleToInstantApp 12530 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12531 return null; 12532 } 12533 // throw out ephemeral filters if we're not explicitly requesting them 12534 if (!isInstantApp && userState.instantApp) { 12535 return null; 12536 } 12537 // throw out instant app filters if updates are available; will trigger 12538 // instant app resolution 12539 if (userState.instantApp && ps.isUpdateAvailable()) { 12540 return null; 12541 } 12542 final ResolveInfo res = new ResolveInfo(); 12543 res.serviceInfo = si; 12544 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12545 res.filter = filter; 12546 } 12547 res.priority = info.getPriority(); 12548 res.preferredOrder = service.owner.mPreferredOrder; 12549 res.match = match; 12550 res.isDefault = info.hasDefault; 12551 res.labelRes = info.labelRes; 12552 res.nonLocalizedLabel = info.nonLocalizedLabel; 12553 res.icon = info.icon; 12554 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12555 return res; 12556 } 12557 12558 @Override 12559 protected void sortResults(List<ResolveInfo> results) { 12560 Collections.sort(results, mResolvePrioritySorter); 12561 } 12562 12563 @Override 12564 protected void dumpFilter(PrintWriter out, String prefix, 12565 PackageParser.ServiceIntentInfo filter) { 12566 out.print(prefix); out.print( 12567 Integer.toHexString(System.identityHashCode(filter.service))); 12568 out.print(' '); 12569 filter.service.printComponentShortName(out); 12570 out.print(" filter "); 12571 out.println(Integer.toHexString(System.identityHashCode(filter))); 12572 } 12573 12574 @Override 12575 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12576 return filter.service; 12577 } 12578 12579 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12580 PackageParser.Service service = (PackageParser.Service)label; 12581 out.print(prefix); out.print( 12582 Integer.toHexString(System.identityHashCode(service))); 12583 out.print(' '); 12584 service.printComponentShortName(out); 12585 if (count > 1) { 12586 out.print(" ("); out.print(count); out.print(" filters)"); 12587 } 12588 out.println(); 12589 } 12590 12591// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12592// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12593// final List<ResolveInfo> retList = Lists.newArrayList(); 12594// while (i.hasNext()) { 12595// final ResolveInfo resolveInfo = (ResolveInfo) i; 12596// if (isEnabledLP(resolveInfo.serviceInfo)) { 12597// retList.add(resolveInfo); 12598// } 12599// } 12600// return retList; 12601// } 12602 12603 // Keys are String (activity class name), values are Activity. 12604 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12605 = new ArrayMap<ComponentName, PackageParser.Service>(); 12606 private int mFlags; 12607 } 12608 12609 private final class ProviderIntentResolver 12610 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12611 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12612 boolean defaultOnly, int userId) { 12613 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12614 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12615 } 12616 12617 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12618 int userId) { 12619 if (!sUserManager.exists(userId)) 12620 return null; 12621 mFlags = flags; 12622 return super.queryIntent(intent, resolvedType, 12623 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12624 userId); 12625 } 12626 12627 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12628 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12629 if (!sUserManager.exists(userId)) 12630 return null; 12631 if (packageProviders == null) { 12632 return null; 12633 } 12634 mFlags = flags; 12635 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12636 final int N = packageProviders.size(); 12637 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12638 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12639 12640 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12641 for (int i = 0; i < N; ++i) { 12642 intentFilters = packageProviders.get(i).intents; 12643 if (intentFilters != null && intentFilters.size() > 0) { 12644 PackageParser.ProviderIntentInfo[] array = 12645 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12646 intentFilters.toArray(array); 12647 listCut.add(array); 12648 } 12649 } 12650 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12651 } 12652 12653 public final void addProvider(PackageParser.Provider p) { 12654 if (mProviders.containsKey(p.getComponentName())) { 12655 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12656 return; 12657 } 12658 12659 mProviders.put(p.getComponentName(), p); 12660 if (DEBUG_SHOW_INFO) { 12661 Log.v(TAG, " " 12662 + (p.info.nonLocalizedLabel != null 12663 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12664 Log.v(TAG, " Class=" + p.info.name); 12665 } 12666 final int NI = p.intents.size(); 12667 int j; 12668 for (j = 0; j < NI; j++) { 12669 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12670 if (DEBUG_SHOW_INFO) { 12671 Log.v(TAG, " IntentFilter:"); 12672 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12673 } 12674 if (!intent.debugCheck()) { 12675 Log.w(TAG, "==> For Provider " + p.info.name); 12676 } 12677 addFilter(intent); 12678 } 12679 } 12680 12681 public final void removeProvider(PackageParser.Provider p) { 12682 mProviders.remove(p.getComponentName()); 12683 if (DEBUG_SHOW_INFO) { 12684 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12685 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12686 Log.v(TAG, " Class=" + p.info.name); 12687 } 12688 final int NI = p.intents.size(); 12689 int j; 12690 for (j = 0; j < NI; j++) { 12691 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12692 if (DEBUG_SHOW_INFO) { 12693 Log.v(TAG, " IntentFilter:"); 12694 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12695 } 12696 removeFilter(intent); 12697 } 12698 } 12699 12700 @Override 12701 protected boolean allowFilterResult( 12702 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12703 ProviderInfo filterPi = filter.provider.info; 12704 for (int i = dest.size() - 1; i >= 0; i--) { 12705 ProviderInfo destPi = dest.get(i).providerInfo; 12706 if (destPi.name == filterPi.name 12707 && destPi.packageName == filterPi.packageName) { 12708 return false; 12709 } 12710 } 12711 return true; 12712 } 12713 12714 @Override 12715 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12716 return new PackageParser.ProviderIntentInfo[size]; 12717 } 12718 12719 @Override 12720 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12721 if (!sUserManager.exists(userId)) 12722 return true; 12723 PackageParser.Package p = filter.provider.owner; 12724 if (p != null) { 12725 PackageSetting ps = (PackageSetting) p.mExtras; 12726 if (ps != null) { 12727 // System apps are never considered stopped for purposes of 12728 // filtering, because there may be no way for the user to 12729 // actually re-launch them. 12730 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12731 && ps.getStopped(userId); 12732 } 12733 } 12734 return false; 12735 } 12736 12737 @Override 12738 protected boolean isPackageForFilter(String packageName, 12739 PackageParser.ProviderIntentInfo info) { 12740 return packageName.equals(info.provider.owner.packageName); 12741 } 12742 12743 @Override 12744 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12745 int match, int userId) { 12746 if (!sUserManager.exists(userId)) 12747 return null; 12748 final PackageParser.ProviderIntentInfo info = filter; 12749 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12750 return null; 12751 } 12752 final PackageParser.Provider provider = info.provider; 12753 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12754 if (ps == null) { 12755 return null; 12756 } 12757 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12758 ps.readUserState(userId), userId); 12759 if (pi == null) { 12760 return null; 12761 } 12762 final ResolveInfo res = new ResolveInfo(); 12763 res.providerInfo = pi; 12764 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12765 res.filter = filter; 12766 } 12767 res.priority = info.getPriority(); 12768 res.preferredOrder = provider.owner.mPreferredOrder; 12769 res.match = match; 12770 res.isDefault = info.hasDefault; 12771 res.labelRes = info.labelRes; 12772 res.nonLocalizedLabel = info.nonLocalizedLabel; 12773 res.icon = info.icon; 12774 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12775 return res; 12776 } 12777 12778 @Override 12779 protected void sortResults(List<ResolveInfo> results) { 12780 Collections.sort(results, mResolvePrioritySorter); 12781 } 12782 12783 @Override 12784 protected void dumpFilter(PrintWriter out, String prefix, 12785 PackageParser.ProviderIntentInfo filter) { 12786 out.print(prefix); 12787 out.print( 12788 Integer.toHexString(System.identityHashCode(filter.provider))); 12789 out.print(' '); 12790 filter.provider.printComponentShortName(out); 12791 out.print(" filter "); 12792 out.println(Integer.toHexString(System.identityHashCode(filter))); 12793 } 12794 12795 @Override 12796 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12797 return filter.provider; 12798 } 12799 12800 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12801 PackageParser.Provider provider = (PackageParser.Provider)label; 12802 out.print(prefix); out.print( 12803 Integer.toHexString(System.identityHashCode(provider))); 12804 out.print(' '); 12805 provider.printComponentShortName(out); 12806 if (count > 1) { 12807 out.print(" ("); out.print(count); out.print(" filters)"); 12808 } 12809 out.println(); 12810 } 12811 12812 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12813 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12814 private int mFlags; 12815 } 12816 12817 static final class EphemeralIntentResolver 12818 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12819 /** 12820 * The result that has the highest defined order. Ordering applies on a 12821 * per-package basis. Mapping is from package name to Pair of order and 12822 * EphemeralResolveInfo. 12823 * <p> 12824 * NOTE: This is implemented as a field variable for convenience and efficiency. 12825 * By having a field variable, we're able to track filter ordering as soon as 12826 * a non-zero order is defined. Otherwise, multiple loops across the result set 12827 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12828 * this needs to be contained entirely within {@link #filterResults}. 12829 */ 12830 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12831 12832 @Override 12833 protected AuxiliaryResolveInfo[] newArray(int size) { 12834 return new AuxiliaryResolveInfo[size]; 12835 } 12836 12837 @Override 12838 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12839 return true; 12840 } 12841 12842 @Override 12843 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12844 int userId) { 12845 if (!sUserManager.exists(userId)) { 12846 return null; 12847 } 12848 final String packageName = responseObj.resolveInfo.getPackageName(); 12849 final Integer order = responseObj.getOrder(); 12850 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12851 mOrderResult.get(packageName); 12852 // ordering is enabled and this item's order isn't high enough 12853 if (lastOrderResult != null && lastOrderResult.first >= order) { 12854 return null; 12855 } 12856 final InstantAppResolveInfo res = responseObj.resolveInfo; 12857 if (order > 0) { 12858 // non-zero order, enable ordering 12859 mOrderResult.put(packageName, new Pair<>(order, res)); 12860 } 12861 return responseObj; 12862 } 12863 12864 @Override 12865 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12866 // only do work if ordering is enabled [most of the time it won't be] 12867 if (mOrderResult.size() == 0) { 12868 return; 12869 } 12870 int resultSize = results.size(); 12871 for (int i = 0; i < resultSize; i++) { 12872 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12873 final String packageName = info.getPackageName(); 12874 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12875 if (savedInfo == null) { 12876 // package doesn't having ordering 12877 continue; 12878 } 12879 if (savedInfo.second == info) { 12880 // circled back to the highest ordered item; remove from order list 12881 mOrderResult.remove(savedInfo); 12882 if (mOrderResult.size() == 0) { 12883 // no more ordered items 12884 break; 12885 } 12886 continue; 12887 } 12888 // item has a worse order, remove it from the result list 12889 results.remove(i); 12890 resultSize--; 12891 i--; 12892 } 12893 } 12894 } 12895 12896 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12897 new Comparator<ResolveInfo>() { 12898 public int compare(ResolveInfo r1, ResolveInfo r2) { 12899 int v1 = r1.priority; 12900 int v2 = r2.priority; 12901 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12902 if (v1 != v2) { 12903 return (v1 > v2) ? -1 : 1; 12904 } 12905 v1 = r1.preferredOrder; 12906 v2 = r2.preferredOrder; 12907 if (v1 != v2) { 12908 return (v1 > v2) ? -1 : 1; 12909 } 12910 if (r1.isDefault != r2.isDefault) { 12911 return r1.isDefault ? -1 : 1; 12912 } 12913 v1 = r1.match; 12914 v2 = r2.match; 12915 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 12916 if (v1 != v2) { 12917 return (v1 > v2) ? -1 : 1; 12918 } 12919 if (r1.system != r2.system) { 12920 return r1.system ? -1 : 1; 12921 } 12922 if (r1.activityInfo != null) { 12923 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 12924 } 12925 if (r1.serviceInfo != null) { 12926 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 12927 } 12928 if (r1.providerInfo != null) { 12929 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 12930 } 12931 return 0; 12932 } 12933 }; 12934 12935 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 12936 new Comparator<ProviderInfo>() { 12937 public int compare(ProviderInfo p1, ProviderInfo p2) { 12938 final int v1 = p1.initOrder; 12939 final int v2 = p2.initOrder; 12940 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12941 } 12942 }; 12943 12944 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12945 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12946 final int[] userIds) { 12947 mHandler.post(new Runnable() { 12948 @Override 12949 public void run() { 12950 try { 12951 final IActivityManager am = ActivityManager.getService(); 12952 if (am == null) return; 12953 final int[] resolvedUserIds; 12954 if (userIds == null) { 12955 resolvedUserIds = am.getRunningUserIds(); 12956 } else { 12957 resolvedUserIds = userIds; 12958 } 12959 for (int id : resolvedUserIds) { 12960 final Intent intent = new Intent(action, 12961 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12962 if (extras != null) { 12963 intent.putExtras(extras); 12964 } 12965 if (targetPkg != null) { 12966 intent.setPackage(targetPkg); 12967 } 12968 // Modify the UID when posting to other users 12969 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12970 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12971 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12972 intent.putExtra(Intent.EXTRA_UID, uid); 12973 } 12974 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12975 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12976 if (DEBUG_BROADCASTS) { 12977 RuntimeException here = new RuntimeException("here"); 12978 here.fillInStackTrace(); 12979 Slog.d(TAG, "Sending to user " + id + ": " 12980 + intent.toShortString(false, true, false, false) 12981 + " " + intent.getExtras(), here); 12982 } 12983 am.broadcastIntent(null, intent, null, finishedReceiver, 12984 0, null, null, null, android.app.AppOpsManager.OP_NONE, 12985 null, finishedReceiver != null, false, id); 12986 } 12987 } catch (RemoteException ex) { 12988 } 12989 } 12990 }); 12991 } 12992 12993 /** 12994 * Check if the external storage media is available. This is true if there 12995 * is a mounted external storage medium or if the external storage is 12996 * emulated. 12997 */ 12998 private boolean isExternalMediaAvailable() { 12999 return mMediaMounted || Environment.isExternalStorageEmulated(); 13000 } 13001 13002 @Override 13003 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13004 // writer 13005 synchronized (mPackages) { 13006 if (!isExternalMediaAvailable()) { 13007 // If the external storage is no longer mounted at this point, 13008 // the caller may not have been able to delete all of this 13009 // packages files and can not delete any more. Bail. 13010 return null; 13011 } 13012 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13013 if (lastPackage != null) { 13014 pkgs.remove(lastPackage); 13015 } 13016 if (pkgs.size() > 0) { 13017 return pkgs.get(0); 13018 } 13019 } 13020 return null; 13021 } 13022 13023 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13024 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13025 userId, andCode ? 1 : 0, packageName); 13026 if (mSystemReady) { 13027 msg.sendToTarget(); 13028 } else { 13029 if (mPostSystemReadyMessages == null) { 13030 mPostSystemReadyMessages = new ArrayList<>(); 13031 } 13032 mPostSystemReadyMessages.add(msg); 13033 } 13034 } 13035 13036 void startCleaningPackages() { 13037 // reader 13038 if (!isExternalMediaAvailable()) { 13039 return; 13040 } 13041 synchronized (mPackages) { 13042 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13043 return; 13044 } 13045 } 13046 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13047 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13048 IActivityManager am = ActivityManager.getService(); 13049 if (am != null) { 13050 int dcsUid = -1; 13051 synchronized (mPackages) { 13052 if (!mDefaultContainerWhitelisted) { 13053 mDefaultContainerWhitelisted = true; 13054 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13055 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13056 } 13057 } 13058 try { 13059 if (dcsUid > 0) { 13060 am.backgroundWhitelistUid(dcsUid); 13061 } 13062 am.startService(null, intent, null, -1, null, false, mContext.getOpPackageName(), 13063 UserHandle.USER_SYSTEM); 13064 } catch (RemoteException e) { 13065 } 13066 } 13067 } 13068 13069 @Override 13070 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 13071 int installFlags, String installerPackageName, int userId) { 13072 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 13073 13074 final int callingUid = Binder.getCallingUid(); 13075 enforceCrossUserPermission(callingUid, userId, 13076 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 13077 13078 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13079 try { 13080 if (observer != null) { 13081 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 13082 } 13083 } catch (RemoteException re) { 13084 } 13085 return; 13086 } 13087 13088 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 13089 installFlags |= PackageManager.INSTALL_FROM_ADB; 13090 13091 } else { 13092 // Caller holds INSTALL_PACKAGES permission, so we're less strict 13093 // about installerPackageName. 13094 13095 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 13096 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 13097 } 13098 13099 UserHandle user; 13100 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 13101 user = UserHandle.ALL; 13102 } else { 13103 user = new UserHandle(userId); 13104 } 13105 13106 // Only system components can circumvent runtime permissions when installing. 13107 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 13108 && mContext.checkCallingOrSelfPermission(Manifest.permission 13109 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 13110 throw new SecurityException("You need the " 13111 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 13112 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 13113 } 13114 13115 if ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0 13116 || (installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13117 throw new IllegalArgumentException( 13118 "New installs into ASEC containers no longer supported"); 13119 } 13120 13121 final File originFile = new File(originPath); 13122 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 13123 13124 final Message msg = mHandler.obtainMessage(INIT_COPY); 13125 final VerificationInfo verificationInfo = new VerificationInfo( 13126 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 13127 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 13128 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 13129 null /*packageAbiOverride*/, null /*grantedPermissions*/, 13130 null /*certificates*/, PackageManager.INSTALL_REASON_UNKNOWN); 13131 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 13132 msg.obj = params; 13133 13134 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 13135 System.identityHashCode(msg.obj)); 13136 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13137 System.identityHashCode(msg.obj)); 13138 13139 mHandler.sendMessage(msg); 13140 } 13141 13142 13143 /** 13144 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13145 * it is acting on behalf on an enterprise or the user). 13146 * 13147 * Note that the ordering of the conditionals in this method is important. The checks we perform 13148 * are as follows, in this order: 13149 * 13150 * 1) If the install is being performed by a system app, we can trust the app to have set the 13151 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13152 * what it is. 13153 * 2) If the install is being performed by a device or profile owner app, the install reason 13154 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13155 * set the install reason correctly. If the app targets an older SDK version where install 13156 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13157 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13158 * 3) In all other cases, the install is being performed by a regular app that is neither part 13159 * of the system nor a device or profile owner. We have no reason to believe that this app is 13160 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13161 * set to enterprise policy and if so, change it to unknown instead. 13162 */ 13163 private int fixUpInstallReason(String installerPackageName, int installerUid, 13164 int installReason) { 13165 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13166 == PERMISSION_GRANTED) { 13167 // If the install is being performed by a system app, we trust that app to have set the 13168 // install reason correctly. 13169 return installReason; 13170 } 13171 13172 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13173 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13174 if (dpm != null) { 13175 ComponentName owner = null; 13176 try { 13177 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13178 if (owner == null) { 13179 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13180 } 13181 } catch (RemoteException e) { 13182 } 13183 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13184 // If the install is being performed by a device or profile owner, the install 13185 // reason should be enterprise policy. 13186 return PackageManager.INSTALL_REASON_POLICY; 13187 } 13188 } 13189 13190 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13191 // If the install is being performed by a regular app (i.e. neither system app nor 13192 // device or profile owner), we have no reason to believe that the app is acting on 13193 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13194 // change it to unknown instead. 13195 return PackageManager.INSTALL_REASON_UNKNOWN; 13196 } 13197 13198 // If the install is being performed by a regular app and the install reason was set to any 13199 // value but enterprise policy, leave the install reason unchanged. 13200 return installReason; 13201 } 13202 13203 void installStage(String packageName, File stagedDir, String stagedCid, 13204 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13205 String installerPackageName, int installerUid, UserHandle user, 13206 Certificate[][] certificates) { 13207 if (DEBUG_EPHEMERAL) { 13208 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13209 Slog.d(TAG, "Ephemeral install of " + packageName); 13210 } 13211 } 13212 final VerificationInfo verificationInfo = new VerificationInfo( 13213 sessionParams.originatingUri, sessionParams.referrerUri, 13214 sessionParams.originatingUid, installerUid); 13215 13216 final OriginInfo origin; 13217 if (stagedDir != null) { 13218 origin = OriginInfo.fromStagedFile(stagedDir); 13219 } else { 13220 origin = OriginInfo.fromStagedContainer(stagedCid); 13221 } 13222 13223 final Message msg = mHandler.obtainMessage(INIT_COPY); 13224 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13225 sessionParams.installReason); 13226 final InstallParams params = new InstallParams(origin, null, observer, 13227 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13228 verificationInfo, user, sessionParams.abiOverride, 13229 sessionParams.grantedRuntimePermissions, certificates, installReason); 13230 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13231 msg.obj = params; 13232 13233 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13234 System.identityHashCode(msg.obj)); 13235 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13236 System.identityHashCode(msg.obj)); 13237 13238 mHandler.sendMessage(msg); 13239 } 13240 13241 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13242 int userId) { 13243 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13244 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 13245 } 13246 13247 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 13248 int appId, int... userIds) { 13249 if (ArrayUtils.isEmpty(userIds)) { 13250 return; 13251 } 13252 Bundle extras = new Bundle(1); 13253 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13254 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 13255 13256 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13257 packageName, extras, 0, null, null, userIds); 13258 if (isSystem) { 13259 mHandler.post(() -> { 13260 for (int userId : userIds) { 13261 sendBootCompletedBroadcastToSystemApp(packageName, userId); 13262 } 13263 } 13264 ); 13265 } 13266 } 13267 13268 /** 13269 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13270 * automatically without needing an explicit launch. 13271 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13272 */ 13273 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 13274 // If user is not running, the app didn't miss any broadcast 13275 if (!mUserManagerInternal.isUserRunning(userId)) { 13276 return; 13277 } 13278 final IActivityManager am = ActivityManager.getService(); 13279 try { 13280 // Deliver LOCKED_BOOT_COMPLETED first 13281 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13282 .setPackage(packageName); 13283 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13284 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13285 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13286 13287 // Deliver BOOT_COMPLETED only if user is unlocked 13288 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13289 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13290 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13291 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13292 } 13293 } catch (RemoteException e) { 13294 throw e.rethrowFromSystemServer(); 13295 } 13296 } 13297 13298 @Override 13299 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13300 int userId) { 13301 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13302 PackageSetting pkgSetting; 13303 final int uid = Binder.getCallingUid(); 13304 enforceCrossUserPermission(uid, userId, 13305 true /* requireFullPermission */, true /* checkShell */, 13306 "setApplicationHiddenSetting for user " + userId); 13307 13308 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13309 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13310 return false; 13311 } 13312 13313 long callingId = Binder.clearCallingIdentity(); 13314 try { 13315 boolean sendAdded = false; 13316 boolean sendRemoved = false; 13317 // writer 13318 synchronized (mPackages) { 13319 pkgSetting = mSettings.mPackages.get(packageName); 13320 if (pkgSetting == null) { 13321 return false; 13322 } 13323 // Do not allow "android" is being disabled 13324 if ("android".equals(packageName)) { 13325 Slog.w(TAG, "Cannot hide package: android"); 13326 return false; 13327 } 13328 // Cannot hide static shared libs as they are considered 13329 // a part of the using app (emulating static linking). Also 13330 // static libs are installed always on internal storage. 13331 PackageParser.Package pkg = mPackages.get(packageName); 13332 if (pkg != null && pkg.staticSharedLibName != null) { 13333 Slog.w(TAG, "Cannot hide package: " + packageName 13334 + " providing static shared library: " 13335 + pkg.staticSharedLibName); 13336 return false; 13337 } 13338 // Only allow protected packages to hide themselves. 13339 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 13340 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13341 Slog.w(TAG, "Not hiding protected package: " + packageName); 13342 return false; 13343 } 13344 13345 if (pkgSetting.getHidden(userId) != hidden) { 13346 pkgSetting.setHidden(hidden, userId); 13347 mSettings.writePackageRestrictionsLPr(userId); 13348 if (hidden) { 13349 sendRemoved = true; 13350 } else { 13351 sendAdded = true; 13352 } 13353 } 13354 } 13355 if (sendAdded) { 13356 sendPackageAddedForUser(packageName, pkgSetting, userId); 13357 return true; 13358 } 13359 if (sendRemoved) { 13360 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13361 "hiding pkg"); 13362 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13363 return true; 13364 } 13365 } finally { 13366 Binder.restoreCallingIdentity(callingId); 13367 } 13368 return false; 13369 } 13370 13371 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13372 int userId) { 13373 final PackageRemovedInfo info = new PackageRemovedInfo(); 13374 info.removedPackage = packageName; 13375 info.removedUsers = new int[] {userId}; 13376 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13377 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13378 } 13379 13380 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13381 if (pkgList.length > 0) { 13382 Bundle extras = new Bundle(1); 13383 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13384 13385 sendPackageBroadcast( 13386 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13387 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13388 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13389 new int[] {userId}); 13390 } 13391 } 13392 13393 /** 13394 * Returns true if application is not found or there was an error. Otherwise it returns 13395 * the hidden state of the package for the given user. 13396 */ 13397 @Override 13398 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13399 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13400 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13401 true /* requireFullPermission */, false /* checkShell */, 13402 "getApplicationHidden for user " + userId); 13403 PackageSetting pkgSetting; 13404 long callingId = Binder.clearCallingIdentity(); 13405 try { 13406 // writer 13407 synchronized (mPackages) { 13408 pkgSetting = mSettings.mPackages.get(packageName); 13409 if (pkgSetting == null) { 13410 return true; 13411 } 13412 return pkgSetting.getHidden(userId); 13413 } 13414 } finally { 13415 Binder.restoreCallingIdentity(callingId); 13416 } 13417 } 13418 13419 /** 13420 * @hide 13421 */ 13422 @Override 13423 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13424 int installReason) { 13425 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13426 null); 13427 PackageSetting pkgSetting; 13428 final int uid = Binder.getCallingUid(); 13429 enforceCrossUserPermission(uid, userId, 13430 true /* requireFullPermission */, true /* checkShell */, 13431 "installExistingPackage for user " + userId); 13432 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13433 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13434 } 13435 13436 long callingId = Binder.clearCallingIdentity(); 13437 try { 13438 boolean installed = false; 13439 final boolean instantApp = 13440 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13441 final boolean fullApp = 13442 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13443 13444 // writer 13445 synchronized (mPackages) { 13446 pkgSetting = mSettings.mPackages.get(packageName); 13447 if (pkgSetting == null) { 13448 return PackageManager.INSTALL_FAILED_INVALID_URI; 13449 } 13450 if (!pkgSetting.getInstalled(userId)) { 13451 pkgSetting.setInstalled(true, userId); 13452 pkgSetting.setHidden(false, userId); 13453 pkgSetting.setInstallReason(installReason, userId); 13454 mSettings.writePackageRestrictionsLPr(userId); 13455 mSettings.writeKernelMappingLPr(pkgSetting); 13456 installed = true; 13457 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13458 // upgrade app from instant to full; we don't allow app downgrade 13459 installed = true; 13460 } 13461 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13462 } 13463 13464 if (installed) { 13465 if (pkgSetting.pkg != null) { 13466 synchronized (mInstallLock) { 13467 // We don't need to freeze for a brand new install 13468 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13469 } 13470 } 13471 sendPackageAddedForUser(packageName, pkgSetting, userId); 13472 synchronized (mPackages) { 13473 updateSequenceNumberLP(packageName, new int[]{ userId }); 13474 } 13475 } 13476 } finally { 13477 Binder.restoreCallingIdentity(callingId); 13478 } 13479 13480 return PackageManager.INSTALL_SUCCEEDED; 13481 } 13482 13483 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13484 boolean instantApp, boolean fullApp) { 13485 // no state specified; do nothing 13486 if (!instantApp && !fullApp) { 13487 return; 13488 } 13489 if (userId != UserHandle.USER_ALL) { 13490 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13491 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13492 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13493 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13494 } 13495 } else { 13496 for (int currentUserId : sUserManager.getUserIds()) { 13497 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13498 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13499 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13500 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13501 } 13502 } 13503 } 13504 } 13505 13506 boolean isUserRestricted(int userId, String restrictionKey) { 13507 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13508 if (restrictions.getBoolean(restrictionKey, false)) { 13509 Log.w(TAG, "User is restricted: " + restrictionKey); 13510 return true; 13511 } 13512 return false; 13513 } 13514 13515 @Override 13516 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13517 int userId) { 13518 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13519 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13520 true /* requireFullPermission */, true /* checkShell */, 13521 "setPackagesSuspended for user " + userId); 13522 13523 if (ArrayUtils.isEmpty(packageNames)) { 13524 return packageNames; 13525 } 13526 13527 // List of package names for whom the suspended state has changed. 13528 List<String> changedPackages = new ArrayList<>(packageNames.length); 13529 // List of package names for whom the suspended state is not set as requested in this 13530 // method. 13531 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13532 long callingId = Binder.clearCallingIdentity(); 13533 try { 13534 for (int i = 0; i < packageNames.length; i++) { 13535 String packageName = packageNames[i]; 13536 boolean changed = false; 13537 final int appId; 13538 synchronized (mPackages) { 13539 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13540 if (pkgSetting == null) { 13541 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13542 + "\". Skipping suspending/un-suspending."); 13543 unactionedPackages.add(packageName); 13544 continue; 13545 } 13546 appId = pkgSetting.appId; 13547 if (pkgSetting.getSuspended(userId) != suspended) { 13548 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13549 unactionedPackages.add(packageName); 13550 continue; 13551 } 13552 pkgSetting.setSuspended(suspended, userId); 13553 mSettings.writePackageRestrictionsLPr(userId); 13554 changed = true; 13555 changedPackages.add(packageName); 13556 } 13557 } 13558 13559 if (changed && suspended) { 13560 killApplication(packageName, UserHandle.getUid(userId, appId), 13561 "suspending package"); 13562 } 13563 } 13564 } finally { 13565 Binder.restoreCallingIdentity(callingId); 13566 } 13567 13568 if (!changedPackages.isEmpty()) { 13569 sendPackagesSuspendedForUser(changedPackages.toArray( 13570 new String[changedPackages.size()]), userId, suspended); 13571 } 13572 13573 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13574 } 13575 13576 @Override 13577 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13578 enforceCrossUserPermission(Binder.getCallingUid(), userId, 13579 true /* requireFullPermission */, false /* checkShell */, 13580 "isPackageSuspendedForUser for user " + userId); 13581 synchronized (mPackages) { 13582 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13583 if (pkgSetting == null) { 13584 throw new IllegalArgumentException("Unknown target package: " + packageName); 13585 } 13586 return pkgSetting.getSuspended(userId); 13587 } 13588 } 13589 13590 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13591 if (isPackageDeviceAdmin(packageName, userId)) { 13592 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13593 + "\": has an active device admin"); 13594 return false; 13595 } 13596 13597 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13598 if (packageName.equals(activeLauncherPackageName)) { 13599 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13600 + "\": contains the active launcher"); 13601 return false; 13602 } 13603 13604 if (packageName.equals(mRequiredInstallerPackage)) { 13605 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13606 + "\": required for package installation"); 13607 return false; 13608 } 13609 13610 if (packageName.equals(mRequiredUninstallerPackage)) { 13611 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13612 + "\": required for package uninstallation"); 13613 return false; 13614 } 13615 13616 if (packageName.equals(mRequiredVerifierPackage)) { 13617 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13618 + "\": required for package verification"); 13619 return false; 13620 } 13621 13622 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13623 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13624 + "\": is the default dialer"); 13625 return false; 13626 } 13627 13628 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13629 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13630 + "\": protected package"); 13631 return false; 13632 } 13633 13634 // Cannot suspend static shared libs as they are considered 13635 // a part of the using app (emulating static linking). Also 13636 // static libs are installed always on internal storage. 13637 PackageParser.Package pkg = mPackages.get(packageName); 13638 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13639 Slog.w(TAG, "Cannot suspend package: " + packageName 13640 + " providing static shared library: " 13641 + pkg.staticSharedLibName); 13642 return false; 13643 } 13644 13645 return true; 13646 } 13647 13648 private String getActiveLauncherPackageName(int userId) { 13649 Intent intent = new Intent(Intent.ACTION_MAIN); 13650 intent.addCategory(Intent.CATEGORY_HOME); 13651 ResolveInfo resolveInfo = resolveIntent( 13652 intent, 13653 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13654 PackageManager.MATCH_DEFAULT_ONLY, 13655 userId); 13656 13657 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13658 } 13659 13660 private String getDefaultDialerPackageName(int userId) { 13661 synchronized (mPackages) { 13662 return mSettings.getDefaultDialerPackageNameLPw(userId); 13663 } 13664 } 13665 13666 @Override 13667 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13668 mContext.enforceCallingOrSelfPermission( 13669 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13670 "Only package verification agents can verify applications"); 13671 13672 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13673 final PackageVerificationResponse response = new PackageVerificationResponse( 13674 verificationCode, Binder.getCallingUid()); 13675 msg.arg1 = id; 13676 msg.obj = response; 13677 mHandler.sendMessage(msg); 13678 } 13679 13680 @Override 13681 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13682 long millisecondsToDelay) { 13683 mContext.enforceCallingOrSelfPermission( 13684 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13685 "Only package verification agents can extend verification timeouts"); 13686 13687 final PackageVerificationState state = mPendingVerification.get(id); 13688 final PackageVerificationResponse response = new PackageVerificationResponse( 13689 verificationCodeAtTimeout, Binder.getCallingUid()); 13690 13691 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13692 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13693 } 13694 if (millisecondsToDelay < 0) { 13695 millisecondsToDelay = 0; 13696 } 13697 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13698 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13699 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13700 } 13701 13702 if ((state != null) && !state.timeoutExtended()) { 13703 state.extendTimeout(); 13704 13705 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13706 msg.arg1 = id; 13707 msg.obj = response; 13708 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13709 } 13710 } 13711 13712 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13713 int verificationCode, UserHandle user) { 13714 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13715 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13716 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13717 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13718 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13719 13720 mContext.sendBroadcastAsUser(intent, user, 13721 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13722 } 13723 13724 private ComponentName matchComponentForVerifier(String packageName, 13725 List<ResolveInfo> receivers) { 13726 ActivityInfo targetReceiver = null; 13727 13728 final int NR = receivers.size(); 13729 for (int i = 0; i < NR; i++) { 13730 final ResolveInfo info = receivers.get(i); 13731 if (info.activityInfo == null) { 13732 continue; 13733 } 13734 13735 if (packageName.equals(info.activityInfo.packageName)) { 13736 targetReceiver = info.activityInfo; 13737 break; 13738 } 13739 } 13740 13741 if (targetReceiver == null) { 13742 return null; 13743 } 13744 13745 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13746 } 13747 13748 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13749 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13750 if (pkgInfo.verifiers.length == 0) { 13751 return null; 13752 } 13753 13754 final int N = pkgInfo.verifiers.length; 13755 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13756 for (int i = 0; i < N; i++) { 13757 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13758 13759 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13760 receivers); 13761 if (comp == null) { 13762 continue; 13763 } 13764 13765 final int verifierUid = getUidForVerifier(verifierInfo); 13766 if (verifierUid == -1) { 13767 continue; 13768 } 13769 13770 if (DEBUG_VERIFY) { 13771 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13772 + " with the correct signature"); 13773 } 13774 sufficientVerifiers.add(comp); 13775 verificationState.addSufficientVerifier(verifierUid); 13776 } 13777 13778 return sufficientVerifiers; 13779 } 13780 13781 private int getUidForVerifier(VerifierInfo verifierInfo) { 13782 synchronized (mPackages) { 13783 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13784 if (pkg == null) { 13785 return -1; 13786 } else if (pkg.mSignatures.length != 1) { 13787 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13788 + " has more than one signature; ignoring"); 13789 return -1; 13790 } 13791 13792 /* 13793 * If the public key of the package's signature does not match 13794 * our expected public key, then this is a different package and 13795 * we should skip. 13796 */ 13797 13798 final byte[] expectedPublicKey; 13799 try { 13800 final Signature verifierSig = pkg.mSignatures[0]; 13801 final PublicKey publicKey = verifierSig.getPublicKey(); 13802 expectedPublicKey = publicKey.getEncoded(); 13803 } catch (CertificateException e) { 13804 return -1; 13805 } 13806 13807 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13808 13809 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13810 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13811 + " does not have the expected public key; ignoring"); 13812 return -1; 13813 } 13814 13815 return pkg.applicationInfo.uid; 13816 } 13817 } 13818 13819 @Override 13820 public void finishPackageInstall(int token, boolean didLaunch) { 13821 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13822 13823 if (DEBUG_INSTALL) { 13824 Slog.v(TAG, "BM finishing package install for " + token); 13825 } 13826 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13827 13828 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13829 mHandler.sendMessage(msg); 13830 } 13831 13832 /** 13833 * Get the verification agent timeout. 13834 * 13835 * @return verification timeout in milliseconds 13836 */ 13837 private long getVerificationTimeout() { 13838 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13839 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13840 DEFAULT_VERIFICATION_TIMEOUT); 13841 } 13842 13843 /** 13844 * Get the default verification agent response code. 13845 * 13846 * @return default verification response code 13847 */ 13848 private int getDefaultVerificationResponse() { 13849 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13850 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13851 DEFAULT_VERIFICATION_RESPONSE); 13852 } 13853 13854 /** 13855 * Check whether or not package verification has been enabled. 13856 * 13857 * @return true if verification should be performed 13858 */ 13859 private boolean isVerificationEnabled(int userId, int installFlags) { 13860 if (!DEFAULT_VERIFY_ENABLE) { 13861 return false; 13862 } 13863 13864 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13865 13866 // Check if installing from ADB 13867 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13868 // Do not run verification in a test harness environment 13869 if (ActivityManager.isRunningInTestHarness()) { 13870 return false; 13871 } 13872 if (ensureVerifyAppsEnabled) { 13873 return true; 13874 } 13875 // Check if the developer does not want package verification for ADB installs 13876 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13877 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13878 return false; 13879 } 13880 } 13881 13882 if (ensureVerifyAppsEnabled) { 13883 return true; 13884 } 13885 13886 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13887 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13888 } 13889 13890 @Override 13891 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13892 throws RemoteException { 13893 mContext.enforceCallingOrSelfPermission( 13894 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13895 "Only intentfilter verification agents can verify applications"); 13896 13897 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13898 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13899 Binder.getCallingUid(), verificationCode, failedDomains); 13900 msg.arg1 = id; 13901 msg.obj = response; 13902 mHandler.sendMessage(msg); 13903 } 13904 13905 @Override 13906 public int getIntentVerificationStatus(String packageName, int userId) { 13907 synchronized (mPackages) { 13908 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13909 } 13910 } 13911 13912 @Override 13913 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13914 mContext.enforceCallingOrSelfPermission( 13915 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13916 13917 boolean result = false; 13918 synchronized (mPackages) { 13919 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13920 } 13921 if (result) { 13922 scheduleWritePackageRestrictionsLocked(userId); 13923 } 13924 return result; 13925 } 13926 13927 @Override 13928 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13929 String packageName) { 13930 synchronized (mPackages) { 13931 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13932 } 13933 } 13934 13935 @Override 13936 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13937 if (TextUtils.isEmpty(packageName)) { 13938 return ParceledListSlice.emptyList(); 13939 } 13940 synchronized (mPackages) { 13941 PackageParser.Package pkg = mPackages.get(packageName); 13942 if (pkg == null || pkg.activities == null) { 13943 return ParceledListSlice.emptyList(); 13944 } 13945 final int count = pkg.activities.size(); 13946 ArrayList<IntentFilter> result = new ArrayList<>(); 13947 for (int n=0; n<count; n++) { 13948 PackageParser.Activity activity = pkg.activities.get(n); 13949 if (activity.intents != null && activity.intents.size() > 0) { 13950 result.addAll(activity.intents); 13951 } 13952 } 13953 return new ParceledListSlice<>(result); 13954 } 13955 } 13956 13957 @Override 13958 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13959 mContext.enforceCallingOrSelfPermission( 13960 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13961 13962 synchronized (mPackages) { 13963 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 13964 if (packageName != null) { 13965 result |= updateIntentVerificationStatus(packageName, 13966 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 13967 userId); 13968 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 13969 packageName, userId); 13970 } 13971 return result; 13972 } 13973 } 13974 13975 @Override 13976 public String getDefaultBrowserPackageName(int userId) { 13977 synchronized (mPackages) { 13978 return mSettings.getDefaultBrowserPackageNameLPw(userId); 13979 } 13980 } 13981 13982 /** 13983 * Get the "allow unknown sources" setting. 13984 * 13985 * @return the current "allow unknown sources" setting 13986 */ 13987 private int getUnknownSourcesSettings() { 13988 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 13989 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 13990 -1); 13991 } 13992 13993 @Override 13994 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 13995 final int uid = Binder.getCallingUid(); 13996 // writer 13997 synchronized (mPackages) { 13998 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 13999 if (targetPackageSetting == null) { 14000 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14001 } 14002 14003 PackageSetting installerPackageSetting; 14004 if (installerPackageName != null) { 14005 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14006 if (installerPackageSetting == null) { 14007 throw new IllegalArgumentException("Unknown installer package: " 14008 + installerPackageName); 14009 } 14010 } else { 14011 installerPackageSetting = null; 14012 } 14013 14014 Signature[] callerSignature; 14015 Object obj = mSettings.getUserIdLPr(uid); 14016 if (obj != null) { 14017 if (obj instanceof SharedUserSetting) { 14018 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14019 } else if (obj instanceof PackageSetting) { 14020 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14021 } else { 14022 throw new SecurityException("Bad object " + obj + " for uid " + uid); 14023 } 14024 } else { 14025 throw new SecurityException("Unknown calling UID: " + uid); 14026 } 14027 14028 // Verify: can't set installerPackageName to a package that is 14029 // not signed with the same cert as the caller. 14030 if (installerPackageSetting != null) { 14031 if (compareSignatures(callerSignature, 14032 installerPackageSetting.signatures.mSignatures) 14033 != PackageManager.SIGNATURE_MATCH) { 14034 throw new SecurityException( 14035 "Caller does not have same cert as new installer package " 14036 + installerPackageName); 14037 } 14038 } 14039 14040 // Verify: if target already has an installer package, it must 14041 // be signed with the same cert as the caller. 14042 if (targetPackageSetting.installerPackageName != null) { 14043 PackageSetting setting = mSettings.mPackages.get( 14044 targetPackageSetting.installerPackageName); 14045 // If the currently set package isn't valid, then it's always 14046 // okay to change it. 14047 if (setting != null) { 14048 if (compareSignatures(callerSignature, 14049 setting.signatures.mSignatures) 14050 != PackageManager.SIGNATURE_MATCH) { 14051 throw new SecurityException( 14052 "Caller does not have same cert as old installer package " 14053 + targetPackageSetting.installerPackageName); 14054 } 14055 } 14056 } 14057 14058 // Okay! 14059 targetPackageSetting.installerPackageName = installerPackageName; 14060 if (installerPackageName != null) { 14061 mSettings.mInstallerPackages.add(installerPackageName); 14062 } 14063 scheduleWriteSettingsLocked(); 14064 } 14065 } 14066 14067 @Override 14068 public void setApplicationCategoryHint(String packageName, int categoryHint, 14069 String callerPackageName) { 14070 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14071 callerPackageName); 14072 synchronized (mPackages) { 14073 PackageSetting ps = mSettings.mPackages.get(packageName); 14074 if (ps == null) { 14075 throw new IllegalArgumentException("Unknown target package " + packageName); 14076 } 14077 14078 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14079 throw new IllegalArgumentException("Calling package " + callerPackageName 14080 + " is not installer for " + packageName); 14081 } 14082 14083 if (ps.categoryHint != categoryHint) { 14084 ps.categoryHint = categoryHint; 14085 scheduleWriteSettingsLocked(); 14086 } 14087 } 14088 } 14089 14090 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14091 // Queue up an async operation since the package installation may take a little while. 14092 mHandler.post(new Runnable() { 14093 public void run() { 14094 mHandler.removeCallbacks(this); 14095 // Result object to be returned 14096 PackageInstalledInfo res = new PackageInstalledInfo(); 14097 res.setReturnCode(currentStatus); 14098 res.uid = -1; 14099 res.pkg = null; 14100 res.removedInfo = null; 14101 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14102 args.doPreInstall(res.returnCode); 14103 synchronized (mInstallLock) { 14104 installPackageTracedLI(args, res); 14105 } 14106 args.doPostInstall(res.returnCode, res.uid); 14107 } 14108 14109 // A restore should be performed at this point if (a) the install 14110 // succeeded, (b) the operation is not an update, and (c) the new 14111 // package has not opted out of backup participation. 14112 final boolean update = res.removedInfo != null 14113 && res.removedInfo.removedPackage != null; 14114 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14115 boolean doRestore = !update 14116 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14117 14118 // Set up the post-install work request bookkeeping. This will be used 14119 // and cleaned up by the post-install event handling regardless of whether 14120 // there's a restore pass performed. Token values are >= 1. 14121 int token; 14122 if (mNextInstallToken < 0) mNextInstallToken = 1; 14123 token = mNextInstallToken++; 14124 14125 PostInstallData data = new PostInstallData(args, res); 14126 mRunningInstalls.put(token, data); 14127 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14128 14129 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14130 // Pass responsibility to the Backup Manager. It will perform a 14131 // restore if appropriate, then pass responsibility back to the 14132 // Package Manager to run the post-install observer callbacks 14133 // and broadcasts. 14134 IBackupManager bm = IBackupManager.Stub.asInterface( 14135 ServiceManager.getService(Context.BACKUP_SERVICE)); 14136 if (bm != null) { 14137 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14138 + " to BM for possible restore"); 14139 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14140 try { 14141 // TODO: http://b/22388012 14142 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14143 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14144 } else { 14145 doRestore = false; 14146 } 14147 } catch (RemoteException e) { 14148 // can't happen; the backup manager is local 14149 } catch (Exception e) { 14150 Slog.e(TAG, "Exception trying to enqueue restore", e); 14151 doRestore = false; 14152 } 14153 } else { 14154 Slog.e(TAG, "Backup Manager not found!"); 14155 doRestore = false; 14156 } 14157 } 14158 14159 if (!doRestore) { 14160 // No restore possible, or the Backup Manager was mysteriously not 14161 // available -- just fire the post-install work request directly. 14162 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14163 14164 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14165 14166 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14167 mHandler.sendMessage(msg); 14168 } 14169 } 14170 }); 14171 } 14172 14173 /** 14174 * Callback from PackageSettings whenever an app is first transitioned out of the 14175 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14176 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14177 * here whether the app is the target of an ongoing install, and only send the 14178 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14179 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14180 * handling. 14181 */ 14182 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 14183 // Serialize this with the rest of the install-process message chain. In the 14184 // restore-at-install case, this Runnable will necessarily run before the 14185 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14186 // are coherent. In the non-restore case, the app has already completed install 14187 // and been launched through some other means, so it is not in a problematic 14188 // state for observers to see the FIRST_LAUNCH signal. 14189 mHandler.post(new Runnable() { 14190 @Override 14191 public void run() { 14192 for (int i = 0; i < mRunningInstalls.size(); i++) { 14193 final PostInstallData data = mRunningInstalls.valueAt(i); 14194 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14195 continue; 14196 } 14197 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 14198 // right package; but is it for the right user? 14199 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14200 if (userId == data.res.newUsers[uIndex]) { 14201 if (DEBUG_BACKUP) { 14202 Slog.i(TAG, "Package " + pkgName 14203 + " being restored so deferring FIRST_LAUNCH"); 14204 } 14205 return; 14206 } 14207 } 14208 } 14209 } 14210 // didn't find it, so not being restored 14211 if (DEBUG_BACKUP) { 14212 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 14213 } 14214 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 14215 } 14216 }); 14217 } 14218 14219 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 14220 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14221 installerPkg, null, userIds); 14222 } 14223 14224 private abstract class HandlerParams { 14225 private static final int MAX_RETRIES = 4; 14226 14227 /** 14228 * Number of times startCopy() has been attempted and had a non-fatal 14229 * error. 14230 */ 14231 private int mRetries = 0; 14232 14233 /** User handle for the user requesting the information or installation. */ 14234 private final UserHandle mUser; 14235 String traceMethod; 14236 int traceCookie; 14237 14238 HandlerParams(UserHandle user) { 14239 mUser = user; 14240 } 14241 14242 UserHandle getUser() { 14243 return mUser; 14244 } 14245 14246 HandlerParams setTraceMethod(String traceMethod) { 14247 this.traceMethod = traceMethod; 14248 return this; 14249 } 14250 14251 HandlerParams setTraceCookie(int traceCookie) { 14252 this.traceCookie = traceCookie; 14253 return this; 14254 } 14255 14256 final boolean startCopy() { 14257 boolean res; 14258 try { 14259 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14260 14261 if (++mRetries > MAX_RETRIES) { 14262 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14263 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14264 handleServiceError(); 14265 return false; 14266 } else { 14267 handleStartCopy(); 14268 res = true; 14269 } 14270 } catch (RemoteException e) { 14271 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14272 mHandler.sendEmptyMessage(MCS_RECONNECT); 14273 res = false; 14274 } 14275 handleReturnCode(); 14276 return res; 14277 } 14278 14279 final void serviceError() { 14280 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14281 handleServiceError(); 14282 handleReturnCode(); 14283 } 14284 14285 abstract void handleStartCopy() throws RemoteException; 14286 abstract void handleServiceError(); 14287 abstract void handleReturnCode(); 14288 } 14289 14290 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14291 for (File path : paths) { 14292 try { 14293 mcs.clearDirectory(path.getAbsolutePath()); 14294 } catch (RemoteException e) { 14295 } 14296 } 14297 } 14298 14299 static class OriginInfo { 14300 /** 14301 * Location where install is coming from, before it has been 14302 * copied/renamed into place. This could be a single monolithic APK 14303 * file, or a cluster directory. This location may be untrusted. 14304 */ 14305 final File file; 14306 final String cid; 14307 14308 /** 14309 * Flag indicating that {@link #file} or {@link #cid} has already been 14310 * staged, meaning downstream users don't need to defensively copy the 14311 * contents. 14312 */ 14313 final boolean staged; 14314 14315 /** 14316 * Flag indicating that {@link #file} or {@link #cid} is an already 14317 * installed app that is being moved. 14318 */ 14319 final boolean existing; 14320 14321 final String resolvedPath; 14322 final File resolvedFile; 14323 14324 static OriginInfo fromNothing() { 14325 return new OriginInfo(null, null, false, false); 14326 } 14327 14328 static OriginInfo fromUntrustedFile(File file) { 14329 return new OriginInfo(file, null, false, false); 14330 } 14331 14332 static OriginInfo fromExistingFile(File file) { 14333 return new OriginInfo(file, null, false, true); 14334 } 14335 14336 static OriginInfo fromStagedFile(File file) { 14337 return new OriginInfo(file, null, true, false); 14338 } 14339 14340 static OriginInfo fromStagedContainer(String cid) { 14341 return new OriginInfo(null, cid, true, false); 14342 } 14343 14344 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 14345 this.file = file; 14346 this.cid = cid; 14347 this.staged = staged; 14348 this.existing = existing; 14349 14350 if (cid != null) { 14351 resolvedPath = PackageHelper.getSdDir(cid); 14352 resolvedFile = new File(resolvedPath); 14353 } else if (file != null) { 14354 resolvedPath = file.getAbsolutePath(); 14355 resolvedFile = file; 14356 } else { 14357 resolvedPath = null; 14358 resolvedFile = null; 14359 } 14360 } 14361 } 14362 14363 static class MoveInfo { 14364 final int moveId; 14365 final String fromUuid; 14366 final String toUuid; 14367 final String packageName; 14368 final String dataAppName; 14369 final int appId; 14370 final String seinfo; 14371 final int targetSdkVersion; 14372 14373 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14374 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14375 this.moveId = moveId; 14376 this.fromUuid = fromUuid; 14377 this.toUuid = toUuid; 14378 this.packageName = packageName; 14379 this.dataAppName = dataAppName; 14380 this.appId = appId; 14381 this.seinfo = seinfo; 14382 this.targetSdkVersion = targetSdkVersion; 14383 } 14384 } 14385 14386 static class VerificationInfo { 14387 /** A constant used to indicate that a uid value is not present. */ 14388 public static final int NO_UID = -1; 14389 14390 /** URI referencing where the package was downloaded from. */ 14391 final Uri originatingUri; 14392 14393 /** HTTP referrer URI associated with the originatingURI. */ 14394 final Uri referrer; 14395 14396 /** UID of the application that the install request originated from. */ 14397 final int originatingUid; 14398 14399 /** UID of application requesting the install */ 14400 final int installerUid; 14401 14402 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14403 this.originatingUri = originatingUri; 14404 this.referrer = referrer; 14405 this.originatingUid = originatingUid; 14406 this.installerUid = installerUid; 14407 } 14408 } 14409 14410 class InstallParams extends HandlerParams { 14411 final OriginInfo origin; 14412 final MoveInfo move; 14413 final IPackageInstallObserver2 observer; 14414 int installFlags; 14415 final String installerPackageName; 14416 final String volumeUuid; 14417 private InstallArgs mArgs; 14418 private int mRet; 14419 final String packageAbiOverride; 14420 final String[] grantedRuntimePermissions; 14421 final VerificationInfo verificationInfo; 14422 final Certificate[][] certificates; 14423 final int installReason; 14424 14425 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14426 int installFlags, String installerPackageName, String volumeUuid, 14427 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14428 String[] grantedPermissions, Certificate[][] certificates, int installReason) { 14429 super(user); 14430 this.origin = origin; 14431 this.move = move; 14432 this.observer = observer; 14433 this.installFlags = installFlags; 14434 this.installerPackageName = installerPackageName; 14435 this.volumeUuid = volumeUuid; 14436 this.verificationInfo = verificationInfo; 14437 this.packageAbiOverride = packageAbiOverride; 14438 this.grantedRuntimePermissions = grantedPermissions; 14439 this.certificates = certificates; 14440 this.installReason = installReason; 14441 } 14442 14443 @Override 14444 public String toString() { 14445 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14446 + " file=" + origin.file + " cid=" + origin.cid + "}"; 14447 } 14448 14449 private int installLocationPolicy(PackageInfoLite pkgLite) { 14450 String packageName = pkgLite.packageName; 14451 int installLocation = pkgLite.installLocation; 14452 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14453 // reader 14454 synchronized (mPackages) { 14455 // Currently installed package which the new package is attempting to replace or 14456 // null if no such package is installed. 14457 PackageParser.Package installedPkg = mPackages.get(packageName); 14458 // Package which currently owns the data which the new package will own if installed. 14459 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14460 // will be null whereas dataOwnerPkg will contain information about the package 14461 // which was uninstalled while keeping its data. 14462 PackageParser.Package dataOwnerPkg = installedPkg; 14463 if (dataOwnerPkg == null) { 14464 PackageSetting ps = mSettings.mPackages.get(packageName); 14465 if (ps != null) { 14466 dataOwnerPkg = ps.pkg; 14467 } 14468 } 14469 14470 if (dataOwnerPkg != null) { 14471 // If installed, the package will get access to data left on the device by its 14472 // predecessor. As a security measure, this is permited only if this is not a 14473 // version downgrade or if the predecessor package is marked as debuggable and 14474 // a downgrade is explicitly requested. 14475 // 14476 // On debuggable platform builds, downgrades are permitted even for 14477 // non-debuggable packages to make testing easier. Debuggable platform builds do 14478 // not offer security guarantees and thus it's OK to disable some security 14479 // mechanisms to make debugging/testing easier on those builds. However, even on 14480 // debuggable builds downgrades of packages are permitted only if requested via 14481 // installFlags. This is because we aim to keep the behavior of debuggable 14482 // platform builds as close as possible to the behavior of non-debuggable 14483 // platform builds. 14484 final boolean downgradeRequested = 14485 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14486 final boolean packageDebuggable = 14487 (dataOwnerPkg.applicationInfo.flags 14488 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14489 final boolean downgradePermitted = 14490 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14491 if (!downgradePermitted) { 14492 try { 14493 checkDowngrade(dataOwnerPkg, pkgLite); 14494 } catch (PackageManagerException e) { 14495 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14496 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14497 } 14498 } 14499 } 14500 14501 if (installedPkg != null) { 14502 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14503 // Check for updated system application. 14504 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14505 if (onSd) { 14506 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14507 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14508 } 14509 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14510 } else { 14511 if (onSd) { 14512 // Install flag overrides everything. 14513 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14514 } 14515 // If current upgrade specifies particular preference 14516 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14517 // Application explicitly specified internal. 14518 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14519 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14520 // App explictly prefers external. Let policy decide 14521 } else { 14522 // Prefer previous location 14523 if (isExternal(installedPkg)) { 14524 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14525 } 14526 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14527 } 14528 } 14529 } else { 14530 // Invalid install. Return error code 14531 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14532 } 14533 } 14534 } 14535 // All the special cases have been taken care of. 14536 // Return result based on recommended install location. 14537 if (onSd) { 14538 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14539 } 14540 return pkgLite.recommendedInstallLocation; 14541 } 14542 14543 /* 14544 * Invoke remote method to get package information and install 14545 * location values. Override install location based on default 14546 * policy if needed and then create install arguments based 14547 * on the install location. 14548 */ 14549 public void handleStartCopy() throws RemoteException { 14550 int ret = PackageManager.INSTALL_SUCCEEDED; 14551 14552 // If we're already staged, we've firmly committed to an install location 14553 if (origin.staged) { 14554 if (origin.file != null) { 14555 installFlags |= PackageManager.INSTALL_INTERNAL; 14556 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14557 } else if (origin.cid != null) { 14558 installFlags |= PackageManager.INSTALL_EXTERNAL; 14559 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14560 } else { 14561 throw new IllegalStateException("Invalid stage location"); 14562 } 14563 } 14564 14565 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14566 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14567 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14568 PackageInfoLite pkgLite = null; 14569 14570 if (onInt && onSd) { 14571 // Check if both bits are set. 14572 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14573 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14574 } else if (onSd && ephemeral) { 14575 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14576 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14577 } else { 14578 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14579 packageAbiOverride); 14580 14581 if (DEBUG_EPHEMERAL && ephemeral) { 14582 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14583 } 14584 14585 /* 14586 * If we have too little free space, try to free cache 14587 * before giving up. 14588 */ 14589 if (!origin.staged && pkgLite.recommendedInstallLocation 14590 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14591 // TODO: focus freeing disk space on the target device 14592 final StorageManager storage = StorageManager.from(mContext); 14593 final long lowThreshold = storage.getStorageLowBytes( 14594 Environment.getDataDirectory()); 14595 14596 final long sizeBytes = mContainerService.calculateInstalledSize( 14597 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 14598 14599 try { 14600 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 14601 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14602 installFlags, packageAbiOverride); 14603 } catch (InstallerException e) { 14604 Slog.w(TAG, "Failed to free cache", e); 14605 } 14606 14607 /* 14608 * The cache free must have deleted the file we 14609 * downloaded to install. 14610 * 14611 * TODO: fix the "freeCache" call to not delete 14612 * the file we care about. 14613 */ 14614 if (pkgLite.recommendedInstallLocation 14615 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14616 pkgLite.recommendedInstallLocation 14617 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14618 } 14619 } 14620 } 14621 14622 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14623 int loc = pkgLite.recommendedInstallLocation; 14624 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14625 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14626 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14627 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14628 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14629 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14630 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14631 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14632 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14633 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14634 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14635 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14636 } else { 14637 // Override with defaults if needed. 14638 loc = installLocationPolicy(pkgLite); 14639 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14640 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14641 } else if (!onSd && !onInt) { 14642 // Override install location with flags 14643 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14644 // Set the flag to install on external media. 14645 installFlags |= PackageManager.INSTALL_EXTERNAL; 14646 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14647 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14648 if (DEBUG_EPHEMERAL) { 14649 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14650 } 14651 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14652 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14653 |PackageManager.INSTALL_INTERNAL); 14654 } else { 14655 // Make sure the flag for installing on external 14656 // media is unset 14657 installFlags |= PackageManager.INSTALL_INTERNAL; 14658 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14659 } 14660 } 14661 } 14662 } 14663 14664 final InstallArgs args = createInstallArgs(this); 14665 mArgs = args; 14666 14667 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14668 // TODO: http://b/22976637 14669 // Apps installed for "all" users use the device owner to verify the app 14670 UserHandle verifierUser = getUser(); 14671 if (verifierUser == UserHandle.ALL) { 14672 verifierUser = UserHandle.SYSTEM; 14673 } 14674 14675 /* 14676 * Determine if we have any installed package verifiers. If we 14677 * do, then we'll defer to them to verify the packages. 14678 */ 14679 final int requiredUid = mRequiredVerifierPackage == null ? -1 14680 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14681 verifierUser.getIdentifier()); 14682 if (!origin.existing && requiredUid != -1 14683 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 14684 final Intent verification = new Intent( 14685 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14686 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14687 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14688 PACKAGE_MIME_TYPE); 14689 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14690 14691 // Query all live verifiers based on current user state 14692 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14693 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 14694 14695 if (DEBUG_VERIFY) { 14696 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14697 + verification.toString() + " with " + pkgLite.verifiers.length 14698 + " optional verifiers"); 14699 } 14700 14701 final int verificationId = mPendingVerificationToken++; 14702 14703 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14704 14705 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14706 installerPackageName); 14707 14708 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14709 installFlags); 14710 14711 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14712 pkgLite.packageName); 14713 14714 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14715 pkgLite.versionCode); 14716 14717 if (verificationInfo != null) { 14718 if (verificationInfo.originatingUri != null) { 14719 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14720 verificationInfo.originatingUri); 14721 } 14722 if (verificationInfo.referrer != null) { 14723 verification.putExtra(Intent.EXTRA_REFERRER, 14724 verificationInfo.referrer); 14725 } 14726 if (verificationInfo.originatingUid >= 0) { 14727 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14728 verificationInfo.originatingUid); 14729 } 14730 if (verificationInfo.installerUid >= 0) { 14731 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14732 verificationInfo.installerUid); 14733 } 14734 } 14735 14736 final PackageVerificationState verificationState = new PackageVerificationState( 14737 requiredUid, args); 14738 14739 mPendingVerification.append(verificationId, verificationState); 14740 14741 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14742 receivers, verificationState); 14743 14744 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14745 final long idleDuration = getVerificationTimeout(); 14746 14747 /* 14748 * If any sufficient verifiers were listed in the package 14749 * manifest, attempt to ask them. 14750 */ 14751 if (sufficientVerifiers != null) { 14752 final int N = sufficientVerifiers.size(); 14753 if (N == 0) { 14754 Slog.i(TAG, "Additional verifiers required, but none installed."); 14755 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14756 } else { 14757 for (int i = 0; i < N; i++) { 14758 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14759 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14760 verifierComponent.getPackageName(), idleDuration, 14761 verifierUser.getIdentifier(), false, "package verifier"); 14762 14763 final Intent sufficientIntent = new Intent(verification); 14764 sufficientIntent.setComponent(verifierComponent); 14765 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14766 } 14767 } 14768 } 14769 14770 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14771 mRequiredVerifierPackage, receivers); 14772 if (ret == PackageManager.INSTALL_SUCCEEDED 14773 && mRequiredVerifierPackage != null) { 14774 Trace.asyncTraceBegin( 14775 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14776 /* 14777 * Send the intent to the required verification agent, 14778 * but only start the verification timeout after the 14779 * target BroadcastReceivers have run. 14780 */ 14781 verification.setComponent(requiredVerifierComponent); 14782 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14783 mRequiredVerifierPackage, idleDuration, 14784 verifierUser.getIdentifier(), false, "package verifier"); 14785 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14786 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14787 new BroadcastReceiver() { 14788 @Override 14789 public void onReceive(Context context, Intent intent) { 14790 final Message msg = mHandler 14791 .obtainMessage(CHECK_PENDING_VERIFICATION); 14792 msg.arg1 = verificationId; 14793 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14794 } 14795 }, null, 0, null, null); 14796 14797 /* 14798 * We don't want the copy to proceed until verification 14799 * succeeds, so null out this field. 14800 */ 14801 mArgs = null; 14802 } 14803 } else { 14804 /* 14805 * No package verification is enabled, so immediately start 14806 * the remote call to initiate copy using temporary file. 14807 */ 14808 ret = args.copyApk(mContainerService, true); 14809 } 14810 } 14811 14812 mRet = ret; 14813 } 14814 14815 @Override 14816 void handleReturnCode() { 14817 // If mArgs is null, then MCS couldn't be reached. When it 14818 // reconnects, it will try again to install. At that point, this 14819 // will succeed. 14820 if (mArgs != null) { 14821 processPendingInstall(mArgs, mRet); 14822 } 14823 } 14824 14825 @Override 14826 void handleServiceError() { 14827 mArgs = createInstallArgs(this); 14828 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14829 } 14830 14831 public boolean isForwardLocked() { 14832 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14833 } 14834 } 14835 14836 /** 14837 * Used during creation of InstallArgs 14838 * 14839 * @param installFlags package installation flags 14840 * @return true if should be installed on external storage 14841 */ 14842 private static boolean installOnExternalAsec(int installFlags) { 14843 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 14844 return false; 14845 } 14846 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 14847 return true; 14848 } 14849 return false; 14850 } 14851 14852 /** 14853 * Used during creation of InstallArgs 14854 * 14855 * @param installFlags package installation flags 14856 * @return true if should be installed as forward locked 14857 */ 14858 private static boolean installForwardLocked(int installFlags) { 14859 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14860 } 14861 14862 private InstallArgs createInstallArgs(InstallParams params) { 14863 if (params.move != null) { 14864 return new MoveInstallArgs(params); 14865 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 14866 return new AsecInstallArgs(params); 14867 } else { 14868 return new FileInstallArgs(params); 14869 } 14870 } 14871 14872 /** 14873 * Create args that describe an existing installed package. Typically used 14874 * when cleaning up old installs, or used as a move source. 14875 */ 14876 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 14877 String resourcePath, String[] instructionSets) { 14878 final boolean isInAsec; 14879 if (installOnExternalAsec(installFlags)) { 14880 /* Apps on SD card are always in ASEC containers. */ 14881 isInAsec = true; 14882 } else if (installForwardLocked(installFlags) 14883 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 14884 /* 14885 * Forward-locked apps are only in ASEC containers if they're the 14886 * new style 14887 */ 14888 isInAsec = true; 14889 } else { 14890 isInAsec = false; 14891 } 14892 14893 if (isInAsec) { 14894 return new AsecInstallArgs(codePath, instructionSets, 14895 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 14896 } else { 14897 return new FileInstallArgs(codePath, resourcePath, instructionSets); 14898 } 14899 } 14900 14901 static abstract class InstallArgs { 14902 /** @see InstallParams#origin */ 14903 final OriginInfo origin; 14904 /** @see InstallParams#move */ 14905 final MoveInfo move; 14906 14907 final IPackageInstallObserver2 observer; 14908 // Always refers to PackageManager flags only 14909 final int installFlags; 14910 final String installerPackageName; 14911 final String volumeUuid; 14912 final UserHandle user; 14913 final String abiOverride; 14914 final String[] installGrantPermissions; 14915 /** If non-null, drop an async trace when the install completes */ 14916 final String traceMethod; 14917 final int traceCookie; 14918 final Certificate[][] certificates; 14919 final int installReason; 14920 14921 // The list of instruction sets supported by this app. This is currently 14922 // only used during the rmdex() phase to clean up resources. We can get rid of this 14923 // if we move dex files under the common app path. 14924 /* nullable */ String[] instructionSets; 14925 14926 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14927 int installFlags, String installerPackageName, String volumeUuid, 14928 UserHandle user, String[] instructionSets, 14929 String abiOverride, String[] installGrantPermissions, 14930 String traceMethod, int traceCookie, Certificate[][] certificates, 14931 int installReason) { 14932 this.origin = origin; 14933 this.move = move; 14934 this.installFlags = installFlags; 14935 this.observer = observer; 14936 this.installerPackageName = installerPackageName; 14937 this.volumeUuid = volumeUuid; 14938 this.user = user; 14939 this.instructionSets = instructionSets; 14940 this.abiOverride = abiOverride; 14941 this.installGrantPermissions = installGrantPermissions; 14942 this.traceMethod = traceMethod; 14943 this.traceCookie = traceCookie; 14944 this.certificates = certificates; 14945 this.installReason = installReason; 14946 } 14947 14948 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 14949 abstract int doPreInstall(int status); 14950 14951 /** 14952 * Rename package into final resting place. All paths on the given 14953 * scanned package should be updated to reflect the rename. 14954 */ 14955 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 14956 abstract int doPostInstall(int status, int uid); 14957 14958 /** @see PackageSettingBase#codePathString */ 14959 abstract String getCodePath(); 14960 /** @see PackageSettingBase#resourcePathString */ 14961 abstract String getResourcePath(); 14962 14963 // Need installer lock especially for dex file removal. 14964 abstract void cleanUpResourcesLI(); 14965 abstract boolean doPostDeleteLI(boolean delete); 14966 14967 /** 14968 * Called before the source arguments are copied. This is used mostly 14969 * for MoveParams when it needs to read the source file to put it in the 14970 * destination. 14971 */ 14972 int doPreCopy() { 14973 return PackageManager.INSTALL_SUCCEEDED; 14974 } 14975 14976 /** 14977 * Called after the source arguments are copied. This is used mostly for 14978 * MoveParams when it needs to read the source file to put it in the 14979 * destination. 14980 */ 14981 int doPostCopy(int uid) { 14982 return PackageManager.INSTALL_SUCCEEDED; 14983 } 14984 14985 protected boolean isFwdLocked() { 14986 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 14987 } 14988 14989 protected boolean isExternalAsec() { 14990 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14991 } 14992 14993 protected boolean isEphemeral() { 14994 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14995 } 14996 14997 UserHandle getUser() { 14998 return user; 14999 } 15000 } 15001 15002 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15003 if (!allCodePaths.isEmpty()) { 15004 if (instructionSets == null) { 15005 throw new IllegalStateException("instructionSet == null"); 15006 } 15007 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15008 for (String codePath : allCodePaths) { 15009 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15010 try { 15011 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15012 } catch (InstallerException ignored) { 15013 } 15014 } 15015 } 15016 } 15017 } 15018 15019 /** 15020 * Logic to handle installation of non-ASEC applications, including copying 15021 * and renaming logic. 15022 */ 15023 class FileInstallArgs extends InstallArgs { 15024 private File codeFile; 15025 private File resourceFile; 15026 15027 // Example topology: 15028 // /data/app/com.example/base.apk 15029 // /data/app/com.example/split_foo.apk 15030 // /data/app/com.example/lib/arm/libfoo.so 15031 // /data/app/com.example/lib/arm64/libfoo.so 15032 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15033 15034 /** New install */ 15035 FileInstallArgs(InstallParams params) { 15036 super(params.origin, params.move, params.observer, params.installFlags, 15037 params.installerPackageName, params.volumeUuid, 15038 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15039 params.grantedRuntimePermissions, 15040 params.traceMethod, params.traceCookie, params.certificates, 15041 params.installReason); 15042 if (isFwdLocked()) { 15043 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15044 } 15045 } 15046 15047 /** Existing install */ 15048 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15049 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15050 null, null, null, 0, null /*certificates*/, 15051 PackageManager.INSTALL_REASON_UNKNOWN); 15052 this.codeFile = (codePath != null) ? new File(codePath) : null; 15053 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15054 } 15055 15056 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15057 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15058 try { 15059 return doCopyApk(imcs, temp); 15060 } finally { 15061 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15062 } 15063 } 15064 15065 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15066 if (origin.staged) { 15067 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15068 codeFile = origin.file; 15069 resourceFile = origin.file; 15070 return PackageManager.INSTALL_SUCCEEDED; 15071 } 15072 15073 try { 15074 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15075 final File tempDir = 15076 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15077 codeFile = tempDir; 15078 resourceFile = tempDir; 15079 } catch (IOException e) { 15080 Slog.w(TAG, "Failed to create copy file: " + e); 15081 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15082 } 15083 15084 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15085 @Override 15086 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15087 if (!FileUtils.isValidExtFilename(name)) { 15088 throw new IllegalArgumentException("Invalid filename: " + name); 15089 } 15090 try { 15091 final File file = new File(codeFile, name); 15092 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15093 O_RDWR | O_CREAT, 0644); 15094 Os.chmod(file.getAbsolutePath(), 0644); 15095 return new ParcelFileDescriptor(fd); 15096 } catch (ErrnoException e) { 15097 throw new RemoteException("Failed to open: " + e.getMessage()); 15098 } 15099 } 15100 }; 15101 15102 int ret = PackageManager.INSTALL_SUCCEEDED; 15103 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15104 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15105 Slog.e(TAG, "Failed to copy package"); 15106 return ret; 15107 } 15108 15109 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15110 NativeLibraryHelper.Handle handle = null; 15111 try { 15112 handle = NativeLibraryHelper.Handle.create(codeFile); 15113 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15114 abiOverride); 15115 } catch (IOException e) { 15116 Slog.e(TAG, "Copying native libraries failed", e); 15117 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15118 } finally { 15119 IoUtils.closeQuietly(handle); 15120 } 15121 15122 return ret; 15123 } 15124 15125 int doPreInstall(int status) { 15126 if (status != PackageManager.INSTALL_SUCCEEDED) { 15127 cleanUp(); 15128 } 15129 return status; 15130 } 15131 15132 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15133 if (status != PackageManager.INSTALL_SUCCEEDED) { 15134 cleanUp(); 15135 return false; 15136 } 15137 15138 final File targetDir = codeFile.getParentFile(); 15139 final File beforeCodeFile = codeFile; 15140 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15141 15142 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15143 try { 15144 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15145 } catch (ErrnoException e) { 15146 Slog.w(TAG, "Failed to rename", e); 15147 return false; 15148 } 15149 15150 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15151 Slog.w(TAG, "Failed to restorecon"); 15152 return false; 15153 } 15154 15155 // Reflect the rename internally 15156 codeFile = afterCodeFile; 15157 resourceFile = afterCodeFile; 15158 15159 // Reflect the rename in scanned details 15160 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15161 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15162 afterCodeFile, pkg.baseCodePath)); 15163 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15164 afterCodeFile, pkg.splitCodePaths)); 15165 15166 // Reflect the rename in app info 15167 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15168 pkg.setApplicationInfoCodePath(pkg.codePath); 15169 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15170 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15171 pkg.setApplicationInfoResourcePath(pkg.codePath); 15172 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15173 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15174 15175 return true; 15176 } 15177 15178 int doPostInstall(int status, int uid) { 15179 if (status != PackageManager.INSTALL_SUCCEEDED) { 15180 cleanUp(); 15181 } 15182 return status; 15183 } 15184 15185 @Override 15186 String getCodePath() { 15187 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15188 } 15189 15190 @Override 15191 String getResourcePath() { 15192 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15193 } 15194 15195 private boolean cleanUp() { 15196 if (codeFile == null || !codeFile.exists()) { 15197 return false; 15198 } 15199 15200 removeCodePathLI(codeFile); 15201 15202 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15203 resourceFile.delete(); 15204 } 15205 15206 return true; 15207 } 15208 15209 void cleanUpResourcesLI() { 15210 // Try enumerating all code paths before deleting 15211 List<String> allCodePaths = Collections.EMPTY_LIST; 15212 if (codeFile != null && codeFile.exists()) { 15213 try { 15214 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15215 allCodePaths = pkg.getAllCodePaths(); 15216 } catch (PackageParserException e) { 15217 // Ignored; we tried our best 15218 } 15219 } 15220 15221 cleanUp(); 15222 removeDexFiles(allCodePaths, instructionSets); 15223 } 15224 15225 boolean doPostDeleteLI(boolean delete) { 15226 // XXX err, shouldn't we respect the delete flag? 15227 cleanUpResourcesLI(); 15228 return true; 15229 } 15230 } 15231 15232 private boolean isAsecExternal(String cid) { 15233 final String asecPath = PackageHelper.getSdFilesystem(cid); 15234 return !asecPath.startsWith(mAsecInternalPath); 15235 } 15236 15237 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15238 PackageManagerException { 15239 if (copyRet < 0) { 15240 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15241 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15242 throw new PackageManagerException(copyRet, message); 15243 } 15244 } 15245 } 15246 15247 /** 15248 * Extract the StorageManagerService "container ID" from the full code path of an 15249 * .apk. 15250 */ 15251 static String cidFromCodePath(String fullCodePath) { 15252 int eidx = fullCodePath.lastIndexOf("/"); 15253 String subStr1 = fullCodePath.substring(0, eidx); 15254 int sidx = subStr1.lastIndexOf("/"); 15255 return subStr1.substring(sidx+1, eidx); 15256 } 15257 15258 /** 15259 * Logic to handle installation of ASEC applications, including copying and 15260 * renaming logic. 15261 */ 15262 class AsecInstallArgs extends InstallArgs { 15263 static final String RES_FILE_NAME = "pkg.apk"; 15264 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 15265 15266 String cid; 15267 String packagePath; 15268 String resourcePath; 15269 15270 /** New install */ 15271 AsecInstallArgs(InstallParams params) { 15272 super(params.origin, params.move, params.observer, params.installFlags, 15273 params.installerPackageName, params.volumeUuid, 15274 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15275 params.grantedRuntimePermissions, 15276 params.traceMethod, params.traceCookie, params.certificates, 15277 params.installReason); 15278 } 15279 15280 /** Existing install */ 15281 AsecInstallArgs(String fullCodePath, String[] instructionSets, 15282 boolean isExternal, boolean isForwardLocked) { 15283 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 15284 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15285 instructionSets, null, null, null, 0, null /*certificates*/, 15286 PackageManager.INSTALL_REASON_UNKNOWN); 15287 // Hackily pretend we're still looking at a full code path 15288 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 15289 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 15290 } 15291 15292 // Extract cid from fullCodePath 15293 int eidx = fullCodePath.lastIndexOf("/"); 15294 String subStr1 = fullCodePath.substring(0, eidx); 15295 int sidx = subStr1.lastIndexOf("/"); 15296 cid = subStr1.substring(sidx+1, eidx); 15297 setMountPath(subStr1); 15298 } 15299 15300 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 15301 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 15302 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 15303 instructionSets, null, null, null, 0, null /*certificates*/, 15304 PackageManager.INSTALL_REASON_UNKNOWN); 15305 this.cid = cid; 15306 setMountPath(PackageHelper.getSdDir(cid)); 15307 } 15308 15309 void createCopyFile() { 15310 cid = mInstallerService.allocateExternalStageCidLegacy(); 15311 } 15312 15313 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15314 if (origin.staged && origin.cid != null) { 15315 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 15316 cid = origin.cid; 15317 setMountPath(PackageHelper.getSdDir(cid)); 15318 return PackageManager.INSTALL_SUCCEEDED; 15319 } 15320 15321 if (temp) { 15322 createCopyFile(); 15323 } else { 15324 /* 15325 * Pre-emptively destroy the container since it's destroyed if 15326 * copying fails due to it existing anyway. 15327 */ 15328 PackageHelper.destroySdDir(cid); 15329 } 15330 15331 final String newMountPath = imcs.copyPackageToContainer( 15332 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 15333 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 15334 15335 if (newMountPath != null) { 15336 setMountPath(newMountPath); 15337 return PackageManager.INSTALL_SUCCEEDED; 15338 } else { 15339 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15340 } 15341 } 15342 15343 @Override 15344 String getCodePath() { 15345 return packagePath; 15346 } 15347 15348 @Override 15349 String getResourcePath() { 15350 return resourcePath; 15351 } 15352 15353 int doPreInstall(int status) { 15354 if (status != PackageManager.INSTALL_SUCCEEDED) { 15355 // Destroy container 15356 PackageHelper.destroySdDir(cid); 15357 } else { 15358 boolean mounted = PackageHelper.isContainerMounted(cid); 15359 if (!mounted) { 15360 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 15361 Process.SYSTEM_UID); 15362 if (newMountPath != null) { 15363 setMountPath(newMountPath); 15364 } else { 15365 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15366 } 15367 } 15368 } 15369 return status; 15370 } 15371 15372 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15373 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 15374 String newMountPath = null; 15375 if (PackageHelper.isContainerMounted(cid)) { 15376 // Unmount the container 15377 if (!PackageHelper.unMountSdDir(cid)) { 15378 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 15379 return false; 15380 } 15381 } 15382 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15383 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 15384 " which might be stale. Will try to clean up."); 15385 // Clean up the stale container and proceed to recreate. 15386 if (!PackageHelper.destroySdDir(newCacheId)) { 15387 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 15388 return false; 15389 } 15390 // Successfully cleaned up stale container. Try to rename again. 15391 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 15392 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 15393 + " inspite of cleaning it up."); 15394 return false; 15395 } 15396 } 15397 if (!PackageHelper.isContainerMounted(newCacheId)) { 15398 Slog.w(TAG, "Mounting container " + newCacheId); 15399 newMountPath = PackageHelper.mountSdDir(newCacheId, 15400 getEncryptKey(), Process.SYSTEM_UID); 15401 } else { 15402 newMountPath = PackageHelper.getSdDir(newCacheId); 15403 } 15404 if (newMountPath == null) { 15405 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 15406 return false; 15407 } 15408 Log.i(TAG, "Succesfully renamed " + cid + 15409 " to " + newCacheId + 15410 " at new path: " + newMountPath); 15411 cid = newCacheId; 15412 15413 final File beforeCodeFile = new File(packagePath); 15414 setMountPath(newMountPath); 15415 final File afterCodeFile = new File(packagePath); 15416 15417 // Reflect the rename in scanned details 15418 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 15419 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15420 afterCodeFile, pkg.baseCodePath)); 15421 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15422 afterCodeFile, pkg.splitCodePaths)); 15423 15424 // Reflect the rename in app info 15425 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15426 pkg.setApplicationInfoCodePath(pkg.codePath); 15427 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15428 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15429 pkg.setApplicationInfoResourcePath(pkg.codePath); 15430 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15431 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15432 15433 return true; 15434 } 15435 15436 private void setMountPath(String mountPath) { 15437 final File mountFile = new File(mountPath); 15438 15439 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 15440 if (monolithicFile.exists()) { 15441 packagePath = monolithicFile.getAbsolutePath(); 15442 if (isFwdLocked()) { 15443 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 15444 } else { 15445 resourcePath = packagePath; 15446 } 15447 } else { 15448 packagePath = mountFile.getAbsolutePath(); 15449 resourcePath = packagePath; 15450 } 15451 } 15452 15453 int doPostInstall(int status, int uid) { 15454 if (status != PackageManager.INSTALL_SUCCEEDED) { 15455 cleanUp(); 15456 } else { 15457 final int groupOwner; 15458 final String protectedFile; 15459 if (isFwdLocked()) { 15460 groupOwner = UserHandle.getSharedAppGid(uid); 15461 protectedFile = RES_FILE_NAME; 15462 } else { 15463 groupOwner = -1; 15464 protectedFile = null; 15465 } 15466 15467 if (uid < Process.FIRST_APPLICATION_UID 15468 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 15469 Slog.e(TAG, "Failed to finalize " + cid); 15470 PackageHelper.destroySdDir(cid); 15471 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15472 } 15473 15474 boolean mounted = PackageHelper.isContainerMounted(cid); 15475 if (!mounted) { 15476 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 15477 } 15478 } 15479 return status; 15480 } 15481 15482 private void cleanUp() { 15483 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 15484 15485 // Destroy secure container 15486 PackageHelper.destroySdDir(cid); 15487 } 15488 15489 private List<String> getAllCodePaths() { 15490 final File codeFile = new File(getCodePath()); 15491 if (codeFile != null && codeFile.exists()) { 15492 try { 15493 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15494 return pkg.getAllCodePaths(); 15495 } catch (PackageParserException e) { 15496 // Ignored; we tried our best 15497 } 15498 } 15499 return Collections.EMPTY_LIST; 15500 } 15501 15502 void cleanUpResourcesLI() { 15503 // Enumerate all code paths before deleting 15504 cleanUpResourcesLI(getAllCodePaths()); 15505 } 15506 15507 private void cleanUpResourcesLI(List<String> allCodePaths) { 15508 cleanUp(); 15509 removeDexFiles(allCodePaths, instructionSets); 15510 } 15511 15512 String getPackageName() { 15513 return getAsecPackageName(cid); 15514 } 15515 15516 boolean doPostDeleteLI(boolean delete) { 15517 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 15518 final List<String> allCodePaths = getAllCodePaths(); 15519 boolean mounted = PackageHelper.isContainerMounted(cid); 15520 if (mounted) { 15521 // Unmount first 15522 if (PackageHelper.unMountSdDir(cid)) { 15523 mounted = false; 15524 } 15525 } 15526 if (!mounted && delete) { 15527 cleanUpResourcesLI(allCodePaths); 15528 } 15529 return !mounted; 15530 } 15531 15532 @Override 15533 int doPreCopy() { 15534 if (isFwdLocked()) { 15535 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 15536 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 15537 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15538 } 15539 } 15540 15541 return PackageManager.INSTALL_SUCCEEDED; 15542 } 15543 15544 @Override 15545 int doPostCopy(int uid) { 15546 if (isFwdLocked()) { 15547 if (uid < Process.FIRST_APPLICATION_UID 15548 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 15549 RES_FILE_NAME)) { 15550 Slog.e(TAG, "Failed to finalize " + cid); 15551 PackageHelper.destroySdDir(cid); 15552 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 15553 } 15554 } 15555 15556 return PackageManager.INSTALL_SUCCEEDED; 15557 } 15558 } 15559 15560 /** 15561 * Logic to handle movement of existing installed applications. 15562 */ 15563 class MoveInstallArgs extends InstallArgs { 15564 private File codeFile; 15565 private File resourceFile; 15566 15567 /** New install */ 15568 MoveInstallArgs(InstallParams params) { 15569 super(params.origin, params.move, params.observer, params.installFlags, 15570 params.installerPackageName, params.volumeUuid, 15571 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15572 params.grantedRuntimePermissions, 15573 params.traceMethod, params.traceCookie, params.certificates, 15574 params.installReason); 15575 } 15576 15577 int copyApk(IMediaContainerService imcs, boolean temp) { 15578 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15579 + move.fromUuid + " to " + move.toUuid); 15580 synchronized (mInstaller) { 15581 try { 15582 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15583 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15584 } catch (InstallerException e) { 15585 Slog.w(TAG, "Failed to move app", e); 15586 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15587 } 15588 } 15589 15590 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15591 resourceFile = codeFile; 15592 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15593 15594 return PackageManager.INSTALL_SUCCEEDED; 15595 } 15596 15597 int doPreInstall(int status) { 15598 if (status != PackageManager.INSTALL_SUCCEEDED) { 15599 cleanUp(move.toUuid); 15600 } 15601 return status; 15602 } 15603 15604 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15605 if (status != PackageManager.INSTALL_SUCCEEDED) { 15606 cleanUp(move.toUuid); 15607 return false; 15608 } 15609 15610 // Reflect the move in app info 15611 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15612 pkg.setApplicationInfoCodePath(pkg.codePath); 15613 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15614 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15615 pkg.setApplicationInfoResourcePath(pkg.codePath); 15616 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15617 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15618 15619 return true; 15620 } 15621 15622 int doPostInstall(int status, int uid) { 15623 if (status == PackageManager.INSTALL_SUCCEEDED) { 15624 cleanUp(move.fromUuid); 15625 } else { 15626 cleanUp(move.toUuid); 15627 } 15628 return status; 15629 } 15630 15631 @Override 15632 String getCodePath() { 15633 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15634 } 15635 15636 @Override 15637 String getResourcePath() { 15638 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15639 } 15640 15641 private boolean cleanUp(String volumeUuid) { 15642 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15643 move.dataAppName); 15644 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15645 final int[] userIds = sUserManager.getUserIds(); 15646 synchronized (mInstallLock) { 15647 // Clean up both app data and code 15648 // All package moves are frozen until finished 15649 for (int userId : userIds) { 15650 try { 15651 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15652 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15653 } catch (InstallerException e) { 15654 Slog.w(TAG, String.valueOf(e)); 15655 } 15656 } 15657 removeCodePathLI(codeFile); 15658 } 15659 return true; 15660 } 15661 15662 void cleanUpResourcesLI() { 15663 throw new UnsupportedOperationException(); 15664 } 15665 15666 boolean doPostDeleteLI(boolean delete) { 15667 throw new UnsupportedOperationException(); 15668 } 15669 } 15670 15671 static String getAsecPackageName(String packageCid) { 15672 int idx = packageCid.lastIndexOf("-"); 15673 if (idx == -1) { 15674 return packageCid; 15675 } 15676 return packageCid.substring(0, idx); 15677 } 15678 15679 // Utility method used to create code paths based on package name and available index. 15680 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15681 String idxStr = ""; 15682 int idx = 1; 15683 // Fall back to default value of idx=1 if prefix is not 15684 // part of oldCodePath 15685 if (oldCodePath != null) { 15686 String subStr = oldCodePath; 15687 // Drop the suffix right away 15688 if (suffix != null && subStr.endsWith(suffix)) { 15689 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15690 } 15691 // If oldCodePath already contains prefix find out the 15692 // ending index to either increment or decrement. 15693 int sidx = subStr.lastIndexOf(prefix); 15694 if (sidx != -1) { 15695 subStr = subStr.substring(sidx + prefix.length()); 15696 if (subStr != null) { 15697 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15698 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15699 } 15700 try { 15701 idx = Integer.parseInt(subStr); 15702 if (idx <= 1) { 15703 idx++; 15704 } else { 15705 idx--; 15706 } 15707 } catch(NumberFormatException e) { 15708 } 15709 } 15710 } 15711 } 15712 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15713 return prefix + idxStr; 15714 } 15715 15716 private File getNextCodePath(File targetDir, String packageName) { 15717 File result; 15718 SecureRandom random = new SecureRandom(); 15719 byte[] bytes = new byte[16]; 15720 do { 15721 random.nextBytes(bytes); 15722 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15723 result = new File(targetDir, packageName + "-" + suffix); 15724 } while (result.exists()); 15725 return result; 15726 } 15727 15728 // Utility method that returns the relative package path with respect 15729 // to the installation directory. Like say for /data/data/com.test-1.apk 15730 // string com.test-1 is returned. 15731 static String deriveCodePathName(String codePath) { 15732 if (codePath == null) { 15733 return null; 15734 } 15735 final File codeFile = new File(codePath); 15736 final String name = codeFile.getName(); 15737 if (codeFile.isDirectory()) { 15738 return name; 15739 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15740 final int lastDot = name.lastIndexOf('.'); 15741 return name.substring(0, lastDot); 15742 } else { 15743 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15744 return null; 15745 } 15746 } 15747 15748 static class PackageInstalledInfo { 15749 String name; 15750 int uid; 15751 // The set of users that originally had this package installed. 15752 int[] origUsers; 15753 // The set of users that now have this package installed. 15754 int[] newUsers; 15755 PackageParser.Package pkg; 15756 int returnCode; 15757 String returnMsg; 15758 PackageRemovedInfo removedInfo; 15759 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15760 15761 public void setError(int code, String msg) { 15762 setReturnCode(code); 15763 setReturnMessage(msg); 15764 Slog.w(TAG, msg); 15765 } 15766 15767 public void setError(String msg, PackageParserException e) { 15768 setReturnCode(e.error); 15769 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15770 Slog.w(TAG, msg, e); 15771 } 15772 15773 public void setError(String msg, PackageManagerException e) { 15774 returnCode = e.error; 15775 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15776 Slog.w(TAG, msg, e); 15777 } 15778 15779 public void setReturnCode(int returnCode) { 15780 this.returnCode = returnCode; 15781 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15782 for (int i = 0; i < childCount; i++) { 15783 addedChildPackages.valueAt(i).returnCode = returnCode; 15784 } 15785 } 15786 15787 private void setReturnMessage(String returnMsg) { 15788 this.returnMsg = returnMsg; 15789 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15790 for (int i = 0; i < childCount; i++) { 15791 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15792 } 15793 } 15794 15795 // In some error cases we want to convey more info back to the observer 15796 String origPackage; 15797 String origPermission; 15798 } 15799 15800 /* 15801 * Install a non-existing package. 15802 */ 15803 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 15804 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 15805 PackageInstalledInfo res, int installReason) { 15806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15807 15808 // Remember this for later, in case we need to rollback this install 15809 String pkgName = pkg.packageName; 15810 15811 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15812 15813 synchronized(mPackages) { 15814 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15815 if (renamedPackage != null) { 15816 // A package with the same name is already installed, though 15817 // it has been renamed to an older name. The package we 15818 // are trying to install should be installed as an update to 15819 // the existing one, but that has not been requested, so bail. 15820 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15821 + " without first uninstalling package running as " 15822 + renamedPackage); 15823 return; 15824 } 15825 if (mPackages.containsKey(pkgName)) { 15826 // Don't allow installation over an existing package with the same name. 15827 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15828 + " without first uninstalling."); 15829 return; 15830 } 15831 } 15832 15833 try { 15834 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 15835 System.currentTimeMillis(), user); 15836 15837 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15838 15839 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15840 prepareAppDataAfterInstallLIF(newPackage); 15841 15842 } else { 15843 // Remove package from internal structures, but keep around any 15844 // data that might have already existed 15845 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15846 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15847 } 15848 } catch (PackageManagerException e) { 15849 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15850 } 15851 15852 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15853 } 15854 15855 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 15856 // Can't rotate keys during boot or if sharedUser. 15857 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 15858 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 15859 return false; 15860 } 15861 // app is using upgradeKeySets; make sure all are valid 15862 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15863 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 15864 for (int i = 0; i < upgradeKeySets.length; i++) { 15865 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 15866 Slog.wtf(TAG, "Package " 15867 + (oldPs.name != null ? oldPs.name : "<null>") 15868 + " contains upgrade-key-set reference to unknown key-set: " 15869 + upgradeKeySets[i] 15870 + " reverting to signatures check."); 15871 return false; 15872 } 15873 } 15874 return true; 15875 } 15876 15877 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 15878 // Upgrade keysets are being used. Determine if new package has a superset of the 15879 // required keys. 15880 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 15881 KeySetManagerService ksms = mSettings.mKeySetManagerService; 15882 for (int i = 0; i < upgradeKeySets.length; i++) { 15883 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 15884 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 15885 return true; 15886 } 15887 } 15888 return false; 15889 } 15890 15891 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15892 try (DigestInputStream digestStream = 15893 new DigestInputStream(new FileInputStream(file), digest)) { 15894 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15895 } 15896 } 15897 15898 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 15899 UserHandle user, String installerPackageName, PackageInstalledInfo res, 15900 int installReason) { 15901 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15902 15903 final PackageParser.Package oldPackage; 15904 final String pkgName = pkg.packageName; 15905 final int[] allUsers; 15906 final int[] installedUsers; 15907 15908 synchronized(mPackages) { 15909 oldPackage = mPackages.get(pkgName); 15910 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15911 15912 // don't allow upgrade to target a release SDK from a pre-release SDK 15913 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15914 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15915 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15916 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15917 if (oldTargetsPreRelease 15918 && !newTargetsPreRelease 15919 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15920 Slog.w(TAG, "Can't install package targeting released sdk"); 15921 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15922 return; 15923 } 15924 15925 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15926 15927 // verify signatures are valid 15928 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15929 if (!checkUpgradeKeySetLP(ps, pkg)) { 15930 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15931 "New package not signed by keys specified by upgrade-keysets: " 15932 + pkgName); 15933 return; 15934 } 15935 } else { 15936 // default to original signature matching 15937 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 15938 != PackageManager.SIGNATURE_MATCH) { 15939 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15940 "New package has a different signature: " + pkgName); 15941 return; 15942 } 15943 } 15944 15945 // don't allow a system upgrade unless the upgrade hash matches 15946 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 15947 byte[] digestBytes = null; 15948 try { 15949 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15950 updateDigest(digest, new File(pkg.baseCodePath)); 15951 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15952 for (String path : pkg.splitCodePaths) { 15953 updateDigest(digest, new File(path)); 15954 } 15955 } 15956 digestBytes = digest.digest(); 15957 } catch (NoSuchAlgorithmException | IOException e) { 15958 res.setError(INSTALL_FAILED_INVALID_APK, 15959 "Could not compute hash: " + pkgName); 15960 return; 15961 } 15962 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15963 res.setError(INSTALL_FAILED_INVALID_APK, 15964 "New package fails restrict-update check: " + pkgName); 15965 return; 15966 } 15967 // retain upgrade restriction 15968 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15969 } 15970 15971 // Check for shared user id changes 15972 String invalidPackageName = 15973 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15974 if (invalidPackageName != null) { 15975 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15976 "Package " + invalidPackageName + " tried to change user " 15977 + oldPackage.mSharedUserId); 15978 return; 15979 } 15980 15981 // In case of rollback, remember per-user/profile install state 15982 allUsers = sUserManager.getUserIds(); 15983 installedUsers = ps.queryInstalledUsers(allUsers, true); 15984 15985 // don't allow an upgrade from full to ephemeral 15986 if (isInstantApp) { 15987 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15988 for (int currentUser : allUsers) { 15989 if (!ps.getInstantApp(currentUser)) { 15990 // can't downgrade from full to instant 15991 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15992 + " for user: " + currentUser); 15993 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15994 return; 15995 } 15996 } 15997 } else if (!ps.getInstantApp(user.getIdentifier())) { 15998 // can't downgrade from full to instant 15999 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16000 + " for user: " + user.getIdentifier()); 16001 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16002 return; 16003 } 16004 } 16005 } 16006 16007 // Update what is removed 16008 res.removedInfo = new PackageRemovedInfo(); 16009 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16010 res.removedInfo.removedPackage = oldPackage.packageName; 16011 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16012 res.removedInfo.isUpdate = true; 16013 res.removedInfo.origUsers = installedUsers; 16014 final PackageSetting ps = mSettings.getPackageLPr(pkgName); 16015 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16016 for (int i = 0; i < installedUsers.length; i++) { 16017 final int userId = installedUsers[i]; 16018 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16019 } 16020 16021 final int childCount = (oldPackage.childPackages != null) 16022 ? oldPackage.childPackages.size() : 0; 16023 for (int i = 0; i < childCount; i++) { 16024 boolean childPackageUpdated = false; 16025 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16026 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16027 if (res.addedChildPackages != null) { 16028 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16029 if (childRes != null) { 16030 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16031 childRes.removedInfo.removedPackage = childPkg.packageName; 16032 childRes.removedInfo.isUpdate = true; 16033 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16034 childPackageUpdated = true; 16035 } 16036 } 16037 if (!childPackageUpdated) { 16038 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 16039 childRemovedRes.removedPackage = childPkg.packageName; 16040 childRemovedRes.isUpdate = false; 16041 childRemovedRes.dataRemoved = true; 16042 synchronized (mPackages) { 16043 if (childPs != null) { 16044 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16045 } 16046 } 16047 if (res.removedInfo.removedChildPackages == null) { 16048 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16049 } 16050 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16051 } 16052 } 16053 16054 boolean sysPkg = (isSystemApp(oldPackage)); 16055 if (sysPkg) { 16056 // Set the system/privileged flags as needed 16057 final boolean privileged = 16058 (oldPackage.applicationInfo.privateFlags 16059 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16060 final int systemPolicyFlags = policyFlags 16061 | PackageParser.PARSE_IS_SYSTEM 16062 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 16063 16064 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 16065 user, allUsers, installerPackageName, res, installReason); 16066 } else { 16067 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 16068 user, allUsers, installerPackageName, res, installReason); 16069 } 16070 } 16071 16072 public List<String> getPreviousCodePaths(String packageName) { 16073 final PackageSetting ps = mSettings.mPackages.get(packageName); 16074 final List<String> result = new ArrayList<String>(); 16075 if (ps != null && ps.oldCodePaths != null) { 16076 result.addAll(ps.oldCodePaths); 16077 } 16078 return result; 16079 } 16080 16081 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16082 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16083 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16084 int installReason) { 16085 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16086 + deletedPackage); 16087 16088 String pkgName = deletedPackage.packageName; 16089 boolean deletedPkg = true; 16090 boolean addedPkg = false; 16091 boolean updatedSettings = false; 16092 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16093 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16094 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16095 16096 final long origUpdateTime = (pkg.mExtras != null) 16097 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16098 16099 // First delete the existing package while retaining the data directory 16100 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16101 res.removedInfo, true, pkg)) { 16102 // If the existing package wasn't successfully deleted 16103 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16104 deletedPkg = false; 16105 } else { 16106 // Successfully deleted the old package; proceed with replace. 16107 16108 // If deleted package lived in a container, give users a chance to 16109 // relinquish resources before killing. 16110 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16111 if (DEBUG_INSTALL) { 16112 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16113 } 16114 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16115 final ArrayList<String> pkgList = new ArrayList<String>(1); 16116 pkgList.add(deletedPackage.applicationInfo.packageName); 16117 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16118 } 16119 16120 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16121 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16122 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16123 16124 try { 16125 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 16126 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16127 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16128 installReason); 16129 16130 // Update the in-memory copy of the previous code paths. 16131 PackageSetting ps = mSettings.mPackages.get(pkgName); 16132 if (!killApp) { 16133 if (ps.oldCodePaths == null) { 16134 ps.oldCodePaths = new ArraySet<>(); 16135 } 16136 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16137 if (deletedPackage.splitCodePaths != null) { 16138 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16139 } 16140 } else { 16141 ps.oldCodePaths = null; 16142 } 16143 if (ps.childPackageNames != null) { 16144 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16145 final String childPkgName = ps.childPackageNames.get(i); 16146 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16147 childPs.oldCodePaths = ps.oldCodePaths; 16148 } 16149 } 16150 // set instant app status, but, only if it's explicitly specified 16151 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16152 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16153 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16154 prepareAppDataAfterInstallLIF(newPackage); 16155 addedPkg = true; 16156 mDexManager.notifyPackageUpdated(newPackage.packageName, 16157 newPackage.baseCodePath, newPackage.splitCodePaths); 16158 } catch (PackageManagerException e) { 16159 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16160 } 16161 } 16162 16163 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16164 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16165 16166 // Revert all internal state mutations and added folders for the failed install 16167 if (addedPkg) { 16168 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16169 res.removedInfo, true, null); 16170 } 16171 16172 // Restore the old package 16173 if (deletedPkg) { 16174 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16175 File restoreFile = new File(deletedPackage.codePath); 16176 // Parse old package 16177 boolean oldExternal = isExternal(deletedPackage); 16178 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16179 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16180 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16181 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16182 try { 16183 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16184 null); 16185 } catch (PackageManagerException e) { 16186 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16187 + e.getMessage()); 16188 return; 16189 } 16190 16191 synchronized (mPackages) { 16192 // Ensure the installer package name up to date 16193 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16194 16195 // Update permissions for restored package 16196 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16197 16198 mSettings.writeLPr(); 16199 } 16200 16201 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16202 } 16203 } else { 16204 synchronized (mPackages) { 16205 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16206 if (ps != null) { 16207 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16208 if (res.removedInfo.removedChildPackages != null) { 16209 final int childCount = res.removedInfo.removedChildPackages.size(); 16210 // Iterate in reverse as we may modify the collection 16211 for (int i = childCount - 1; i >= 0; i--) { 16212 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16213 if (res.addedChildPackages.containsKey(childPackageName)) { 16214 res.removedInfo.removedChildPackages.removeAt(i); 16215 } else { 16216 PackageRemovedInfo childInfo = res.removedInfo 16217 .removedChildPackages.valueAt(i); 16218 childInfo.removedForAllUsers = mPackages.get( 16219 childInfo.removedPackage) == null; 16220 } 16221 } 16222 } 16223 } 16224 } 16225 } 16226 } 16227 16228 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16229 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 16230 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16231 int installReason) { 16232 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16233 + ", old=" + deletedPackage); 16234 16235 final boolean disabledSystem; 16236 16237 // Remove existing system package 16238 removePackageLI(deletedPackage, true); 16239 16240 synchronized (mPackages) { 16241 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16242 } 16243 if (!disabledSystem) { 16244 // We didn't need to disable the .apk as a current system package, 16245 // which means we are replacing another update that is already 16246 // installed. We need to make sure to delete the older one's .apk. 16247 res.removedInfo.args = createInstallArgsForExisting(0, 16248 deletedPackage.applicationInfo.getCodePath(), 16249 deletedPackage.applicationInfo.getResourcePath(), 16250 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16251 } else { 16252 res.removedInfo.args = null; 16253 } 16254 16255 // Successfully disabled the old package. Now proceed with re-installation 16256 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16257 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16258 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16259 16260 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16261 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16262 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16263 16264 PackageParser.Package newPackage = null; 16265 try { 16266 // Add the package to the internal data structures 16267 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 16268 16269 // Set the update and install times 16270 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16271 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16272 System.currentTimeMillis()); 16273 16274 // Update the package dynamic state if succeeded 16275 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16276 // Now that the install succeeded make sure we remove data 16277 // directories for any child package the update removed. 16278 final int deletedChildCount = (deletedPackage.childPackages != null) 16279 ? deletedPackage.childPackages.size() : 0; 16280 final int newChildCount = (newPackage.childPackages != null) 16281 ? newPackage.childPackages.size() : 0; 16282 for (int i = 0; i < deletedChildCount; i++) { 16283 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16284 boolean childPackageDeleted = true; 16285 for (int j = 0; j < newChildCount; j++) { 16286 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16287 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16288 childPackageDeleted = false; 16289 break; 16290 } 16291 } 16292 if (childPackageDeleted) { 16293 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16294 deletedChildPkg.packageName); 16295 if (ps != null && res.removedInfo.removedChildPackages != null) { 16296 PackageRemovedInfo removedChildRes = res.removedInfo 16297 .removedChildPackages.get(deletedChildPkg.packageName); 16298 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16299 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16300 } 16301 } 16302 } 16303 16304 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16305 installReason); 16306 prepareAppDataAfterInstallLIF(newPackage); 16307 16308 mDexManager.notifyPackageUpdated(newPackage.packageName, 16309 newPackage.baseCodePath, newPackage.splitCodePaths); 16310 } 16311 } catch (PackageManagerException e) { 16312 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16313 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16314 } 16315 16316 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16317 // Re installation failed. Restore old information 16318 // Remove new pkg information 16319 if (newPackage != null) { 16320 removeInstalledPackageLI(newPackage, true); 16321 } 16322 // Add back the old system package 16323 try { 16324 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16325 } catch (PackageManagerException e) { 16326 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16327 } 16328 16329 synchronized (mPackages) { 16330 if (disabledSystem) { 16331 enableSystemPackageLPw(deletedPackage); 16332 } 16333 16334 // Ensure the installer package name up to date 16335 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16336 16337 // Update permissions for restored package 16338 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 16339 16340 mSettings.writeLPr(); 16341 } 16342 16343 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16344 + " after failed upgrade"); 16345 } 16346 } 16347 16348 /** 16349 * Checks whether the parent or any of the child packages have a change shared 16350 * user. For a package to be a valid update the shred users of the parent and 16351 * the children should match. We may later support changing child shared users. 16352 * @param oldPkg The updated package. 16353 * @param newPkg The update package. 16354 * @return The shared user that change between the versions. 16355 */ 16356 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16357 PackageParser.Package newPkg) { 16358 // Check parent shared user 16359 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16360 return newPkg.packageName; 16361 } 16362 // Check child shared users 16363 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16364 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16365 for (int i = 0; i < newChildCount; i++) { 16366 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16367 // If this child was present, did it have the same shared user? 16368 for (int j = 0; j < oldChildCount; j++) { 16369 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16370 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16371 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16372 return newChildPkg.packageName; 16373 } 16374 } 16375 } 16376 return null; 16377 } 16378 16379 private void removeNativeBinariesLI(PackageSetting ps) { 16380 // Remove the lib path for the parent package 16381 if (ps != null) { 16382 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16383 // Remove the lib path for the child packages 16384 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16385 for (int i = 0; i < childCount; i++) { 16386 PackageSetting childPs = null; 16387 synchronized (mPackages) { 16388 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16389 } 16390 if (childPs != null) { 16391 NativeLibraryHelper.removeNativeBinariesLI(childPs 16392 .legacyNativeLibraryPathString); 16393 } 16394 } 16395 } 16396 } 16397 16398 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16399 // Enable the parent package 16400 mSettings.enableSystemPackageLPw(pkg.packageName); 16401 // Enable the child packages 16402 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16403 for (int i = 0; i < childCount; i++) { 16404 PackageParser.Package childPkg = pkg.childPackages.get(i); 16405 mSettings.enableSystemPackageLPw(childPkg.packageName); 16406 } 16407 } 16408 16409 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16410 PackageParser.Package newPkg) { 16411 // Disable the parent package (parent always replaced) 16412 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16413 // Disable the child packages 16414 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16415 for (int i = 0; i < childCount; i++) { 16416 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16417 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16418 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16419 } 16420 return disabled; 16421 } 16422 16423 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16424 String installerPackageName) { 16425 // Enable the parent package 16426 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16427 // Enable the child packages 16428 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16429 for (int i = 0; i < childCount; i++) { 16430 PackageParser.Package childPkg = pkg.childPackages.get(i); 16431 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16432 } 16433 } 16434 16435 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 16436 // Collect all used permissions in the UID 16437 ArraySet<String> usedPermissions = new ArraySet<>(); 16438 final int packageCount = su.packages.size(); 16439 for (int i = 0; i < packageCount; i++) { 16440 PackageSetting ps = su.packages.valueAt(i); 16441 if (ps.pkg == null) { 16442 continue; 16443 } 16444 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 16445 for (int j = 0; j < requestedPermCount; j++) { 16446 String permission = ps.pkg.requestedPermissions.get(j); 16447 BasePermission bp = mSettings.mPermissions.get(permission); 16448 if (bp != null) { 16449 usedPermissions.add(permission); 16450 } 16451 } 16452 } 16453 16454 PermissionsState permissionsState = su.getPermissionsState(); 16455 // Prune install permissions 16456 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 16457 final int installPermCount = installPermStates.size(); 16458 for (int i = installPermCount - 1; i >= 0; i--) { 16459 PermissionState permissionState = installPermStates.get(i); 16460 if (!usedPermissions.contains(permissionState.getName())) { 16461 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16462 if (bp != null) { 16463 permissionsState.revokeInstallPermission(bp); 16464 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 16465 PackageManager.MASK_PERMISSION_FLAGS, 0); 16466 } 16467 } 16468 } 16469 16470 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 16471 16472 // Prune runtime permissions 16473 for (int userId : allUserIds) { 16474 List<PermissionState> runtimePermStates = permissionsState 16475 .getRuntimePermissionStates(userId); 16476 final int runtimePermCount = runtimePermStates.size(); 16477 for (int i = runtimePermCount - 1; i >= 0; i--) { 16478 PermissionState permissionState = runtimePermStates.get(i); 16479 if (!usedPermissions.contains(permissionState.getName())) { 16480 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 16481 if (bp != null) { 16482 permissionsState.revokeRuntimePermission(bp, userId); 16483 permissionsState.updatePermissionFlags(bp, userId, 16484 PackageManager.MASK_PERMISSION_FLAGS, 0); 16485 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 16486 runtimePermissionChangedUserIds, userId); 16487 } 16488 } 16489 } 16490 } 16491 16492 return runtimePermissionChangedUserIds; 16493 } 16494 16495 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16496 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16497 // Update the parent package setting 16498 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16499 res, user, installReason); 16500 // Update the child packages setting 16501 final int childCount = (newPackage.childPackages != null) 16502 ? newPackage.childPackages.size() : 0; 16503 for (int i = 0; i < childCount; i++) { 16504 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16505 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16506 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16507 childRes.origUsers, childRes, user, installReason); 16508 } 16509 } 16510 16511 private void updateSettingsInternalLI(PackageParser.Package newPackage, 16512 String installerPackageName, int[] allUsers, int[] installedForUsers, 16513 PackageInstalledInfo res, UserHandle user, int installReason) { 16514 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16515 16516 String pkgName = newPackage.packageName; 16517 synchronized (mPackages) { 16518 //write settings. the installStatus will be incomplete at this stage. 16519 //note that the new package setting would have already been 16520 //added to mPackages. It hasn't been persisted yet. 16521 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16522 // TODO: Remove this write? It's also written at the end of this method 16523 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16524 mSettings.writeLPr(); 16525 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16526 } 16527 16528 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 16529 synchronized (mPackages) { 16530 updatePermissionsLPw(newPackage.packageName, newPackage, 16531 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 16532 ? UPDATE_PERMISSIONS_ALL : 0)); 16533 // For system-bundled packages, we assume that installing an upgraded version 16534 // of the package implies that the user actually wants to run that new code, 16535 // so we enable the package. 16536 PackageSetting ps = mSettings.mPackages.get(pkgName); 16537 final int userId = user.getIdentifier(); 16538 if (ps != null) { 16539 if (isSystemApp(newPackage)) { 16540 if (DEBUG_INSTALL) { 16541 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16542 } 16543 // Enable system package for requested users 16544 if (res.origUsers != null) { 16545 for (int origUserId : res.origUsers) { 16546 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16547 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16548 origUserId, installerPackageName); 16549 } 16550 } 16551 } 16552 // Also convey the prior install/uninstall state 16553 if (allUsers != null && installedForUsers != null) { 16554 for (int currentUserId : allUsers) { 16555 final boolean installed = ArrayUtils.contains( 16556 installedForUsers, currentUserId); 16557 if (DEBUG_INSTALL) { 16558 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16559 } 16560 ps.setInstalled(installed, currentUserId); 16561 } 16562 // these install state changes will be persisted in the 16563 // upcoming call to mSettings.writeLPr(). 16564 } 16565 } 16566 // It's implied that when a user requests installation, they want the app to be 16567 // installed and enabled. 16568 if (userId != UserHandle.USER_ALL) { 16569 ps.setInstalled(true, userId); 16570 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16571 } 16572 16573 // When replacing an existing package, preserve the original install reason for all 16574 // users that had the package installed before. 16575 final Set<Integer> previousUserIds = new ArraySet<>(); 16576 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16577 final int installReasonCount = res.removedInfo.installReasons.size(); 16578 for (int i = 0; i < installReasonCount; i++) { 16579 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16580 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16581 ps.setInstallReason(previousInstallReason, previousUserId); 16582 previousUserIds.add(previousUserId); 16583 } 16584 } 16585 16586 // Set install reason for users that are having the package newly installed. 16587 if (userId == UserHandle.USER_ALL) { 16588 for (int currentUserId : sUserManager.getUserIds()) { 16589 if (!previousUserIds.contains(currentUserId)) { 16590 ps.setInstallReason(installReason, currentUserId); 16591 } 16592 } 16593 } else if (!previousUserIds.contains(userId)) { 16594 ps.setInstallReason(installReason, userId); 16595 } 16596 mSettings.writeKernelMappingLPr(ps); 16597 } 16598 res.name = pkgName; 16599 res.uid = newPackage.applicationInfo.uid; 16600 res.pkg = newPackage; 16601 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16602 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16603 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16604 //to update install status 16605 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16606 mSettings.writeLPr(); 16607 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16608 } 16609 16610 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16611 } 16612 16613 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16614 try { 16615 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16616 installPackageLI(args, res); 16617 } finally { 16618 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16619 } 16620 } 16621 16622 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16623 final int installFlags = args.installFlags; 16624 final String installerPackageName = args.installerPackageName; 16625 final String volumeUuid = args.volumeUuid; 16626 final File tmpPackageFile = new File(args.getCodePath()); 16627 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16628 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16629 || (args.volumeUuid != null)); 16630 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16631 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16632 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16633 boolean replace = false; 16634 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16635 if (args.move != null) { 16636 // moving a complete application; perform an initial scan on the new install location 16637 scanFlags |= SCAN_INITIAL; 16638 } 16639 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16640 scanFlags |= SCAN_DONT_KILL_APP; 16641 } 16642 if (instantApp) { 16643 scanFlags |= SCAN_AS_INSTANT_APP; 16644 } 16645 if (fullApp) { 16646 scanFlags |= SCAN_AS_FULL_APP; 16647 } 16648 16649 // Result object to be returned 16650 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16651 16652 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16653 16654 // Sanity check 16655 if (instantApp && (forwardLocked || onExternal)) { 16656 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16657 + " external=" + onExternal); 16658 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16659 return; 16660 } 16661 16662 // Retrieve PackageSettings and parse package 16663 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16664 | PackageParser.PARSE_ENFORCE_CODE 16665 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16666 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16667 | (instantApp ? PackageParser.PARSE_IS_EPHEMERAL : 0) 16668 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16669 PackageParser pp = new PackageParser(); 16670 pp.setSeparateProcesses(mSeparateProcesses); 16671 pp.setDisplayMetrics(mMetrics); 16672 pp.setCallback(mPackageParserCallback); 16673 16674 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16675 final PackageParser.Package pkg; 16676 try { 16677 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16678 } catch (PackageParserException e) { 16679 res.setError("Failed parse during installPackageLI", e); 16680 return; 16681 } finally { 16682 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16683 } 16684 16685 // Instant apps must have target SDK >= O and have targetSanboxVersion >= 2 16686 if (instantApp && pkg.applicationInfo.targetSdkVersion <= Build.VERSION_CODES.N_MR1) { 16687 Slog.w(TAG, "Instant app package " + pkg.packageName 16688 + " does not target O, this will be a fatal error."); 16689 // STOPSHIP: Make this a fatal error 16690 pkg.applicationInfo.targetSdkVersion = Build.VERSION_CODES.O; 16691 } 16692 if (instantApp && pkg.applicationInfo.targetSandboxVersion != 2) { 16693 Slog.w(TAG, "Instant app package " + pkg.packageName 16694 + " does not target targetSandboxVersion 2, this will be a fatal error."); 16695 // STOPSHIP: Make this a fatal error 16696 pkg.applicationInfo.targetSandboxVersion = 2; 16697 } 16698 16699 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16700 // Static shared libraries have synthetic package names 16701 renameStaticSharedLibraryPackage(pkg); 16702 16703 // No static shared libs on external storage 16704 if (onExternal) { 16705 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16706 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16707 "Packages declaring static-shared libs cannot be updated"); 16708 return; 16709 } 16710 } 16711 16712 // If we are installing a clustered package add results for the children 16713 if (pkg.childPackages != null) { 16714 synchronized (mPackages) { 16715 final int childCount = pkg.childPackages.size(); 16716 for (int i = 0; i < childCount; i++) { 16717 PackageParser.Package childPkg = pkg.childPackages.get(i); 16718 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16719 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16720 childRes.pkg = childPkg; 16721 childRes.name = childPkg.packageName; 16722 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16723 if (childPs != null) { 16724 childRes.origUsers = childPs.queryInstalledUsers( 16725 sUserManager.getUserIds(), true); 16726 } 16727 if ((mPackages.containsKey(childPkg.packageName))) { 16728 childRes.removedInfo = new PackageRemovedInfo(); 16729 childRes.removedInfo.removedPackage = childPkg.packageName; 16730 } 16731 if (res.addedChildPackages == null) { 16732 res.addedChildPackages = new ArrayMap<>(); 16733 } 16734 res.addedChildPackages.put(childPkg.packageName, childRes); 16735 } 16736 } 16737 } 16738 16739 // If package doesn't declare API override, mark that we have an install 16740 // time CPU ABI override. 16741 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16742 pkg.cpuAbiOverride = args.abiOverride; 16743 } 16744 16745 String pkgName = res.name = pkg.packageName; 16746 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16747 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16748 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16749 return; 16750 } 16751 } 16752 16753 try { 16754 // either use what we've been given or parse directly from the APK 16755 if (args.certificates != null) { 16756 try { 16757 PackageParser.populateCertificates(pkg, args.certificates); 16758 } catch (PackageParserException e) { 16759 // there was something wrong with the certificates we were given; 16760 // try to pull them from the APK 16761 PackageParser.collectCertificates(pkg, parseFlags); 16762 } 16763 } else { 16764 PackageParser.collectCertificates(pkg, parseFlags); 16765 } 16766 } catch (PackageParserException e) { 16767 res.setError("Failed collect during installPackageLI", e); 16768 return; 16769 } 16770 16771 // Get rid of all references to package scan path via parser. 16772 pp = null; 16773 String oldCodePath = null; 16774 boolean systemApp = false; 16775 synchronized (mPackages) { 16776 // Check if installing already existing package 16777 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16778 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16779 if (pkg.mOriginalPackages != null 16780 && pkg.mOriginalPackages.contains(oldName) 16781 && mPackages.containsKey(oldName)) { 16782 // This package is derived from an original package, 16783 // and this device has been updating from that original 16784 // name. We must continue using the original name, so 16785 // rename the new package here. 16786 pkg.setPackageName(oldName); 16787 pkgName = pkg.packageName; 16788 replace = true; 16789 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16790 + oldName + " pkgName=" + pkgName); 16791 } else if (mPackages.containsKey(pkgName)) { 16792 // This package, under its official name, already exists 16793 // on the device; we should replace it. 16794 replace = true; 16795 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16796 } 16797 16798 // Child packages are installed through the parent package 16799 if (pkg.parentPackage != null) { 16800 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16801 "Package " + pkg.packageName + " is child of package " 16802 + pkg.parentPackage.parentPackage + ". Child packages " 16803 + "can be updated only through the parent package."); 16804 return; 16805 } 16806 16807 if (replace) { 16808 // Prevent apps opting out from runtime permissions 16809 PackageParser.Package oldPackage = mPackages.get(pkgName); 16810 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16811 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16812 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16813 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16814 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16815 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16816 + " doesn't support runtime permissions but the old" 16817 + " target SDK " + oldTargetSdk + " does."); 16818 return; 16819 } 16820 // Prevent apps from downgrading their targetSandbox. 16821 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16822 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16823 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16824 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16825 "Package " + pkg.packageName + " new target sandbox " 16826 + newTargetSandbox + " is incompatible with the previous value of" 16827 + oldTargetSandbox + "."); 16828 return; 16829 } 16830 16831 // Prevent installing of child packages 16832 if (oldPackage.parentPackage != null) { 16833 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16834 "Package " + pkg.packageName + " is child of package " 16835 + oldPackage.parentPackage + ". Child packages " 16836 + "can be updated only through the parent package."); 16837 return; 16838 } 16839 } 16840 } 16841 16842 PackageSetting ps = mSettings.mPackages.get(pkgName); 16843 if (ps != null) { 16844 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16845 16846 // Static shared libs have same package with different versions where 16847 // we internally use a synthetic package name to allow multiple versions 16848 // of the same package, therefore we need to compare signatures against 16849 // the package setting for the latest library version. 16850 PackageSetting signatureCheckPs = ps; 16851 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16852 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16853 if (libraryEntry != null) { 16854 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16855 } 16856 } 16857 16858 // Quick sanity check that we're signed correctly if updating; 16859 // we'll check this again later when scanning, but we want to 16860 // bail early here before tripping over redefined permissions. 16861 if (shouldCheckUpgradeKeySetLP(signatureCheckPs, scanFlags)) { 16862 if (!checkUpgradeKeySetLP(signatureCheckPs, pkg)) { 16863 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16864 + pkg.packageName + " upgrade keys do not match the " 16865 + "previously installed version"); 16866 return; 16867 } 16868 } else { 16869 try { 16870 verifySignaturesLP(signatureCheckPs, pkg); 16871 } catch (PackageManagerException e) { 16872 res.setError(e.error, e.getMessage()); 16873 return; 16874 } 16875 } 16876 16877 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16878 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16879 systemApp = (ps.pkg.applicationInfo.flags & 16880 ApplicationInfo.FLAG_SYSTEM) != 0; 16881 } 16882 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16883 } 16884 16885 int N = pkg.permissions.size(); 16886 for (int i = N-1; i >= 0; i--) { 16887 PackageParser.Permission perm = pkg.permissions.get(i); 16888 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 16889 16890 // Don't allow anyone but the platform to define ephemeral permissions. 16891 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_EPHEMERAL) != 0 16892 && !PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16893 Slog.w(TAG, "Package " + pkg.packageName 16894 + " attempting to delcare ephemeral permission " 16895 + perm.info.name + "; Removing ephemeral."); 16896 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_EPHEMERAL; 16897 } 16898 // Check whether the newly-scanned package wants to define an already-defined perm 16899 if (bp != null) { 16900 // If the defining package is signed with our cert, it's okay. This 16901 // also includes the "updating the same package" case, of course. 16902 // "updating same package" could also involve key-rotation. 16903 final boolean sigsOk; 16904 if (bp.sourcePackage.equals(pkg.packageName) 16905 && (bp.packageSetting instanceof PackageSetting) 16906 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 16907 scanFlags))) { 16908 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 16909 } else { 16910 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 16911 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 16912 } 16913 if (!sigsOk) { 16914 // If the owning package is the system itself, we log but allow 16915 // install to proceed; we fail the install on all other permission 16916 // redefinitions. 16917 if (!bp.sourcePackage.equals("android")) { 16918 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16919 + pkg.packageName + " attempting to redeclare permission " 16920 + perm.info.name + " already owned by " + bp.sourcePackage); 16921 res.origPermission = perm.info.name; 16922 res.origPackage = bp.sourcePackage; 16923 return; 16924 } else { 16925 Slog.w(TAG, "Package " + pkg.packageName 16926 + " attempting to redeclare system permission " 16927 + perm.info.name + "; ignoring new declaration"); 16928 pkg.permissions.remove(i); 16929 } 16930 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16931 // Prevent apps to change protection level to dangerous from any other 16932 // type as this would allow a privilege escalation where an app adds a 16933 // normal/signature permission in other app's group and later redefines 16934 // it as dangerous leading to the group auto-grant. 16935 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16936 == PermissionInfo.PROTECTION_DANGEROUS) { 16937 if (bp != null && !bp.isRuntime()) { 16938 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16939 + "non-runtime permission " + perm.info.name 16940 + " to runtime; keeping old protection level"); 16941 perm.info.protectionLevel = bp.protectionLevel; 16942 } 16943 } 16944 } 16945 } 16946 } 16947 } 16948 16949 if (systemApp) { 16950 if (onExternal) { 16951 // Abort update; system app can't be replaced with app on sdcard 16952 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16953 "Cannot install updates to system apps on sdcard"); 16954 return; 16955 } else if (instantApp) { 16956 // Abort update; system app can't be replaced with an instant app 16957 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16958 "Cannot update a system app with an instant app"); 16959 return; 16960 } 16961 } 16962 16963 if (args.move != null) { 16964 // We did an in-place move, so dex is ready to roll 16965 scanFlags |= SCAN_NO_DEX; 16966 scanFlags |= SCAN_MOVE; 16967 16968 synchronized (mPackages) { 16969 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16970 if (ps == null) { 16971 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16972 "Missing settings for moved package " + pkgName); 16973 } 16974 16975 // We moved the entire application as-is, so bring over the 16976 // previously derived ABI information. 16977 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16978 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16979 } 16980 16981 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16982 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16983 scanFlags |= SCAN_NO_DEX; 16984 16985 try { 16986 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16987 args.abiOverride : pkg.cpuAbiOverride); 16988 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 16989 true /*extractLibs*/, mAppLib32InstallDir); 16990 } catch (PackageManagerException pme) { 16991 Slog.e(TAG, "Error deriving application ABI", pme); 16992 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16993 return; 16994 } 16995 16996 // Shared libraries for the package need to be updated. 16997 synchronized (mPackages) { 16998 try { 16999 updateSharedLibrariesLPr(pkg, null); 17000 } catch (PackageManagerException e) { 17001 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17002 } 17003 } 17004 17005 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17006 // Do not run PackageDexOptimizer through the local performDexOpt 17007 // method because `pkg` may not be in `mPackages` yet. 17008 // 17009 // Also, don't fail application installs if the dexopt step fails. 17010 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17011 null /* instructionSets */, false /* checkProfiles */, 17012 getCompilerFilterForReason(REASON_INSTALL), 17013 getOrCreateCompilerPackageStats(pkg), 17014 mDexManager.isUsedByOtherApps(pkg.packageName)); 17015 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17016 17017 // Notify BackgroundDexOptService that the package has been changed. 17018 // If this is an update of a package which used to fail to compile, 17019 // BDOS will remove it from its blacklist. 17020 // TODO: Layering violation 17021 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17022 } 17023 17024 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17025 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17026 return; 17027 } 17028 17029 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17030 17031 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17032 "installPackageLI")) { 17033 if (replace) { 17034 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17035 // Static libs have a synthetic package name containing the version 17036 // and cannot be updated as an update would get a new package name, 17037 // unless this is the exact same version code which is useful for 17038 // development. 17039 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17040 if (existingPkg != null && existingPkg.mVersionCode != pkg.mVersionCode) { 17041 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17042 + "static-shared libs cannot be updated"); 17043 return; 17044 } 17045 } 17046 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 17047 installerPackageName, res, args.installReason); 17048 } else { 17049 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17050 args.user, installerPackageName, volumeUuid, res, args.installReason); 17051 } 17052 } 17053 17054 synchronized (mPackages) { 17055 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17056 if (ps != null) { 17057 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17058 ps.setUpdateAvailable(false /*updateAvailable*/); 17059 } 17060 17061 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17062 for (int i = 0; i < childCount; i++) { 17063 PackageParser.Package childPkg = pkg.childPackages.get(i); 17064 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17065 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17066 if (childPs != null) { 17067 childRes.newUsers = childPs.queryInstalledUsers( 17068 sUserManager.getUserIds(), true); 17069 } 17070 } 17071 17072 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17073 updateSequenceNumberLP(pkgName, res.newUsers); 17074 updateInstantAppInstallerLocked(pkgName); 17075 } 17076 } 17077 } 17078 17079 private void startIntentFilterVerifications(int userId, boolean replacing, 17080 PackageParser.Package pkg) { 17081 if (mIntentFilterVerifierComponent == null) { 17082 Slog.w(TAG, "No IntentFilter verification will not be done as " 17083 + "there is no IntentFilterVerifier available!"); 17084 return; 17085 } 17086 17087 final int verifierUid = getPackageUid( 17088 mIntentFilterVerifierComponent.getPackageName(), 17089 MATCH_DEBUG_TRIAGED_MISSING, 17090 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17091 17092 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17093 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17094 mHandler.sendMessage(msg); 17095 17096 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17097 for (int i = 0; i < childCount; i++) { 17098 PackageParser.Package childPkg = pkg.childPackages.get(i); 17099 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17100 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17101 mHandler.sendMessage(msg); 17102 } 17103 } 17104 17105 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17106 PackageParser.Package pkg) { 17107 int size = pkg.activities.size(); 17108 if (size == 0) { 17109 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17110 "No activity, so no need to verify any IntentFilter!"); 17111 return; 17112 } 17113 17114 final boolean hasDomainURLs = hasDomainURLs(pkg); 17115 if (!hasDomainURLs) { 17116 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17117 "No domain URLs, so no need to verify any IntentFilter!"); 17118 return; 17119 } 17120 17121 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17122 + " if any IntentFilter from the " + size 17123 + " Activities needs verification ..."); 17124 17125 int count = 0; 17126 final String packageName = pkg.packageName; 17127 17128 synchronized (mPackages) { 17129 // If this is a new install and we see that we've already run verification for this 17130 // package, we have nothing to do: it means the state was restored from backup. 17131 if (!replacing) { 17132 IntentFilterVerificationInfo ivi = 17133 mSettings.getIntentFilterVerificationLPr(packageName); 17134 if (ivi != null) { 17135 if (DEBUG_DOMAIN_VERIFICATION) { 17136 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17137 + ivi.getStatusString()); 17138 } 17139 return; 17140 } 17141 } 17142 17143 // If any filters need to be verified, then all need to be. 17144 boolean needToVerify = false; 17145 for (PackageParser.Activity a : pkg.activities) { 17146 for (ActivityIntentInfo filter : a.intents) { 17147 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17148 if (DEBUG_DOMAIN_VERIFICATION) { 17149 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 17150 } 17151 needToVerify = true; 17152 break; 17153 } 17154 } 17155 } 17156 17157 if (needToVerify) { 17158 final int verificationId = mIntentFilterVerificationToken++; 17159 for (PackageParser.Activity a : pkg.activities) { 17160 for (ActivityIntentInfo filter : a.intents) { 17161 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17162 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17163 "Verification needed for IntentFilter:" + filter.toString()); 17164 mIntentFilterVerifier.addOneIntentFilterVerification( 17165 verifierUid, userId, verificationId, filter, packageName); 17166 count++; 17167 } 17168 } 17169 } 17170 } 17171 } 17172 17173 if (count > 0) { 17174 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17175 + " IntentFilter verification" + (count > 1 ? "s" : "") 17176 + " for userId:" + userId); 17177 mIntentFilterVerifier.startVerifications(userId); 17178 } else { 17179 if (DEBUG_DOMAIN_VERIFICATION) { 17180 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17181 } 17182 } 17183 } 17184 17185 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17186 final ComponentName cn = filter.activity.getComponentName(); 17187 final String packageName = cn.getPackageName(); 17188 17189 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17190 packageName); 17191 if (ivi == null) { 17192 return true; 17193 } 17194 int status = ivi.getStatus(); 17195 switch (status) { 17196 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17197 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17198 return true; 17199 17200 default: 17201 // Nothing to do 17202 return false; 17203 } 17204 } 17205 17206 private static boolean isMultiArch(ApplicationInfo info) { 17207 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17208 } 17209 17210 private static boolean isExternal(PackageParser.Package pkg) { 17211 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17212 } 17213 17214 private static boolean isExternal(PackageSetting ps) { 17215 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17216 } 17217 17218 private static boolean isSystemApp(PackageParser.Package pkg) { 17219 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17220 } 17221 17222 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17223 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17224 } 17225 17226 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17227 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17228 } 17229 17230 private static boolean isSystemApp(PackageSetting ps) { 17231 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17232 } 17233 17234 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17235 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17236 } 17237 17238 private int packageFlagsToInstallFlags(PackageSetting ps) { 17239 int installFlags = 0; 17240 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17241 // This existing package was an external ASEC install when we have 17242 // the external flag without a UUID 17243 installFlags |= PackageManager.INSTALL_EXTERNAL; 17244 } 17245 if (ps.isForwardLocked()) { 17246 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17247 } 17248 return installFlags; 17249 } 17250 17251 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 17252 if (isExternal(pkg)) { 17253 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17254 return StorageManager.UUID_PRIMARY_PHYSICAL; 17255 } else { 17256 return pkg.volumeUuid; 17257 } 17258 } else { 17259 return StorageManager.UUID_PRIVATE_INTERNAL; 17260 } 17261 } 17262 17263 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17264 if (isExternal(pkg)) { 17265 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17266 return mSettings.getExternalVersion(); 17267 } else { 17268 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17269 } 17270 } else { 17271 return mSettings.getInternalVersion(); 17272 } 17273 } 17274 17275 private void deleteTempPackageFiles() { 17276 final FilenameFilter filter = new FilenameFilter() { 17277 public boolean accept(File dir, String name) { 17278 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17279 } 17280 }; 17281 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 17282 file.delete(); 17283 } 17284 } 17285 17286 @Override 17287 public void deletePackageAsUser(String packageName, int versionCode, 17288 IPackageDeleteObserver observer, int userId, int flags) { 17289 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17290 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17291 } 17292 17293 @Override 17294 public void deletePackageVersioned(VersionedPackage versionedPackage, 17295 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17296 mContext.enforceCallingOrSelfPermission( 17297 android.Manifest.permission.DELETE_PACKAGES, null); 17298 Preconditions.checkNotNull(versionedPackage); 17299 Preconditions.checkNotNull(observer); 17300 Preconditions.checkArgumentInRange(versionedPackage.getVersionCode(), 17301 PackageManager.VERSION_CODE_HIGHEST, 17302 Integer.MAX_VALUE, "versionCode must be >= -1"); 17303 17304 final String packageName = versionedPackage.getPackageName(); 17305 // TODO: We will change version code to long, so in the new API it is long 17306 final int versionCode = (int) versionedPackage.getVersionCode(); 17307 final String internalPackageName; 17308 synchronized (mPackages) { 17309 // Normalize package name to handle renamed packages and static libs 17310 internalPackageName = resolveInternalPackageNameLPr(versionedPackage.getPackageName(), 17311 // TODO: We will change version code to long, so in the new API it is long 17312 (int) versionedPackage.getVersionCode()); 17313 } 17314 17315 final int uid = Binder.getCallingUid(); 17316 if (!isOrphaned(internalPackageName) 17317 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17318 try { 17319 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17320 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17321 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17322 observer.onUserActionRequired(intent); 17323 } catch (RemoteException re) { 17324 } 17325 return; 17326 } 17327 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17328 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17329 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17330 mContext.enforceCallingOrSelfPermission( 17331 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17332 "deletePackage for user " + userId); 17333 } 17334 17335 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17336 try { 17337 observer.onPackageDeleted(packageName, 17338 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17339 } catch (RemoteException re) { 17340 } 17341 return; 17342 } 17343 17344 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17345 try { 17346 observer.onPackageDeleted(packageName, 17347 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17348 } catch (RemoteException re) { 17349 } 17350 return; 17351 } 17352 17353 if (DEBUG_REMOVE) { 17354 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17355 + " deleteAllUsers: " + deleteAllUsers + " version=" 17356 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17357 ? "VERSION_CODE_HIGHEST" : versionCode)); 17358 } 17359 // Queue up an async operation since the package deletion may take a little while. 17360 mHandler.post(new Runnable() { 17361 public void run() { 17362 mHandler.removeCallbacks(this); 17363 int returnCode; 17364 if (!deleteAllUsers) { 17365 returnCode = deletePackageX(internalPackageName, versionCode, 17366 userId, deleteFlags); 17367 } else { 17368 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17369 internalPackageName, users); 17370 // If nobody is blocking uninstall, proceed with delete for all users 17371 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17372 returnCode = deletePackageX(internalPackageName, versionCode, 17373 userId, deleteFlags); 17374 } else { 17375 // Otherwise uninstall individually for users with blockUninstalls=false 17376 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17377 for (int userId : users) { 17378 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17379 returnCode = deletePackageX(internalPackageName, versionCode, 17380 userId, userFlags); 17381 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17382 Slog.w(TAG, "Package delete failed for user " + userId 17383 + ", returnCode " + returnCode); 17384 } 17385 } 17386 } 17387 // The app has only been marked uninstalled for certain users. 17388 // We still need to report that delete was blocked 17389 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17390 } 17391 } 17392 try { 17393 observer.onPackageDeleted(packageName, returnCode, null); 17394 } catch (RemoteException e) { 17395 Log.i(TAG, "Observer no longer exists."); 17396 } //end catch 17397 } //end run 17398 }); 17399 } 17400 17401 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17402 if (pkg.staticSharedLibName != null) { 17403 return pkg.manifestPackageName; 17404 } 17405 return pkg.packageName; 17406 } 17407 17408 private String resolveInternalPackageNameLPr(String packageName, int versionCode) { 17409 // Handle renamed packages 17410 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17411 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17412 17413 // Is this a static library? 17414 SparseArray<SharedLibraryEntry> versionedLib = 17415 mStaticLibsByDeclaringPackage.get(packageName); 17416 if (versionedLib == null || versionedLib.size() <= 0) { 17417 return packageName; 17418 } 17419 17420 // Figure out which lib versions the caller can see 17421 SparseIntArray versionsCallerCanSee = null; 17422 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17423 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17424 && callingAppId != Process.ROOT_UID) { 17425 versionsCallerCanSee = new SparseIntArray(); 17426 String libName = versionedLib.valueAt(0).info.getName(); 17427 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17428 if (uidPackages != null) { 17429 for (String uidPackage : uidPackages) { 17430 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17431 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17432 if (libIdx >= 0) { 17433 final int libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17434 versionsCallerCanSee.append(libVersion, libVersion); 17435 } 17436 } 17437 } 17438 } 17439 17440 // Caller can see nothing - done 17441 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17442 return packageName; 17443 } 17444 17445 // Find the version the caller can see and the app version code 17446 SharedLibraryEntry highestVersion = null; 17447 final int versionCount = versionedLib.size(); 17448 for (int i = 0; i < versionCount; i++) { 17449 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17450 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17451 libEntry.info.getVersion()) < 0) { 17452 continue; 17453 } 17454 // TODO: We will change version code to long, so in the new API it is long 17455 final int libVersionCode = (int) libEntry.info.getDeclaringPackage().getVersionCode(); 17456 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17457 if (libVersionCode == versionCode) { 17458 return libEntry.apk; 17459 } 17460 } else if (highestVersion == null) { 17461 highestVersion = libEntry; 17462 } else if (libVersionCode > highestVersion.info 17463 .getDeclaringPackage().getVersionCode()) { 17464 highestVersion = libEntry; 17465 } 17466 } 17467 17468 if (highestVersion != null) { 17469 return highestVersion.apk; 17470 } 17471 17472 return packageName; 17473 } 17474 17475 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17476 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17477 || callingUid == Process.SYSTEM_UID) { 17478 return true; 17479 } 17480 final int callingUserId = UserHandle.getUserId(callingUid); 17481 // If the caller installed the pkgName, then allow it to silently uninstall. 17482 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17483 return true; 17484 } 17485 17486 // Allow package verifier to silently uninstall. 17487 if (mRequiredVerifierPackage != null && 17488 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17489 return true; 17490 } 17491 17492 // Allow package uninstaller to silently uninstall. 17493 if (mRequiredUninstallerPackage != null && 17494 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17495 return true; 17496 } 17497 17498 // Allow storage manager to silently uninstall. 17499 if (mStorageManagerPackage != null && 17500 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17501 return true; 17502 } 17503 return false; 17504 } 17505 17506 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17507 int[] result = EMPTY_INT_ARRAY; 17508 for (int userId : userIds) { 17509 if (getBlockUninstallForUser(packageName, userId)) { 17510 result = ArrayUtils.appendInt(result, userId); 17511 } 17512 } 17513 return result; 17514 } 17515 17516 @Override 17517 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17518 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17519 } 17520 17521 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17522 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17523 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17524 try { 17525 if (dpm != null) { 17526 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17527 /* callingUserOnly =*/ false); 17528 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17529 : deviceOwnerComponentName.getPackageName(); 17530 // Does the package contains the device owner? 17531 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17532 // this check is probably not needed, since DO should be registered as a device 17533 // admin on some user too. (Original bug for this: b/17657954) 17534 if (packageName.equals(deviceOwnerPackageName)) { 17535 return true; 17536 } 17537 // Does it contain a device admin for any user? 17538 int[] users; 17539 if (userId == UserHandle.USER_ALL) { 17540 users = sUserManager.getUserIds(); 17541 } else { 17542 users = new int[]{userId}; 17543 } 17544 for (int i = 0; i < users.length; ++i) { 17545 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17546 return true; 17547 } 17548 } 17549 } 17550 } catch (RemoteException e) { 17551 } 17552 return false; 17553 } 17554 17555 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17556 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17557 } 17558 17559 /** 17560 * This method is an internal method that could be get invoked either 17561 * to delete an installed package or to clean up a failed installation. 17562 * After deleting an installed package, a broadcast is sent to notify any 17563 * listeners that the package has been removed. For cleaning up a failed 17564 * installation, the broadcast is not necessary since the package's 17565 * installation wouldn't have sent the initial broadcast either 17566 * The key steps in deleting a package are 17567 * deleting the package information in internal structures like mPackages, 17568 * deleting the packages base directories through installd 17569 * updating mSettings to reflect current status 17570 * persisting settings for later use 17571 * sending a broadcast if necessary 17572 */ 17573 private int deletePackageX(String packageName, int versionCode, int userId, int deleteFlags) { 17574 final PackageRemovedInfo info = new PackageRemovedInfo(); 17575 final boolean res; 17576 17577 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17578 ? UserHandle.USER_ALL : userId; 17579 17580 if (isPackageDeviceAdmin(packageName, removeUser)) { 17581 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17582 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17583 } 17584 17585 PackageSetting uninstalledPs = null; 17586 PackageParser.Package pkg = null; 17587 17588 // for the uninstall-updates case and restricted profiles, remember the per- 17589 // user handle installed state 17590 int[] allUsers; 17591 synchronized (mPackages) { 17592 uninstalledPs = mSettings.mPackages.get(packageName); 17593 if (uninstalledPs == null) { 17594 Slog.w(TAG, "Not removing non-existent package " + packageName); 17595 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17596 } 17597 17598 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17599 && uninstalledPs.versionCode != versionCode) { 17600 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17601 + uninstalledPs.versionCode + " != " + versionCode); 17602 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17603 } 17604 17605 // Static shared libs can be declared by any package, so let us not 17606 // allow removing a package if it provides a lib others depend on. 17607 pkg = mPackages.get(packageName); 17608 if (pkg != null && pkg.staticSharedLibName != null) { 17609 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17610 pkg.staticSharedLibVersion); 17611 if (libEntry != null) { 17612 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17613 libEntry.info, 0, userId); 17614 if (!ArrayUtils.isEmpty(libClientPackages)) { 17615 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17616 + " hosting lib " + libEntry.info.getName() + " version " 17617 + libEntry.info.getVersion() + " used by " + libClientPackages); 17618 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17619 } 17620 } 17621 } 17622 17623 allUsers = sUserManager.getUserIds(); 17624 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17625 } 17626 17627 final int freezeUser; 17628 if (isUpdatedSystemApp(uninstalledPs) 17629 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17630 // We're downgrading a system app, which will apply to all users, so 17631 // freeze them all during the downgrade 17632 freezeUser = UserHandle.USER_ALL; 17633 } else { 17634 freezeUser = removeUser; 17635 } 17636 17637 synchronized (mInstallLock) { 17638 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17639 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17640 deleteFlags, "deletePackageX")) { 17641 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17642 deleteFlags | FLAGS_REMOVE_CHATTY, info, true, null); 17643 } 17644 synchronized (mPackages) { 17645 if (res) { 17646 if (pkg != null) { 17647 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17648 } 17649 updateSequenceNumberLP(packageName, info.removedUsers); 17650 updateInstantAppInstallerLocked(packageName); 17651 } 17652 } 17653 } 17654 17655 if (res) { 17656 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17657 info.sendPackageRemovedBroadcasts(killApp); 17658 info.sendSystemPackageUpdatedBroadcasts(); 17659 info.sendSystemPackageAppearedBroadcasts(); 17660 } 17661 // Force a gc here. 17662 Runtime.getRuntime().gc(); 17663 // Delete the resources here after sending the broadcast to let 17664 // other processes clean up before deleting resources. 17665 if (info.args != null) { 17666 synchronized (mInstallLock) { 17667 info.args.doPostDeleteLI(true); 17668 } 17669 } 17670 17671 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17672 } 17673 17674 class PackageRemovedInfo { 17675 String removedPackage; 17676 int uid = -1; 17677 int removedAppId = -1; 17678 int[] origUsers; 17679 int[] removedUsers = null; 17680 int[] broadcastUsers = null; 17681 SparseArray<Integer> installReasons; 17682 boolean isRemovedPackageSystemUpdate = false; 17683 boolean isUpdate; 17684 boolean dataRemoved; 17685 boolean removedForAllUsers; 17686 boolean isStaticSharedLib; 17687 // Clean up resources deleted packages. 17688 InstallArgs args = null; 17689 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17690 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17691 17692 void sendPackageRemovedBroadcasts(boolean killApp) { 17693 sendPackageRemovedBroadcastInternal(killApp); 17694 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17695 for (int i = 0; i < childCount; i++) { 17696 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17697 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17698 } 17699 } 17700 17701 void sendSystemPackageUpdatedBroadcasts() { 17702 if (isRemovedPackageSystemUpdate) { 17703 sendSystemPackageUpdatedBroadcastsInternal(); 17704 final int childCount = (removedChildPackages != null) 17705 ? removedChildPackages.size() : 0; 17706 for (int i = 0; i < childCount; i++) { 17707 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17708 if (childInfo.isRemovedPackageSystemUpdate) { 17709 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17710 } 17711 } 17712 } 17713 } 17714 17715 void sendSystemPackageAppearedBroadcasts() { 17716 final int packageCount = (appearedChildPackages != null) 17717 ? appearedChildPackages.size() : 0; 17718 for (int i = 0; i < packageCount; i++) { 17719 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17720 sendPackageAddedForNewUsers(installedInfo.name, true, 17721 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 17722 } 17723 } 17724 17725 private void sendSystemPackageUpdatedBroadcastsInternal() { 17726 Bundle extras = new Bundle(2); 17727 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17728 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17729 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 17730 extras, 0, null, null, null); 17731 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 17732 extras, 0, null, null, null); 17733 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 17734 null, 0, removedPackage, null, null); 17735 } 17736 17737 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17738 // Don't send static shared library removal broadcasts as these 17739 // libs are visible only the the apps that depend on them an one 17740 // cannot remove the library if it has a dependency. 17741 if (isStaticSharedLib) { 17742 return; 17743 } 17744 Bundle extras = new Bundle(2); 17745 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17746 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17747 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17748 if (isUpdate || isRemovedPackageSystemUpdate) { 17749 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17750 } 17751 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17752 if (removedPackage != null) { 17753 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 17754 extras, 0, null, null, broadcastUsers); 17755 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17756 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17757 removedPackage, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17758 null, null, broadcastUsers); 17759 } 17760 } 17761 if (removedAppId >= 0) { 17762 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 17763 broadcastUsers); 17764 } 17765 } 17766 } 17767 17768 /* 17769 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17770 * flag is not set, the data directory is removed as well. 17771 * make sure this flag is set for partially installed apps. If not its meaningless to 17772 * delete a partially installed application. 17773 */ 17774 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17775 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17776 String packageName = ps.name; 17777 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17778 // Retrieve object to delete permissions for shared user later on 17779 final PackageParser.Package deletedPkg; 17780 final PackageSetting deletedPs; 17781 // reader 17782 synchronized (mPackages) { 17783 deletedPkg = mPackages.get(packageName); 17784 deletedPs = mSettings.mPackages.get(packageName); 17785 if (outInfo != null) { 17786 outInfo.removedPackage = packageName; 17787 outInfo.isStaticSharedLib = deletedPkg != null 17788 && deletedPkg.staticSharedLibName != null; 17789 outInfo.removedUsers = deletedPs != null 17790 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 17791 : null; 17792 if (outInfo.removedUsers == null) { 17793 outInfo.broadcastUsers = null; 17794 } else { 17795 outInfo.broadcastUsers = EMPTY_INT_ARRAY; 17796 int[] allUsers = outInfo.removedUsers; 17797 for (int i = allUsers.length - 1; i >= 0; --i) { 17798 final int userId = allUsers[i]; 17799 if (deletedPs.getInstantApp(userId)) { 17800 continue; 17801 } 17802 outInfo.broadcastUsers = 17803 ArrayUtils.appendInt(outInfo.broadcastUsers, userId); 17804 } 17805 } 17806 } 17807 } 17808 17809 removePackageLI(ps, (flags & FLAGS_REMOVE_CHATTY) != 0); 17810 17811 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17812 final PackageParser.Package resolvedPkg; 17813 if (deletedPkg != null) { 17814 resolvedPkg = deletedPkg; 17815 } else { 17816 // We don't have a parsed package when it lives on an ejected 17817 // adopted storage device, so fake something together 17818 resolvedPkg = new PackageParser.Package(ps.name); 17819 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17820 } 17821 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17822 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17823 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17824 if (outInfo != null) { 17825 outInfo.dataRemoved = true; 17826 } 17827 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17828 } 17829 17830 int removedAppId = -1; 17831 17832 // writer 17833 synchronized (mPackages) { 17834 boolean installedStateChanged = false; 17835 if (deletedPs != null) { 17836 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17837 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17838 clearDefaultBrowserIfNeeded(packageName); 17839 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17840 removedAppId = mSettings.removePackageLPw(packageName); 17841 if (outInfo != null) { 17842 outInfo.removedAppId = removedAppId; 17843 } 17844 updatePermissionsLPw(deletedPs.name, null, 0); 17845 if (deletedPs.sharedUser != null) { 17846 // Remove permissions associated with package. Since runtime 17847 // permissions are per user we have to kill the removed package 17848 // or packages running under the shared user of the removed 17849 // package if revoking the permissions requested only by the removed 17850 // package is successful and this causes a change in gids. 17851 for (int userId : UserManagerService.getInstance().getUserIds()) { 17852 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17853 userId); 17854 if (userIdToKill == UserHandle.USER_ALL 17855 || userIdToKill >= UserHandle.USER_SYSTEM) { 17856 // If gids changed for this user, kill all affected packages. 17857 mHandler.post(new Runnable() { 17858 @Override 17859 public void run() { 17860 // This has to happen with no lock held. 17861 killApplication(deletedPs.name, deletedPs.appId, 17862 KILL_APP_REASON_GIDS_CHANGED); 17863 } 17864 }); 17865 break; 17866 } 17867 } 17868 } 17869 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17870 } 17871 // make sure to preserve per-user disabled state if this removal was just 17872 // a downgrade of a system app to the factory package 17873 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17874 if (DEBUG_REMOVE) { 17875 Slog.d(TAG, "Propagating install state across downgrade"); 17876 } 17877 for (int userId : allUserHandles) { 17878 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17879 if (DEBUG_REMOVE) { 17880 Slog.d(TAG, " user " + userId + " => " + installed); 17881 } 17882 if (installed != ps.getInstalled(userId)) { 17883 installedStateChanged = true; 17884 } 17885 ps.setInstalled(installed, userId); 17886 } 17887 } 17888 } 17889 // can downgrade to reader 17890 if (writeSettings) { 17891 // Save settings now 17892 mSettings.writeLPr(); 17893 } 17894 if (installedStateChanged) { 17895 mSettings.writeKernelMappingLPr(ps); 17896 } 17897 } 17898 if (removedAppId != -1) { 17899 // A user ID was deleted here. Go through all users and remove it 17900 // from KeyStore. 17901 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17902 } 17903 } 17904 17905 static boolean locationIsPrivileged(File path) { 17906 try { 17907 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 17908 .getCanonicalPath(); 17909 return path.getCanonicalPath().startsWith(privilegedAppDir); 17910 } catch (IOException e) { 17911 Slog.e(TAG, "Unable to access code path " + path); 17912 } 17913 return false; 17914 } 17915 17916 /* 17917 * Tries to delete system package. 17918 */ 17919 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17920 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17921 boolean writeSettings) { 17922 if (deletedPs.parentPackageName != null) { 17923 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17924 return false; 17925 } 17926 17927 final boolean applyUserRestrictions 17928 = (allUserHandles != null) && (outInfo.origUsers != null); 17929 final PackageSetting disabledPs; 17930 // Confirm if the system package has been updated 17931 // An updated system app can be deleted. This will also have to restore 17932 // the system pkg from system partition 17933 // reader 17934 synchronized (mPackages) { 17935 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17936 } 17937 17938 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17939 + " disabledPs=" + disabledPs); 17940 17941 if (disabledPs == null) { 17942 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17943 return false; 17944 } else if (DEBUG_REMOVE) { 17945 Slog.d(TAG, "Deleting system pkg from data partition"); 17946 } 17947 17948 if (DEBUG_REMOVE) { 17949 if (applyUserRestrictions) { 17950 Slog.d(TAG, "Remembering install states:"); 17951 for (int userId : allUserHandles) { 17952 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17953 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17954 } 17955 } 17956 } 17957 17958 // Delete the updated package 17959 outInfo.isRemovedPackageSystemUpdate = true; 17960 if (outInfo.removedChildPackages != null) { 17961 final int childCount = (deletedPs.childPackageNames != null) 17962 ? deletedPs.childPackageNames.size() : 0; 17963 for (int i = 0; i < childCount; i++) { 17964 String childPackageName = deletedPs.childPackageNames.get(i); 17965 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17966 .contains(childPackageName)) { 17967 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17968 childPackageName); 17969 if (childInfo != null) { 17970 childInfo.isRemovedPackageSystemUpdate = true; 17971 } 17972 } 17973 } 17974 } 17975 17976 if (disabledPs.versionCode < deletedPs.versionCode) { 17977 // Delete data for downgrades 17978 flags &= ~PackageManager.DELETE_KEEP_DATA; 17979 } else { 17980 // Preserve data by setting flag 17981 flags |= PackageManager.DELETE_KEEP_DATA; 17982 } 17983 17984 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17985 outInfo, writeSettings, disabledPs.pkg); 17986 if (!ret) { 17987 return false; 17988 } 17989 17990 // writer 17991 synchronized (mPackages) { 17992 // Reinstate the old system package 17993 enableSystemPackageLPw(disabledPs.pkg); 17994 // Remove any native libraries from the upgraded package. 17995 removeNativeBinariesLI(deletedPs); 17996 } 17997 17998 // Install the system package 17999 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18000 int parseFlags = mDefParseFlags 18001 | PackageParser.PARSE_MUST_BE_APK 18002 | PackageParser.PARSE_IS_SYSTEM 18003 | PackageParser.PARSE_IS_SYSTEM_DIR; 18004 if (locationIsPrivileged(disabledPs.codePath)) { 18005 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 18006 } 18007 18008 final PackageParser.Package newPkg; 18009 try { 18010 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 18011 0 /* currentTime */, null); 18012 } catch (PackageManagerException e) { 18013 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18014 + e.getMessage()); 18015 return false; 18016 } 18017 18018 try { 18019 // update shared libraries for the newly re-installed system package 18020 updateSharedLibrariesLPr(newPkg, null); 18021 } catch (PackageManagerException e) { 18022 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18023 } 18024 18025 prepareAppDataAfterInstallLIF(newPkg); 18026 18027 // writer 18028 synchronized (mPackages) { 18029 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 18030 18031 // Propagate the permissions state as we do not want to drop on the floor 18032 // runtime permissions. The update permissions method below will take 18033 // care of removing obsolete permissions and grant install permissions. 18034 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 18035 updatePermissionsLPw(newPkg.packageName, newPkg, 18036 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 18037 18038 if (applyUserRestrictions) { 18039 boolean installedStateChanged = false; 18040 if (DEBUG_REMOVE) { 18041 Slog.d(TAG, "Propagating install state across reinstall"); 18042 } 18043 for (int userId : allUserHandles) { 18044 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18045 if (DEBUG_REMOVE) { 18046 Slog.d(TAG, " user " + userId + " => " + installed); 18047 } 18048 if (installed != ps.getInstalled(userId)) { 18049 installedStateChanged = true; 18050 } 18051 ps.setInstalled(installed, userId); 18052 18053 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18054 } 18055 // Regardless of writeSettings we need to ensure that this restriction 18056 // state propagation is persisted 18057 mSettings.writeAllUsersPackageRestrictionsLPr(); 18058 if (installedStateChanged) { 18059 mSettings.writeKernelMappingLPr(ps); 18060 } 18061 } 18062 // can downgrade to reader here 18063 if (writeSettings) { 18064 mSettings.writeLPr(); 18065 } 18066 } 18067 return true; 18068 } 18069 18070 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18071 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18072 PackageRemovedInfo outInfo, boolean writeSettings, 18073 PackageParser.Package replacingPackage) { 18074 synchronized (mPackages) { 18075 if (outInfo != null) { 18076 outInfo.uid = ps.appId; 18077 } 18078 18079 if (outInfo != null && outInfo.removedChildPackages != null) { 18080 final int childCount = (ps.childPackageNames != null) 18081 ? ps.childPackageNames.size() : 0; 18082 for (int i = 0; i < childCount; i++) { 18083 String childPackageName = ps.childPackageNames.get(i); 18084 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18085 if (childPs == null) { 18086 return false; 18087 } 18088 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18089 childPackageName); 18090 if (childInfo != null) { 18091 childInfo.uid = childPs.appId; 18092 } 18093 } 18094 } 18095 } 18096 18097 // Delete package data from internal structures and also remove data if flag is set 18098 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18099 18100 // Delete the child packages data 18101 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18102 for (int i = 0; i < childCount; i++) { 18103 PackageSetting childPs; 18104 synchronized (mPackages) { 18105 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18106 } 18107 if (childPs != null) { 18108 PackageRemovedInfo childOutInfo = (outInfo != null 18109 && outInfo.removedChildPackages != null) 18110 ? outInfo.removedChildPackages.get(childPs.name) : null; 18111 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18112 && (replacingPackage != null 18113 && !replacingPackage.hasChildPackage(childPs.name)) 18114 ? flags & ~DELETE_KEEP_DATA : flags; 18115 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18116 deleteFlags, writeSettings); 18117 } 18118 } 18119 18120 // Delete application code and resources only for parent packages 18121 if (ps.parentPackageName == null) { 18122 if (deleteCodeAndResources && (outInfo != null)) { 18123 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18124 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18125 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18126 } 18127 } 18128 18129 return true; 18130 } 18131 18132 @Override 18133 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18134 int userId) { 18135 mContext.enforceCallingOrSelfPermission( 18136 android.Manifest.permission.DELETE_PACKAGES, null); 18137 synchronized (mPackages) { 18138 PackageSetting ps = mSettings.mPackages.get(packageName); 18139 if (ps == null) { 18140 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 18141 return false; 18142 } 18143 // Cannot block uninstall of static shared libs as they are 18144 // considered a part of the using app (emulating static linking). 18145 // Also static libs are installed always on internal storage. 18146 PackageParser.Package pkg = mPackages.get(packageName); 18147 if (pkg != null && pkg.staticSharedLibName != null) { 18148 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18149 + " providing static shared library: " + pkg.staticSharedLibName); 18150 return false; 18151 } 18152 if (!ps.getInstalled(userId)) { 18153 // Can't block uninstall for an app that is not installed or enabled. 18154 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 18155 return false; 18156 } 18157 ps.setBlockUninstall(blockUninstall, userId); 18158 mSettings.writePackageRestrictionsLPr(userId); 18159 } 18160 return true; 18161 } 18162 18163 @Override 18164 public boolean getBlockUninstallForUser(String packageName, int userId) { 18165 synchronized (mPackages) { 18166 PackageSetting ps = mSettings.mPackages.get(packageName); 18167 if (ps == null) { 18168 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 18169 return false; 18170 } 18171 return ps.getBlockUninstall(userId); 18172 } 18173 } 18174 18175 @Override 18176 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18177 int callingUid = Binder.getCallingUid(); 18178 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 18179 throw new SecurityException( 18180 "setRequiredForSystemUser can only be run by the system or root"); 18181 } 18182 synchronized (mPackages) { 18183 PackageSetting ps = mSettings.mPackages.get(packageName); 18184 if (ps == null) { 18185 Log.w(TAG, "Package doesn't exist: " + packageName); 18186 return false; 18187 } 18188 if (systemUserApp) { 18189 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18190 } else { 18191 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18192 } 18193 mSettings.writeLPr(); 18194 } 18195 return true; 18196 } 18197 18198 /* 18199 * This method handles package deletion in general 18200 */ 18201 private boolean deletePackageLIF(String packageName, UserHandle user, 18202 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18203 PackageRemovedInfo outInfo, boolean writeSettings, 18204 PackageParser.Package replacingPackage) { 18205 if (packageName == null) { 18206 Slog.w(TAG, "Attempt to delete null packageName."); 18207 return false; 18208 } 18209 18210 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18211 18212 PackageSetting ps; 18213 synchronized (mPackages) { 18214 ps = mSettings.mPackages.get(packageName); 18215 if (ps == null) { 18216 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18217 return false; 18218 } 18219 18220 if (ps.parentPackageName != null && (!isSystemApp(ps) 18221 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18222 if (DEBUG_REMOVE) { 18223 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18224 + ((user == null) ? UserHandle.USER_ALL : user)); 18225 } 18226 final int removedUserId = (user != null) ? user.getIdentifier() 18227 : UserHandle.USER_ALL; 18228 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18229 return false; 18230 } 18231 markPackageUninstalledForUserLPw(ps, user); 18232 scheduleWritePackageRestrictionsLocked(user); 18233 return true; 18234 } 18235 } 18236 18237 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18238 && user.getIdentifier() != UserHandle.USER_ALL)) { 18239 // The caller is asking that the package only be deleted for a single 18240 // user. To do this, we just mark its uninstalled state and delete 18241 // its data. If this is a system app, we only allow this to happen if 18242 // they have set the special DELETE_SYSTEM_APP which requests different 18243 // semantics than normal for uninstalling system apps. 18244 markPackageUninstalledForUserLPw(ps, user); 18245 18246 if (!isSystemApp(ps)) { 18247 // Do not uninstall the APK if an app should be cached 18248 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18249 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18250 // Other user still have this package installed, so all 18251 // we need to do is clear this user's data and save that 18252 // it is uninstalled. 18253 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18254 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18255 return false; 18256 } 18257 scheduleWritePackageRestrictionsLocked(user); 18258 return true; 18259 } else { 18260 // We need to set it back to 'installed' so the uninstall 18261 // broadcasts will be sent correctly. 18262 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18263 ps.setInstalled(true, user.getIdentifier()); 18264 mSettings.writeKernelMappingLPr(ps); 18265 } 18266 } else { 18267 // This is a system app, so we assume that the 18268 // other users still have this package installed, so all 18269 // we need to do is clear this user's data and save that 18270 // it is uninstalled. 18271 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18272 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18273 return false; 18274 } 18275 scheduleWritePackageRestrictionsLocked(user); 18276 return true; 18277 } 18278 } 18279 18280 // If we are deleting a composite package for all users, keep track 18281 // of result for each child. 18282 if (ps.childPackageNames != null && outInfo != null) { 18283 synchronized (mPackages) { 18284 final int childCount = ps.childPackageNames.size(); 18285 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18286 for (int i = 0; i < childCount; i++) { 18287 String childPackageName = ps.childPackageNames.get(i); 18288 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 18289 childInfo.removedPackage = childPackageName; 18290 outInfo.removedChildPackages.put(childPackageName, childInfo); 18291 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18292 if (childPs != null) { 18293 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18294 } 18295 } 18296 } 18297 } 18298 18299 boolean ret = false; 18300 if (isSystemApp(ps)) { 18301 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18302 // When an updated system application is deleted we delete the existing resources 18303 // as well and fall back to existing code in system partition 18304 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18305 } else { 18306 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18307 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18308 outInfo, writeSettings, replacingPackage); 18309 } 18310 18311 // Take a note whether we deleted the package for all users 18312 if (outInfo != null) { 18313 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18314 if (outInfo.removedChildPackages != null) { 18315 synchronized (mPackages) { 18316 final int childCount = outInfo.removedChildPackages.size(); 18317 for (int i = 0; i < childCount; i++) { 18318 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18319 if (childInfo != null) { 18320 childInfo.removedForAllUsers = mPackages.get( 18321 childInfo.removedPackage) == null; 18322 } 18323 } 18324 } 18325 } 18326 // If we uninstalled an update to a system app there may be some 18327 // child packages that appeared as they are declared in the system 18328 // app but were not declared in the update. 18329 if (isSystemApp(ps)) { 18330 synchronized (mPackages) { 18331 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18332 final int childCount = (updatedPs.childPackageNames != null) 18333 ? updatedPs.childPackageNames.size() : 0; 18334 for (int i = 0; i < childCount; i++) { 18335 String childPackageName = updatedPs.childPackageNames.get(i); 18336 if (outInfo.removedChildPackages == null 18337 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18338 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18339 if (childPs == null) { 18340 continue; 18341 } 18342 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18343 installRes.name = childPackageName; 18344 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18345 installRes.pkg = mPackages.get(childPackageName); 18346 installRes.uid = childPs.pkg.applicationInfo.uid; 18347 if (outInfo.appearedChildPackages == null) { 18348 outInfo.appearedChildPackages = new ArrayMap<>(); 18349 } 18350 outInfo.appearedChildPackages.put(childPackageName, installRes); 18351 } 18352 } 18353 } 18354 } 18355 } 18356 18357 return ret; 18358 } 18359 18360 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18361 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18362 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18363 for (int nextUserId : userIds) { 18364 if (DEBUG_REMOVE) { 18365 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18366 } 18367 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18368 false /*installed*/, 18369 true /*stopped*/, 18370 true /*notLaunched*/, 18371 false /*hidden*/, 18372 false /*suspended*/, 18373 false /*instantApp*/, 18374 null /*lastDisableAppCaller*/, 18375 null /*enabledComponents*/, 18376 null /*disabledComponents*/, 18377 false /*blockUninstall*/, 18378 ps.readUserState(nextUserId).domainVerificationStatus, 18379 0, PackageManager.INSTALL_REASON_UNKNOWN); 18380 } 18381 mSettings.writeKernelMappingLPr(ps); 18382 } 18383 18384 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18385 PackageRemovedInfo outInfo) { 18386 final PackageParser.Package pkg; 18387 synchronized (mPackages) { 18388 pkg = mPackages.get(ps.name); 18389 } 18390 18391 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18392 : new int[] {userId}; 18393 for (int nextUserId : userIds) { 18394 if (DEBUG_REMOVE) { 18395 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18396 + nextUserId); 18397 } 18398 18399 destroyAppDataLIF(pkg, userId, 18400 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18401 destroyAppProfilesLIF(pkg, userId); 18402 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18403 schedulePackageCleaning(ps.name, nextUserId, false); 18404 synchronized (mPackages) { 18405 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18406 scheduleWritePackageRestrictionsLocked(nextUserId); 18407 } 18408 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18409 } 18410 } 18411 18412 if (outInfo != null) { 18413 outInfo.removedPackage = ps.name; 18414 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18415 outInfo.removedAppId = ps.appId; 18416 outInfo.removedUsers = userIds; 18417 } 18418 18419 return true; 18420 } 18421 18422 private final class ClearStorageConnection implements ServiceConnection { 18423 IMediaContainerService mContainerService; 18424 18425 @Override 18426 public void onServiceConnected(ComponentName name, IBinder service) { 18427 synchronized (this) { 18428 mContainerService = IMediaContainerService.Stub 18429 .asInterface(Binder.allowBlocking(service)); 18430 notifyAll(); 18431 } 18432 } 18433 18434 @Override 18435 public void onServiceDisconnected(ComponentName name) { 18436 } 18437 } 18438 18439 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18440 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18441 18442 final boolean mounted; 18443 if (Environment.isExternalStorageEmulated()) { 18444 mounted = true; 18445 } else { 18446 final String status = Environment.getExternalStorageState(); 18447 18448 mounted = status.equals(Environment.MEDIA_MOUNTED) 18449 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18450 } 18451 18452 if (!mounted) { 18453 return; 18454 } 18455 18456 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18457 int[] users; 18458 if (userId == UserHandle.USER_ALL) { 18459 users = sUserManager.getUserIds(); 18460 } else { 18461 users = new int[] { userId }; 18462 } 18463 final ClearStorageConnection conn = new ClearStorageConnection(); 18464 if (mContext.bindServiceAsUser( 18465 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18466 try { 18467 for (int curUser : users) { 18468 long timeout = SystemClock.uptimeMillis() + 5000; 18469 synchronized (conn) { 18470 long now; 18471 while (conn.mContainerService == null && 18472 (now = SystemClock.uptimeMillis()) < timeout) { 18473 try { 18474 conn.wait(timeout - now); 18475 } catch (InterruptedException e) { 18476 } 18477 } 18478 } 18479 if (conn.mContainerService == null) { 18480 return; 18481 } 18482 18483 final UserEnvironment userEnv = new UserEnvironment(curUser); 18484 clearDirectory(conn.mContainerService, 18485 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18486 if (allData) { 18487 clearDirectory(conn.mContainerService, 18488 userEnv.buildExternalStorageAppDataDirs(packageName)); 18489 clearDirectory(conn.mContainerService, 18490 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18491 } 18492 } 18493 } finally { 18494 mContext.unbindService(conn); 18495 } 18496 } 18497 } 18498 18499 @Override 18500 public void clearApplicationProfileData(String packageName) { 18501 enforceSystemOrRoot("Only the system can clear all profile data"); 18502 18503 final PackageParser.Package pkg; 18504 synchronized (mPackages) { 18505 pkg = mPackages.get(packageName); 18506 } 18507 18508 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18509 synchronized (mInstallLock) { 18510 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18511 } 18512 } 18513 } 18514 18515 @Override 18516 public void clearApplicationUserData(final String packageName, 18517 final IPackageDataObserver observer, final int userId) { 18518 mContext.enforceCallingOrSelfPermission( 18519 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18520 18521 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18522 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18523 18524 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18525 throw new SecurityException("Cannot clear data for a protected package: " 18526 + packageName); 18527 } 18528 // Queue up an async operation since the package deletion may take a little while. 18529 mHandler.post(new Runnable() { 18530 public void run() { 18531 mHandler.removeCallbacks(this); 18532 final boolean succeeded; 18533 try (PackageFreezer freezer = freezePackage(packageName, 18534 "clearApplicationUserData")) { 18535 synchronized (mInstallLock) { 18536 succeeded = clearApplicationUserDataLIF(packageName, userId); 18537 } 18538 clearExternalStorageDataSync(packageName, userId, true); 18539 synchronized (mPackages) { 18540 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18541 packageName, userId); 18542 } 18543 } 18544 if (succeeded) { 18545 // invoke DeviceStorageMonitor's update method to clear any notifications 18546 DeviceStorageMonitorInternal dsm = LocalServices 18547 .getService(DeviceStorageMonitorInternal.class); 18548 if (dsm != null) { 18549 dsm.checkMemory(); 18550 } 18551 } 18552 if(observer != null) { 18553 try { 18554 observer.onRemoveCompleted(packageName, succeeded); 18555 } catch (RemoteException e) { 18556 Log.i(TAG, "Observer no longer exists."); 18557 } 18558 } //end if observer 18559 } //end run 18560 }); 18561 } 18562 18563 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18564 if (packageName == null) { 18565 Slog.w(TAG, "Attempt to delete null packageName."); 18566 return false; 18567 } 18568 18569 // Try finding details about the requested package 18570 PackageParser.Package pkg; 18571 synchronized (mPackages) { 18572 pkg = mPackages.get(packageName); 18573 if (pkg == null) { 18574 final PackageSetting ps = mSettings.mPackages.get(packageName); 18575 if (ps != null) { 18576 pkg = ps.pkg; 18577 } 18578 } 18579 18580 if (pkg == null) { 18581 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18582 return false; 18583 } 18584 18585 PackageSetting ps = (PackageSetting) pkg.mExtras; 18586 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18587 } 18588 18589 clearAppDataLIF(pkg, userId, 18590 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18591 18592 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18593 removeKeystoreDataIfNeeded(userId, appId); 18594 18595 UserManagerInternal umInternal = getUserManagerInternal(); 18596 final int flags; 18597 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18598 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18599 } else if (umInternal.isUserRunning(userId)) { 18600 flags = StorageManager.FLAG_STORAGE_DE; 18601 } else { 18602 flags = 0; 18603 } 18604 prepareAppDataContentsLIF(pkg, userId, flags); 18605 18606 return true; 18607 } 18608 18609 /** 18610 * Reverts user permission state changes (permissions and flags) in 18611 * all packages for a given user. 18612 * 18613 * @param userId The device user for which to do a reset. 18614 */ 18615 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18616 final int packageCount = mPackages.size(); 18617 for (int i = 0; i < packageCount; i++) { 18618 PackageParser.Package pkg = mPackages.valueAt(i); 18619 PackageSetting ps = (PackageSetting) pkg.mExtras; 18620 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18621 } 18622 } 18623 18624 private void resetNetworkPolicies(int userId) { 18625 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18626 } 18627 18628 /** 18629 * Reverts user permission state changes (permissions and flags). 18630 * 18631 * @param ps The package for which to reset. 18632 * @param userId The device user for which to do a reset. 18633 */ 18634 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18635 final PackageSetting ps, final int userId) { 18636 if (ps.pkg == null) { 18637 return; 18638 } 18639 18640 // These are flags that can change base on user actions. 18641 final int userSettableMask = FLAG_PERMISSION_USER_SET 18642 | FLAG_PERMISSION_USER_FIXED 18643 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18644 | FLAG_PERMISSION_REVIEW_REQUIRED; 18645 18646 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18647 | FLAG_PERMISSION_POLICY_FIXED; 18648 18649 boolean writeInstallPermissions = false; 18650 boolean writeRuntimePermissions = false; 18651 18652 final int permissionCount = ps.pkg.requestedPermissions.size(); 18653 for (int i = 0; i < permissionCount; i++) { 18654 String permission = ps.pkg.requestedPermissions.get(i); 18655 18656 BasePermission bp = mSettings.mPermissions.get(permission); 18657 if (bp == null) { 18658 continue; 18659 } 18660 18661 // If shared user we just reset the state to which only this app contributed. 18662 if (ps.sharedUser != null) { 18663 boolean used = false; 18664 final int packageCount = ps.sharedUser.packages.size(); 18665 for (int j = 0; j < packageCount; j++) { 18666 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18667 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18668 && pkg.pkg.requestedPermissions.contains(permission)) { 18669 used = true; 18670 break; 18671 } 18672 } 18673 if (used) { 18674 continue; 18675 } 18676 } 18677 18678 PermissionsState permissionsState = ps.getPermissionsState(); 18679 18680 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 18681 18682 // Always clear the user settable flags. 18683 final boolean hasInstallState = permissionsState.getInstallPermissionState( 18684 bp.name) != null; 18685 // If permission review is enabled and this is a legacy app, mark the 18686 // permission as requiring a review as this is the initial state. 18687 int flags = 0; 18688 if (mPermissionReviewRequired 18689 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18690 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18691 } 18692 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18693 if (hasInstallState) { 18694 writeInstallPermissions = true; 18695 } else { 18696 writeRuntimePermissions = true; 18697 } 18698 } 18699 18700 // Below is only runtime permission handling. 18701 if (!bp.isRuntime()) { 18702 continue; 18703 } 18704 18705 // Never clobber system or policy. 18706 if ((oldFlags & policyOrSystemFlags) != 0) { 18707 continue; 18708 } 18709 18710 // If this permission was granted by default, make sure it is. 18711 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18712 if (permissionsState.grantRuntimePermission(bp, userId) 18713 != PERMISSION_OPERATION_FAILURE) { 18714 writeRuntimePermissions = true; 18715 } 18716 // If permission review is enabled the permissions for a legacy apps 18717 // are represented as constantly granted runtime ones, so don't revoke. 18718 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18719 // Otherwise, reset the permission. 18720 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18721 switch (revokeResult) { 18722 case PERMISSION_OPERATION_SUCCESS: 18723 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18724 writeRuntimePermissions = true; 18725 final int appId = ps.appId; 18726 mHandler.post(new Runnable() { 18727 @Override 18728 public void run() { 18729 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18730 } 18731 }); 18732 } break; 18733 } 18734 } 18735 } 18736 18737 // Synchronously write as we are taking permissions away. 18738 if (writeRuntimePermissions) { 18739 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18740 } 18741 18742 // Synchronously write as we are taking permissions away. 18743 if (writeInstallPermissions) { 18744 mSettings.writeLPr(); 18745 } 18746 } 18747 18748 /** 18749 * Remove entries from the keystore daemon. Will only remove it if the 18750 * {@code appId} is valid. 18751 */ 18752 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18753 if (appId < 0) { 18754 return; 18755 } 18756 18757 final KeyStore keyStore = KeyStore.getInstance(); 18758 if (keyStore != null) { 18759 if (userId == UserHandle.USER_ALL) { 18760 for (final int individual : sUserManager.getUserIds()) { 18761 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18762 } 18763 } else { 18764 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18765 } 18766 } else { 18767 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18768 } 18769 } 18770 18771 @Override 18772 public void deleteApplicationCacheFiles(final String packageName, 18773 final IPackageDataObserver observer) { 18774 final int userId = UserHandle.getCallingUserId(); 18775 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18776 } 18777 18778 @Override 18779 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18780 final IPackageDataObserver observer) { 18781 mContext.enforceCallingOrSelfPermission( 18782 android.Manifest.permission.DELETE_CACHE_FILES, null); 18783 enforceCrossUserPermission(Binder.getCallingUid(), userId, 18784 /* requireFullPermission= */ true, /* checkShell= */ false, 18785 "delete application cache files"); 18786 18787 final PackageParser.Package pkg; 18788 synchronized (mPackages) { 18789 pkg = mPackages.get(packageName); 18790 } 18791 18792 // Queue up an async operation since the package deletion may take a little while. 18793 mHandler.post(new Runnable() { 18794 public void run() { 18795 synchronized (mInstallLock) { 18796 final int flags = StorageManager.FLAG_STORAGE_DE 18797 | StorageManager.FLAG_STORAGE_CE; 18798 // We're only clearing cache files, so we don't care if the 18799 // app is unfrozen and still able to run 18800 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18801 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18802 } 18803 clearExternalStorageDataSync(packageName, userId, false); 18804 if (observer != null) { 18805 try { 18806 observer.onRemoveCompleted(packageName, true); 18807 } catch (RemoteException e) { 18808 Log.i(TAG, "Observer no longer exists."); 18809 } 18810 } 18811 } 18812 }); 18813 } 18814 18815 @Override 18816 public void getPackageSizeInfo(final String packageName, int userHandle, 18817 final IPackageStatsObserver observer) { 18818 throw new UnsupportedOperationException( 18819 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18820 } 18821 18822 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18823 final PackageSetting ps; 18824 synchronized (mPackages) { 18825 ps = mSettings.mPackages.get(packageName); 18826 if (ps == null) { 18827 Slog.w(TAG, "Failed to find settings for " + packageName); 18828 return false; 18829 } 18830 } 18831 18832 final String[] packageNames = { packageName }; 18833 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18834 final String[] codePaths = { ps.codePathString }; 18835 18836 try { 18837 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18838 ps.appId, ceDataInodes, codePaths, stats); 18839 18840 // For now, ignore code size of packages on system partition 18841 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18842 stats.codeSize = 0; 18843 } 18844 18845 // External clients expect these to be tracked separately 18846 stats.dataSize -= stats.cacheSize; 18847 18848 } catch (InstallerException e) { 18849 Slog.w(TAG, String.valueOf(e)); 18850 return false; 18851 } 18852 18853 return true; 18854 } 18855 18856 private int getUidTargetSdkVersionLockedLPr(int uid) { 18857 Object obj = mSettings.getUserIdLPr(uid); 18858 if (obj instanceof SharedUserSetting) { 18859 final SharedUserSetting sus = (SharedUserSetting) obj; 18860 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18861 final Iterator<PackageSetting> it = sus.packages.iterator(); 18862 while (it.hasNext()) { 18863 final PackageSetting ps = it.next(); 18864 if (ps.pkg != null) { 18865 int v = ps.pkg.applicationInfo.targetSdkVersion; 18866 if (v < vers) vers = v; 18867 } 18868 } 18869 return vers; 18870 } else if (obj instanceof PackageSetting) { 18871 final PackageSetting ps = (PackageSetting) obj; 18872 if (ps.pkg != null) { 18873 return ps.pkg.applicationInfo.targetSdkVersion; 18874 } 18875 } 18876 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18877 } 18878 18879 @Override 18880 public void addPreferredActivity(IntentFilter filter, int match, 18881 ComponentName[] set, ComponentName activity, int userId) { 18882 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18883 "Adding preferred"); 18884 } 18885 18886 private void addPreferredActivityInternal(IntentFilter filter, int match, 18887 ComponentName[] set, ComponentName activity, boolean always, int userId, 18888 String opname) { 18889 // writer 18890 int callingUid = Binder.getCallingUid(); 18891 enforceCrossUserPermission(callingUid, userId, 18892 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18893 if (filter.countActions() == 0) { 18894 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18895 return; 18896 } 18897 synchronized (mPackages) { 18898 if (mContext.checkCallingOrSelfPermission( 18899 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18900 != PackageManager.PERMISSION_GRANTED) { 18901 if (getUidTargetSdkVersionLockedLPr(callingUid) 18902 < Build.VERSION_CODES.FROYO) { 18903 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18904 + callingUid); 18905 return; 18906 } 18907 mContext.enforceCallingOrSelfPermission( 18908 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18909 } 18910 18911 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18912 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18913 + userId + ":"); 18914 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18915 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18916 scheduleWritePackageRestrictionsLocked(userId); 18917 postPreferredActivityChangedBroadcast(userId); 18918 } 18919 } 18920 18921 private void postPreferredActivityChangedBroadcast(int userId) { 18922 mHandler.post(() -> { 18923 final IActivityManager am = ActivityManager.getService(); 18924 if (am == null) { 18925 return; 18926 } 18927 18928 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18929 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18930 try { 18931 am.broadcastIntent(null, intent, null, null, 18932 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18933 null, false, false, userId); 18934 } catch (RemoteException e) { 18935 } 18936 }); 18937 } 18938 18939 @Override 18940 public void replacePreferredActivity(IntentFilter filter, int match, 18941 ComponentName[] set, ComponentName activity, int userId) { 18942 if (filter.countActions() != 1) { 18943 throw new IllegalArgumentException( 18944 "replacePreferredActivity expects filter to have only 1 action."); 18945 } 18946 if (filter.countDataAuthorities() != 0 18947 || filter.countDataPaths() != 0 18948 || filter.countDataSchemes() > 1 18949 || filter.countDataTypes() != 0) { 18950 throw new IllegalArgumentException( 18951 "replacePreferredActivity expects filter to have no data authorities, " + 18952 "paths, or types; and at most one scheme."); 18953 } 18954 18955 final int callingUid = Binder.getCallingUid(); 18956 enforceCrossUserPermission(callingUid, userId, 18957 true /* requireFullPermission */, false /* checkShell */, 18958 "replace preferred activity"); 18959 synchronized (mPackages) { 18960 if (mContext.checkCallingOrSelfPermission( 18961 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18962 != PackageManager.PERMISSION_GRANTED) { 18963 if (getUidTargetSdkVersionLockedLPr(callingUid) 18964 < Build.VERSION_CODES.FROYO) { 18965 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18966 + Binder.getCallingUid()); 18967 return; 18968 } 18969 mContext.enforceCallingOrSelfPermission( 18970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18971 } 18972 18973 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18974 if (pir != null) { 18975 // Get all of the existing entries that exactly match this filter. 18976 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18977 if (existing != null && existing.size() == 1) { 18978 PreferredActivity cur = existing.get(0); 18979 if (DEBUG_PREFERRED) { 18980 Slog.i(TAG, "Checking replace of preferred:"); 18981 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18982 if (!cur.mPref.mAlways) { 18983 Slog.i(TAG, " -- CUR; not mAlways!"); 18984 } else { 18985 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18986 Slog.i(TAG, " -- CUR: mSet=" 18987 + Arrays.toString(cur.mPref.mSetComponents)); 18988 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18989 Slog.i(TAG, " -- NEW: mMatch=" 18990 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18991 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18992 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18993 } 18994 } 18995 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18996 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18997 && cur.mPref.sameSet(set)) { 18998 // Setting the preferred activity to what it happens to be already 18999 if (DEBUG_PREFERRED) { 19000 Slog.i(TAG, "Replacing with same preferred activity " 19001 + cur.mPref.mShortComponent + " for user " 19002 + userId + ":"); 19003 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19004 } 19005 return; 19006 } 19007 } 19008 19009 if (existing != null) { 19010 if (DEBUG_PREFERRED) { 19011 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19012 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19013 } 19014 for (int i = 0; i < existing.size(); i++) { 19015 PreferredActivity pa = existing.get(i); 19016 if (DEBUG_PREFERRED) { 19017 Slog.i(TAG, "Removing existing preferred activity " 19018 + pa.mPref.mComponent + ":"); 19019 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19020 } 19021 pir.removeFilter(pa); 19022 } 19023 } 19024 } 19025 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19026 "Replacing preferred"); 19027 } 19028 } 19029 19030 @Override 19031 public void clearPackagePreferredActivities(String packageName) { 19032 final int uid = Binder.getCallingUid(); 19033 // writer 19034 synchronized (mPackages) { 19035 PackageParser.Package pkg = mPackages.get(packageName); 19036 if (pkg == null || pkg.applicationInfo.uid != uid) { 19037 if (mContext.checkCallingOrSelfPermission( 19038 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19039 != PackageManager.PERMISSION_GRANTED) { 19040 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 19041 < Build.VERSION_CODES.FROYO) { 19042 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19043 + Binder.getCallingUid()); 19044 return; 19045 } 19046 mContext.enforceCallingOrSelfPermission( 19047 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19048 } 19049 } 19050 19051 int user = UserHandle.getCallingUserId(); 19052 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19053 scheduleWritePackageRestrictionsLocked(user); 19054 } 19055 } 19056 } 19057 19058 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19059 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19060 ArrayList<PreferredActivity> removed = null; 19061 boolean changed = false; 19062 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19063 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19064 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19065 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19066 continue; 19067 } 19068 Iterator<PreferredActivity> it = pir.filterIterator(); 19069 while (it.hasNext()) { 19070 PreferredActivity pa = it.next(); 19071 // Mark entry for removal only if it matches the package name 19072 // and the entry is of type "always". 19073 if (packageName == null || 19074 (pa.mPref.mComponent.getPackageName().equals(packageName) 19075 && pa.mPref.mAlways)) { 19076 if (removed == null) { 19077 removed = new ArrayList<PreferredActivity>(); 19078 } 19079 removed.add(pa); 19080 } 19081 } 19082 if (removed != null) { 19083 for (int j=0; j<removed.size(); j++) { 19084 PreferredActivity pa = removed.get(j); 19085 pir.removeFilter(pa); 19086 } 19087 changed = true; 19088 } 19089 } 19090 if (changed) { 19091 postPreferredActivityChangedBroadcast(userId); 19092 } 19093 return changed; 19094 } 19095 19096 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19097 private void clearIntentFilterVerificationsLPw(int userId) { 19098 final int packageCount = mPackages.size(); 19099 for (int i = 0; i < packageCount; i++) { 19100 PackageParser.Package pkg = mPackages.valueAt(i); 19101 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19102 } 19103 } 19104 19105 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19106 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19107 if (userId == UserHandle.USER_ALL) { 19108 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19109 sUserManager.getUserIds())) { 19110 for (int oneUserId : sUserManager.getUserIds()) { 19111 scheduleWritePackageRestrictionsLocked(oneUserId); 19112 } 19113 } 19114 } else { 19115 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19116 scheduleWritePackageRestrictionsLocked(userId); 19117 } 19118 } 19119 } 19120 19121 void clearDefaultBrowserIfNeeded(String packageName) { 19122 for (int oneUserId : sUserManager.getUserIds()) { 19123 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 19124 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 19125 if (packageName.equals(defaultBrowserPackageName)) { 19126 setDefaultBrowserPackageName(null, oneUserId); 19127 } 19128 } 19129 } 19130 19131 @Override 19132 public void resetApplicationPreferences(int userId) { 19133 mContext.enforceCallingOrSelfPermission( 19134 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19135 final long identity = Binder.clearCallingIdentity(); 19136 // writer 19137 try { 19138 synchronized (mPackages) { 19139 clearPackagePreferredActivitiesLPw(null, userId); 19140 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19141 // TODO: We have to reset the default SMS and Phone. This requires 19142 // significant refactoring to keep all default apps in the package 19143 // manager (cleaner but more work) or have the services provide 19144 // callbacks to the package manager to request a default app reset. 19145 applyFactoryDefaultBrowserLPw(userId); 19146 clearIntentFilterVerificationsLPw(userId); 19147 primeDomainVerificationsLPw(userId); 19148 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19149 scheduleWritePackageRestrictionsLocked(userId); 19150 } 19151 resetNetworkPolicies(userId); 19152 } finally { 19153 Binder.restoreCallingIdentity(identity); 19154 } 19155 } 19156 19157 @Override 19158 public int getPreferredActivities(List<IntentFilter> outFilters, 19159 List<ComponentName> outActivities, String packageName) { 19160 19161 int num = 0; 19162 final int userId = UserHandle.getCallingUserId(); 19163 // reader 19164 synchronized (mPackages) { 19165 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19166 if (pir != null) { 19167 final Iterator<PreferredActivity> it = pir.filterIterator(); 19168 while (it.hasNext()) { 19169 final PreferredActivity pa = it.next(); 19170 if (packageName == null 19171 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19172 && pa.mPref.mAlways)) { 19173 if (outFilters != null) { 19174 outFilters.add(new IntentFilter(pa)); 19175 } 19176 if (outActivities != null) { 19177 outActivities.add(pa.mPref.mComponent); 19178 } 19179 } 19180 } 19181 } 19182 } 19183 19184 return num; 19185 } 19186 19187 @Override 19188 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19189 int userId) { 19190 int callingUid = Binder.getCallingUid(); 19191 if (callingUid != Process.SYSTEM_UID) { 19192 throw new SecurityException( 19193 "addPersistentPreferredActivity can only be run by the system"); 19194 } 19195 if (filter.countActions() == 0) { 19196 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19197 return; 19198 } 19199 synchronized (mPackages) { 19200 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19201 ":"); 19202 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19203 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19204 new PersistentPreferredActivity(filter, activity)); 19205 scheduleWritePackageRestrictionsLocked(userId); 19206 postPreferredActivityChangedBroadcast(userId); 19207 } 19208 } 19209 19210 @Override 19211 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19212 int callingUid = Binder.getCallingUid(); 19213 if (callingUid != Process.SYSTEM_UID) { 19214 throw new SecurityException( 19215 "clearPackagePersistentPreferredActivities can only be run by the system"); 19216 } 19217 ArrayList<PersistentPreferredActivity> removed = null; 19218 boolean changed = false; 19219 synchronized (mPackages) { 19220 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19221 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19222 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19223 .valueAt(i); 19224 if (userId != thisUserId) { 19225 continue; 19226 } 19227 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19228 while (it.hasNext()) { 19229 PersistentPreferredActivity ppa = it.next(); 19230 // Mark entry for removal only if it matches the package name. 19231 if (ppa.mComponent.getPackageName().equals(packageName)) { 19232 if (removed == null) { 19233 removed = new ArrayList<PersistentPreferredActivity>(); 19234 } 19235 removed.add(ppa); 19236 } 19237 } 19238 if (removed != null) { 19239 for (int j=0; j<removed.size(); j++) { 19240 PersistentPreferredActivity ppa = removed.get(j); 19241 ppir.removeFilter(ppa); 19242 } 19243 changed = true; 19244 } 19245 } 19246 19247 if (changed) { 19248 scheduleWritePackageRestrictionsLocked(userId); 19249 postPreferredActivityChangedBroadcast(userId); 19250 } 19251 } 19252 } 19253 19254 /** 19255 * Common machinery for picking apart a restored XML blob and passing 19256 * it to a caller-supplied functor to be applied to the running system. 19257 */ 19258 private void restoreFromXml(XmlPullParser parser, int userId, 19259 String expectedStartTag, BlobXmlRestorer functor) 19260 throws IOException, XmlPullParserException { 19261 int type; 19262 while ((type = parser.next()) != XmlPullParser.START_TAG 19263 && type != XmlPullParser.END_DOCUMENT) { 19264 } 19265 if (type != XmlPullParser.START_TAG) { 19266 // oops didn't find a start tag?! 19267 if (DEBUG_BACKUP) { 19268 Slog.e(TAG, "Didn't find start tag during restore"); 19269 } 19270 return; 19271 } 19272Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19273 // this is supposed to be TAG_PREFERRED_BACKUP 19274 if (!expectedStartTag.equals(parser.getName())) { 19275 if (DEBUG_BACKUP) { 19276 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19277 } 19278 return; 19279 } 19280 19281 // skip interfering stuff, then we're aligned with the backing implementation 19282 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19283Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19284 functor.apply(parser, userId); 19285 } 19286 19287 private interface BlobXmlRestorer { 19288 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19289 } 19290 19291 /** 19292 * Non-Binder method, support for the backup/restore mechanism: write the 19293 * full set of preferred activities in its canonical XML format. Returns the 19294 * XML output as a byte array, or null if there is none. 19295 */ 19296 @Override 19297 public byte[] getPreferredActivityBackup(int userId) { 19298 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19299 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19300 } 19301 19302 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19303 try { 19304 final XmlSerializer serializer = new FastXmlSerializer(); 19305 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19306 serializer.startDocument(null, true); 19307 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19308 19309 synchronized (mPackages) { 19310 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19311 } 19312 19313 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19314 serializer.endDocument(); 19315 serializer.flush(); 19316 } catch (Exception e) { 19317 if (DEBUG_BACKUP) { 19318 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19319 } 19320 return null; 19321 } 19322 19323 return dataStream.toByteArray(); 19324 } 19325 19326 @Override 19327 public void restorePreferredActivities(byte[] backup, int userId) { 19328 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19329 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19330 } 19331 19332 try { 19333 final XmlPullParser parser = Xml.newPullParser(); 19334 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19335 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19336 new BlobXmlRestorer() { 19337 @Override 19338 public void apply(XmlPullParser parser, int userId) 19339 throws XmlPullParserException, IOException { 19340 synchronized (mPackages) { 19341 mSettings.readPreferredActivitiesLPw(parser, userId); 19342 } 19343 } 19344 } ); 19345 } catch (Exception e) { 19346 if (DEBUG_BACKUP) { 19347 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19348 } 19349 } 19350 } 19351 19352 /** 19353 * Non-Binder method, support for the backup/restore mechanism: write the 19354 * default browser (etc) settings in its canonical XML format. Returns the default 19355 * browser XML representation as a byte array, or null if there is none. 19356 */ 19357 @Override 19358 public byte[] getDefaultAppsBackup(int userId) { 19359 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19360 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19361 } 19362 19363 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19364 try { 19365 final XmlSerializer serializer = new FastXmlSerializer(); 19366 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19367 serializer.startDocument(null, true); 19368 serializer.startTag(null, TAG_DEFAULT_APPS); 19369 19370 synchronized (mPackages) { 19371 mSettings.writeDefaultAppsLPr(serializer, userId); 19372 } 19373 19374 serializer.endTag(null, TAG_DEFAULT_APPS); 19375 serializer.endDocument(); 19376 serializer.flush(); 19377 } catch (Exception e) { 19378 if (DEBUG_BACKUP) { 19379 Slog.e(TAG, "Unable to write default apps for backup", e); 19380 } 19381 return null; 19382 } 19383 19384 return dataStream.toByteArray(); 19385 } 19386 19387 @Override 19388 public void restoreDefaultApps(byte[] backup, int userId) { 19389 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19390 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19391 } 19392 19393 try { 19394 final XmlPullParser parser = Xml.newPullParser(); 19395 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19396 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19397 new BlobXmlRestorer() { 19398 @Override 19399 public void apply(XmlPullParser parser, int userId) 19400 throws XmlPullParserException, IOException { 19401 synchronized (mPackages) { 19402 mSettings.readDefaultAppsLPw(parser, userId); 19403 } 19404 } 19405 } ); 19406 } catch (Exception e) { 19407 if (DEBUG_BACKUP) { 19408 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19409 } 19410 } 19411 } 19412 19413 @Override 19414 public byte[] getIntentFilterVerificationBackup(int userId) { 19415 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19416 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19417 } 19418 19419 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19420 try { 19421 final XmlSerializer serializer = new FastXmlSerializer(); 19422 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19423 serializer.startDocument(null, true); 19424 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19425 19426 synchronized (mPackages) { 19427 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19428 } 19429 19430 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19431 serializer.endDocument(); 19432 serializer.flush(); 19433 } catch (Exception e) { 19434 if (DEBUG_BACKUP) { 19435 Slog.e(TAG, "Unable to write default apps for backup", e); 19436 } 19437 return null; 19438 } 19439 19440 return dataStream.toByteArray(); 19441 } 19442 19443 @Override 19444 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19445 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19446 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19447 } 19448 19449 try { 19450 final XmlPullParser parser = Xml.newPullParser(); 19451 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19452 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19453 new BlobXmlRestorer() { 19454 @Override 19455 public void apply(XmlPullParser parser, int userId) 19456 throws XmlPullParserException, IOException { 19457 synchronized (mPackages) { 19458 mSettings.readAllDomainVerificationsLPr(parser, userId); 19459 mSettings.writeLPr(); 19460 } 19461 } 19462 } ); 19463 } catch (Exception e) { 19464 if (DEBUG_BACKUP) { 19465 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19466 } 19467 } 19468 } 19469 19470 @Override 19471 public byte[] getPermissionGrantBackup(int userId) { 19472 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19473 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19474 } 19475 19476 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19477 try { 19478 final XmlSerializer serializer = new FastXmlSerializer(); 19479 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19480 serializer.startDocument(null, true); 19481 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19482 19483 synchronized (mPackages) { 19484 serializeRuntimePermissionGrantsLPr(serializer, userId); 19485 } 19486 19487 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19488 serializer.endDocument(); 19489 serializer.flush(); 19490 } catch (Exception e) { 19491 if (DEBUG_BACKUP) { 19492 Slog.e(TAG, "Unable to write default apps for backup", e); 19493 } 19494 return null; 19495 } 19496 19497 return dataStream.toByteArray(); 19498 } 19499 19500 @Override 19501 public void restorePermissionGrants(byte[] backup, int userId) { 19502 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19503 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19504 } 19505 19506 try { 19507 final XmlPullParser parser = Xml.newPullParser(); 19508 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19509 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19510 new BlobXmlRestorer() { 19511 @Override 19512 public void apply(XmlPullParser parser, int userId) 19513 throws XmlPullParserException, IOException { 19514 synchronized (mPackages) { 19515 processRestoredPermissionGrantsLPr(parser, userId); 19516 } 19517 } 19518 } ); 19519 } catch (Exception e) { 19520 if (DEBUG_BACKUP) { 19521 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19522 } 19523 } 19524 } 19525 19526 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19527 throws IOException { 19528 serializer.startTag(null, TAG_ALL_GRANTS); 19529 19530 final int N = mSettings.mPackages.size(); 19531 for (int i = 0; i < N; i++) { 19532 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19533 boolean pkgGrantsKnown = false; 19534 19535 PermissionsState packagePerms = ps.getPermissionsState(); 19536 19537 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19538 final int grantFlags = state.getFlags(); 19539 // only look at grants that are not system/policy fixed 19540 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19541 final boolean isGranted = state.isGranted(); 19542 // And only back up the user-twiddled state bits 19543 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19544 final String packageName = mSettings.mPackages.keyAt(i); 19545 if (!pkgGrantsKnown) { 19546 serializer.startTag(null, TAG_GRANT); 19547 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19548 pkgGrantsKnown = true; 19549 } 19550 19551 final boolean userSet = 19552 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19553 final boolean userFixed = 19554 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19555 final boolean revoke = 19556 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19557 19558 serializer.startTag(null, TAG_PERMISSION); 19559 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19560 if (isGranted) { 19561 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19562 } 19563 if (userSet) { 19564 serializer.attribute(null, ATTR_USER_SET, "true"); 19565 } 19566 if (userFixed) { 19567 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19568 } 19569 if (revoke) { 19570 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19571 } 19572 serializer.endTag(null, TAG_PERMISSION); 19573 } 19574 } 19575 } 19576 19577 if (pkgGrantsKnown) { 19578 serializer.endTag(null, TAG_GRANT); 19579 } 19580 } 19581 19582 serializer.endTag(null, TAG_ALL_GRANTS); 19583 } 19584 19585 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19586 throws XmlPullParserException, IOException { 19587 String pkgName = null; 19588 int outerDepth = parser.getDepth(); 19589 int type; 19590 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19591 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19592 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19593 continue; 19594 } 19595 19596 final String tagName = parser.getName(); 19597 if (tagName.equals(TAG_GRANT)) { 19598 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19599 if (DEBUG_BACKUP) { 19600 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19601 } 19602 } else if (tagName.equals(TAG_PERMISSION)) { 19603 19604 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19605 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19606 19607 int newFlagSet = 0; 19608 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19609 newFlagSet |= FLAG_PERMISSION_USER_SET; 19610 } 19611 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19612 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19613 } 19614 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19615 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19616 } 19617 if (DEBUG_BACKUP) { 19618 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 19619 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 19620 } 19621 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19622 if (ps != null) { 19623 // Already installed so we apply the grant immediately 19624 if (DEBUG_BACKUP) { 19625 Slog.v(TAG, " + already installed; applying"); 19626 } 19627 PermissionsState perms = ps.getPermissionsState(); 19628 BasePermission bp = mSettings.mPermissions.get(permName); 19629 if (bp != null) { 19630 if (isGranted) { 19631 perms.grantRuntimePermission(bp, userId); 19632 } 19633 if (newFlagSet != 0) { 19634 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19635 } 19636 } 19637 } else { 19638 // Need to wait for post-restore install to apply the grant 19639 if (DEBUG_BACKUP) { 19640 Slog.v(TAG, " - not yet installed; saving for later"); 19641 } 19642 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19643 isGranted, newFlagSet, userId); 19644 } 19645 } else { 19646 PackageManagerService.reportSettingsProblem(Log.WARN, 19647 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19648 XmlUtils.skipCurrentTag(parser); 19649 } 19650 } 19651 19652 scheduleWriteSettingsLocked(); 19653 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19654 } 19655 19656 @Override 19657 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19658 int sourceUserId, int targetUserId, int flags) { 19659 mContext.enforceCallingOrSelfPermission( 19660 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19661 int callingUid = Binder.getCallingUid(); 19662 enforceOwnerRights(ownerPackage, callingUid); 19663 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19664 if (intentFilter.countActions() == 0) { 19665 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19666 return; 19667 } 19668 synchronized (mPackages) { 19669 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19670 ownerPackage, targetUserId, flags); 19671 CrossProfileIntentResolver resolver = 19672 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19673 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19674 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19675 if (existing != null) { 19676 int size = existing.size(); 19677 for (int i = 0; i < size; i++) { 19678 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19679 return; 19680 } 19681 } 19682 } 19683 resolver.addFilter(newFilter); 19684 scheduleWritePackageRestrictionsLocked(sourceUserId); 19685 } 19686 } 19687 19688 @Override 19689 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19690 mContext.enforceCallingOrSelfPermission( 19691 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19692 int callingUid = Binder.getCallingUid(); 19693 enforceOwnerRights(ownerPackage, callingUid); 19694 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19695 synchronized (mPackages) { 19696 CrossProfileIntentResolver resolver = 19697 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19698 ArraySet<CrossProfileIntentFilter> set = 19699 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19700 for (CrossProfileIntentFilter filter : set) { 19701 if (filter.getOwnerPackage().equals(ownerPackage)) { 19702 resolver.removeFilter(filter); 19703 } 19704 } 19705 scheduleWritePackageRestrictionsLocked(sourceUserId); 19706 } 19707 } 19708 19709 // Enforcing that callingUid is owning pkg on userId 19710 private void enforceOwnerRights(String pkg, int callingUid) { 19711 // The system owns everything. 19712 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19713 return; 19714 } 19715 int callingUserId = UserHandle.getUserId(callingUid); 19716 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19717 if (pi == null) { 19718 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19719 + callingUserId); 19720 } 19721 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19722 throw new SecurityException("Calling uid " + callingUid 19723 + " does not own package " + pkg); 19724 } 19725 } 19726 19727 @Override 19728 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19729 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19730 } 19731 19732 /** 19733 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19734 * then reports the most likely home activity or null if there are more than one. 19735 */ 19736 public ComponentName getDefaultHomeActivity(int userId) { 19737 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19738 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19739 if (cn != null) { 19740 return cn; 19741 } 19742 19743 // Find the launcher with the highest priority and return that component if there are no 19744 // other home activity with the same priority. 19745 int lastPriority = Integer.MIN_VALUE; 19746 ComponentName lastComponent = null; 19747 final int size = allHomeCandidates.size(); 19748 for (int i = 0; i < size; i++) { 19749 final ResolveInfo ri = allHomeCandidates.get(i); 19750 if (ri.priority > lastPriority) { 19751 lastComponent = ri.activityInfo.getComponentName(); 19752 lastPriority = ri.priority; 19753 } else if (ri.priority == lastPriority) { 19754 // Two components found with same priority. 19755 lastComponent = null; 19756 } 19757 } 19758 return lastComponent; 19759 } 19760 19761 private Intent getHomeIntent() { 19762 Intent intent = new Intent(Intent.ACTION_MAIN); 19763 intent.addCategory(Intent.CATEGORY_HOME); 19764 intent.addCategory(Intent.CATEGORY_DEFAULT); 19765 return intent; 19766 } 19767 19768 private IntentFilter getHomeFilter() { 19769 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19770 filter.addCategory(Intent.CATEGORY_HOME); 19771 filter.addCategory(Intent.CATEGORY_DEFAULT); 19772 return filter; 19773 } 19774 19775 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19776 int userId) { 19777 Intent intent = getHomeIntent(); 19778 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19779 PackageManager.GET_META_DATA, userId); 19780 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19781 true, false, false, userId); 19782 19783 allHomeCandidates.clear(); 19784 if (list != null) { 19785 for (ResolveInfo ri : list) { 19786 allHomeCandidates.add(ri); 19787 } 19788 } 19789 return (preferred == null || preferred.activityInfo == null) 19790 ? null 19791 : new ComponentName(preferred.activityInfo.packageName, 19792 preferred.activityInfo.name); 19793 } 19794 19795 @Override 19796 public void setHomeActivity(ComponentName comp, int userId) { 19797 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19798 getHomeActivitiesAsUser(homeActivities, userId); 19799 19800 boolean found = false; 19801 19802 final int size = homeActivities.size(); 19803 final ComponentName[] set = new ComponentName[size]; 19804 for (int i = 0; i < size; i++) { 19805 final ResolveInfo candidate = homeActivities.get(i); 19806 final ActivityInfo info = candidate.activityInfo; 19807 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19808 set[i] = activityName; 19809 if (!found && activityName.equals(comp)) { 19810 found = true; 19811 } 19812 } 19813 if (!found) { 19814 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19815 + userId); 19816 } 19817 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19818 set, comp, userId); 19819 } 19820 19821 private @Nullable String getSetupWizardPackageName() { 19822 final Intent intent = new Intent(Intent.ACTION_MAIN); 19823 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19824 19825 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19826 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19827 | MATCH_DISABLED_COMPONENTS, 19828 UserHandle.myUserId()); 19829 if (matches.size() == 1) { 19830 return matches.get(0).getComponentInfo().packageName; 19831 } else { 19832 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19833 + ": matches=" + matches); 19834 return null; 19835 } 19836 } 19837 19838 private @Nullable String getStorageManagerPackageName() { 19839 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19840 19841 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19842 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19843 | MATCH_DISABLED_COMPONENTS, 19844 UserHandle.myUserId()); 19845 if (matches.size() == 1) { 19846 return matches.get(0).getComponentInfo().packageName; 19847 } else { 19848 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19849 + matches.size() + ": matches=" + matches); 19850 return null; 19851 } 19852 } 19853 19854 @Override 19855 public void setApplicationEnabledSetting(String appPackageName, 19856 int newState, int flags, int userId, String callingPackage) { 19857 if (!sUserManager.exists(userId)) return; 19858 if (callingPackage == null) { 19859 callingPackage = Integer.toString(Binder.getCallingUid()); 19860 } 19861 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19862 } 19863 19864 @Override 19865 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19866 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19867 synchronized (mPackages) { 19868 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19869 if (pkgSetting != null) { 19870 pkgSetting.setUpdateAvailable(updateAvailable); 19871 } 19872 } 19873 } 19874 19875 @Override 19876 public void setComponentEnabledSetting(ComponentName componentName, 19877 int newState, int flags, int userId) { 19878 if (!sUserManager.exists(userId)) return; 19879 setEnabledSetting(componentName.getPackageName(), 19880 componentName.getClassName(), newState, flags, userId, null); 19881 } 19882 19883 private void setEnabledSetting(final String packageName, String className, int newState, 19884 final int flags, int userId, String callingPackage) { 19885 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19886 || newState == COMPONENT_ENABLED_STATE_ENABLED 19887 || newState == COMPONENT_ENABLED_STATE_DISABLED 19888 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19889 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19890 throw new IllegalArgumentException("Invalid new component state: " 19891 + newState); 19892 } 19893 PackageSetting pkgSetting; 19894 final int uid = Binder.getCallingUid(); 19895 final int permission; 19896 if (uid == Process.SYSTEM_UID) { 19897 permission = PackageManager.PERMISSION_GRANTED; 19898 } else { 19899 permission = mContext.checkCallingOrSelfPermission( 19900 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19901 } 19902 enforceCrossUserPermission(uid, userId, 19903 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19904 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19905 boolean sendNow = false; 19906 boolean isApp = (className == null); 19907 String componentName = isApp ? packageName : className; 19908 int packageUid = -1; 19909 ArrayList<String> components; 19910 19911 // writer 19912 synchronized (mPackages) { 19913 pkgSetting = mSettings.mPackages.get(packageName); 19914 if (pkgSetting == null) { 19915 if (className == null) { 19916 throw new IllegalArgumentException("Unknown package: " + packageName); 19917 } 19918 throw new IllegalArgumentException( 19919 "Unknown component: " + packageName + "/" + className); 19920 } 19921 } 19922 19923 // Limit who can change which apps 19924 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 19925 // Don't allow apps that don't have permission to modify other apps 19926 if (!allowedByPermission) { 19927 throw new SecurityException( 19928 "Permission Denial: attempt to change component state from pid=" 19929 + Binder.getCallingPid() 19930 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 19931 } 19932 // Don't allow changing protected packages. 19933 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19934 throw new SecurityException("Cannot disable a protected package: " + packageName); 19935 } 19936 } 19937 19938 synchronized (mPackages) { 19939 if (uid == Process.SHELL_UID 19940 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 19941 // Shell can only change whole packages between ENABLED and DISABLED_USER states 19942 // unless it is a test package. 19943 int oldState = pkgSetting.getEnabled(userId); 19944 if (className == null 19945 && 19946 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 19947 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 19948 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 19949 && 19950 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19951 || newState == COMPONENT_ENABLED_STATE_DEFAULT 19952 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 19953 // ok 19954 } else { 19955 throw new SecurityException( 19956 "Shell cannot change component state for " + packageName + "/" 19957 + className + " to " + newState); 19958 } 19959 } 19960 if (className == null) { 19961 // We're dealing with an application/package level state change 19962 if (pkgSetting.getEnabled(userId) == newState) { 19963 // Nothing to do 19964 return; 19965 } 19966 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 19967 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 19968 // Don't care about who enables an app. 19969 callingPackage = null; 19970 } 19971 pkgSetting.setEnabled(newState, userId, callingPackage); 19972 // pkgSetting.pkg.mSetEnabled = newState; 19973 } else { 19974 // We're dealing with a component level state change 19975 // First, verify that this is a valid class name. 19976 PackageParser.Package pkg = pkgSetting.pkg; 19977 if (pkg == null || !pkg.hasComponentClassName(className)) { 19978 if (pkg != null && 19979 pkg.applicationInfo.targetSdkVersion >= 19980 Build.VERSION_CODES.JELLY_BEAN) { 19981 throw new IllegalArgumentException("Component class " + className 19982 + " does not exist in " + packageName); 19983 } else { 19984 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 19985 + className + " does not exist in " + packageName); 19986 } 19987 } 19988 switch (newState) { 19989 case COMPONENT_ENABLED_STATE_ENABLED: 19990 if (!pkgSetting.enableComponentLPw(className, userId)) { 19991 return; 19992 } 19993 break; 19994 case COMPONENT_ENABLED_STATE_DISABLED: 19995 if (!pkgSetting.disableComponentLPw(className, userId)) { 19996 return; 19997 } 19998 break; 19999 case COMPONENT_ENABLED_STATE_DEFAULT: 20000 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20001 return; 20002 } 20003 break; 20004 default: 20005 Slog.e(TAG, "Invalid new component state: " + newState); 20006 return; 20007 } 20008 } 20009 scheduleWritePackageRestrictionsLocked(userId); 20010 updateSequenceNumberLP(packageName, new int[] { userId }); 20011 final long callingId = Binder.clearCallingIdentity(); 20012 try { 20013 updateInstantAppInstallerLocked(packageName); 20014 } finally { 20015 Binder.restoreCallingIdentity(callingId); 20016 } 20017 components = mPendingBroadcasts.get(userId, packageName); 20018 final boolean newPackage = components == null; 20019 if (newPackage) { 20020 components = new ArrayList<String>(); 20021 } 20022 if (!components.contains(componentName)) { 20023 components.add(componentName); 20024 } 20025 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20026 sendNow = true; 20027 // Purge entry from pending broadcast list if another one exists already 20028 // since we are sending one right away. 20029 mPendingBroadcasts.remove(userId, packageName); 20030 } else { 20031 if (newPackage) { 20032 mPendingBroadcasts.put(userId, packageName, components); 20033 } 20034 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20035 // Schedule a message 20036 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20037 } 20038 } 20039 } 20040 20041 long callingId = Binder.clearCallingIdentity(); 20042 try { 20043 if (sendNow) { 20044 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20045 sendPackageChangedBroadcast(packageName, 20046 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20047 } 20048 } finally { 20049 Binder.restoreCallingIdentity(callingId); 20050 } 20051 } 20052 20053 @Override 20054 public void flushPackageRestrictionsAsUser(int userId) { 20055 if (!sUserManager.exists(userId)) { 20056 return; 20057 } 20058 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20059 false /* checkShell */, "flushPackageRestrictions"); 20060 synchronized (mPackages) { 20061 mSettings.writePackageRestrictionsLPr(userId); 20062 mDirtyUsers.remove(userId); 20063 if (mDirtyUsers.isEmpty()) { 20064 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20065 } 20066 } 20067 } 20068 20069 private void sendPackageChangedBroadcast(String packageName, 20070 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20071 if (DEBUG_INSTALL) 20072 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20073 + componentNames); 20074 Bundle extras = new Bundle(4); 20075 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20076 String nameList[] = new String[componentNames.size()]; 20077 componentNames.toArray(nameList); 20078 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20079 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20080 extras.putInt(Intent.EXTRA_UID, packageUid); 20081 // If this is not reporting a change of the overall package, then only send it 20082 // to registered receivers. We don't want to launch a swath of apps for every 20083 // little component state change. 20084 final int flags = !componentNames.contains(packageName) 20085 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20086 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20087 new int[] {UserHandle.getUserId(packageUid)}); 20088 } 20089 20090 @Override 20091 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20092 if (!sUserManager.exists(userId)) return; 20093 final int uid = Binder.getCallingUid(); 20094 final int permission = mContext.checkCallingOrSelfPermission( 20095 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20096 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20097 enforceCrossUserPermission(uid, userId, 20098 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20099 // writer 20100 synchronized (mPackages) { 20101 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20102 allowedByPermission, uid, userId)) { 20103 scheduleWritePackageRestrictionsLocked(userId); 20104 } 20105 } 20106 } 20107 20108 @Override 20109 public String getInstallerPackageName(String packageName) { 20110 // reader 20111 synchronized (mPackages) { 20112 return mSettings.getInstallerPackageNameLPr(packageName); 20113 } 20114 } 20115 20116 public boolean isOrphaned(String packageName) { 20117 // reader 20118 synchronized (mPackages) { 20119 return mSettings.isOrphaned(packageName); 20120 } 20121 } 20122 20123 @Override 20124 public int getApplicationEnabledSetting(String packageName, int userId) { 20125 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20126 int uid = Binder.getCallingUid(); 20127 enforceCrossUserPermission(uid, userId, 20128 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20129 // reader 20130 synchronized (mPackages) { 20131 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20132 } 20133 } 20134 20135 @Override 20136 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 20137 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20138 int uid = Binder.getCallingUid(); 20139 enforceCrossUserPermission(uid, userId, 20140 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 20141 // reader 20142 synchronized (mPackages) { 20143 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 20144 } 20145 } 20146 20147 @Override 20148 public void enterSafeMode() { 20149 enforceSystemOrRoot("Only the system can request entering safe mode"); 20150 20151 if (!mSystemReady) { 20152 mSafeMode = true; 20153 } 20154 } 20155 20156 @Override 20157 public void systemReady() { 20158 mSystemReady = true; 20159 final ContentResolver resolver = mContext.getContentResolver(); 20160 ContentObserver co = new ContentObserver(mHandler) { 20161 @Override 20162 public void onChange(boolean selfChange) { 20163 mEphemeralAppsDisabled = 20164 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20165 (Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0); 20166 } 20167 }; 20168 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20169 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20170 false, co, UserHandle.USER_SYSTEM); 20171 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20172 .getUriFor(Secure.WEB_ACTION_ENABLED), false, co, UserHandle.USER_SYSTEM); 20173 co.onChange(true); 20174 20175 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20176 // disabled after already being started. 20177 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20178 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20179 20180 // Read the compatibilty setting when the system is ready. 20181 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20182 mContext.getContentResolver(), 20183 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20184 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20185 if (DEBUG_SETTINGS) { 20186 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20187 } 20188 20189 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20190 20191 synchronized (mPackages) { 20192 // Verify that all of the preferred activity components actually 20193 // exist. It is possible for applications to be updated and at 20194 // that point remove a previously declared activity component that 20195 // had been set as a preferred activity. We try to clean this up 20196 // the next time we encounter that preferred activity, but it is 20197 // possible for the user flow to never be able to return to that 20198 // situation so here we do a sanity check to make sure we haven't 20199 // left any junk around. 20200 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20201 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20202 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20203 removed.clear(); 20204 for (PreferredActivity pa : pir.filterSet()) { 20205 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20206 removed.add(pa); 20207 } 20208 } 20209 if (removed.size() > 0) { 20210 for (int r=0; r<removed.size(); r++) { 20211 PreferredActivity pa = removed.get(r); 20212 Slog.w(TAG, "Removing dangling preferred activity: " 20213 + pa.mPref.mComponent); 20214 pir.removeFilter(pa); 20215 } 20216 mSettings.writePackageRestrictionsLPr( 20217 mSettings.mPreferredActivities.keyAt(i)); 20218 } 20219 } 20220 20221 for (int userId : UserManagerService.getInstance().getUserIds()) { 20222 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20223 grantPermissionsUserIds = ArrayUtils.appendInt( 20224 grantPermissionsUserIds, userId); 20225 } 20226 } 20227 } 20228 sUserManager.systemReady(); 20229 20230 // If we upgraded grant all default permissions before kicking off. 20231 for (int userId : grantPermissionsUserIds) { 20232 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20233 } 20234 20235 // If we did not grant default permissions, we preload from this the 20236 // default permission exceptions lazily to ensure we don't hit the 20237 // disk on a new user creation. 20238 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20239 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20240 } 20241 20242 // Kick off any messages waiting for system ready 20243 if (mPostSystemReadyMessages != null) { 20244 for (Message msg : mPostSystemReadyMessages) { 20245 msg.sendToTarget(); 20246 } 20247 mPostSystemReadyMessages = null; 20248 } 20249 20250 // Watch for external volumes that come and go over time 20251 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20252 storage.registerListener(mStorageListener); 20253 20254 mInstallerService.systemReady(); 20255 mPackageDexOptimizer.systemReady(); 20256 20257 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20258 StorageManagerInternal.class); 20259 StorageManagerInternal.addExternalStoragePolicy( 20260 new StorageManagerInternal.ExternalStorageMountPolicy() { 20261 @Override 20262 public int getMountMode(int uid, String packageName) { 20263 if (Process.isIsolated(uid)) { 20264 return Zygote.MOUNT_EXTERNAL_NONE; 20265 } 20266 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20267 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20268 } 20269 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20270 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20271 } 20272 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20273 return Zygote.MOUNT_EXTERNAL_READ; 20274 } 20275 return Zygote.MOUNT_EXTERNAL_WRITE; 20276 } 20277 20278 @Override 20279 public boolean hasExternalStorage(int uid, String packageName) { 20280 return true; 20281 } 20282 }); 20283 20284 // Now that we're mostly running, clean up stale users and apps 20285 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20286 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20287 20288 if (mPrivappPermissionsViolations != null) { 20289 Slog.wtf(TAG,"Signature|privileged permissions not in " 20290 + "privapp-permissions whitelist: " + mPrivappPermissionsViolations); 20291 mPrivappPermissionsViolations = null; 20292 } 20293 } 20294 20295 public void waitForAppDataPrepared() { 20296 if (mPrepareAppDataFuture == null) { 20297 return; 20298 } 20299 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20300 mPrepareAppDataFuture = null; 20301 } 20302 20303 @Override 20304 public boolean isSafeMode() { 20305 return mSafeMode; 20306 } 20307 20308 @Override 20309 public boolean hasSystemUidErrors() { 20310 return mHasSystemUidErrors; 20311 } 20312 20313 static String arrayToString(int[] array) { 20314 StringBuffer buf = new StringBuffer(128); 20315 buf.append('['); 20316 if (array != null) { 20317 for (int i=0; i<array.length; i++) { 20318 if (i > 0) buf.append(", "); 20319 buf.append(array[i]); 20320 } 20321 } 20322 buf.append(']'); 20323 return buf.toString(); 20324 } 20325 20326 static class DumpState { 20327 public static final int DUMP_LIBS = 1 << 0; 20328 public static final int DUMP_FEATURES = 1 << 1; 20329 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 20330 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 20331 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 20332 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 20333 public static final int DUMP_PERMISSIONS = 1 << 6; 20334 public static final int DUMP_PACKAGES = 1 << 7; 20335 public static final int DUMP_SHARED_USERS = 1 << 8; 20336 public static final int DUMP_MESSAGES = 1 << 9; 20337 public static final int DUMP_PROVIDERS = 1 << 10; 20338 public static final int DUMP_VERIFIERS = 1 << 11; 20339 public static final int DUMP_PREFERRED = 1 << 12; 20340 public static final int DUMP_PREFERRED_XML = 1 << 13; 20341 public static final int DUMP_KEYSETS = 1 << 14; 20342 public static final int DUMP_VERSION = 1 << 15; 20343 public static final int DUMP_INSTALLS = 1 << 16; 20344 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 20345 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 20346 public static final int DUMP_FROZEN = 1 << 19; 20347 public static final int DUMP_DEXOPT = 1 << 20; 20348 public static final int DUMP_COMPILER_STATS = 1 << 21; 20349 public static final int DUMP_ENABLED_OVERLAYS = 1 << 22; 20350 20351 public static final int OPTION_SHOW_FILTERS = 1 << 0; 20352 20353 private int mTypes; 20354 20355 private int mOptions; 20356 20357 private boolean mTitlePrinted; 20358 20359 private SharedUserSetting mSharedUser; 20360 20361 public boolean isDumping(int type) { 20362 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 20363 return true; 20364 } 20365 20366 return (mTypes & type) != 0; 20367 } 20368 20369 public void setDump(int type) { 20370 mTypes |= type; 20371 } 20372 20373 public boolean isOptionEnabled(int option) { 20374 return (mOptions & option) != 0; 20375 } 20376 20377 public void setOptionEnabled(int option) { 20378 mOptions |= option; 20379 } 20380 20381 public boolean onTitlePrinted() { 20382 final boolean printed = mTitlePrinted; 20383 mTitlePrinted = true; 20384 return printed; 20385 } 20386 20387 public boolean getTitlePrinted() { 20388 return mTitlePrinted; 20389 } 20390 20391 public void setTitlePrinted(boolean enabled) { 20392 mTitlePrinted = enabled; 20393 } 20394 20395 public SharedUserSetting getSharedUser() { 20396 return mSharedUser; 20397 } 20398 20399 public void setSharedUser(SharedUserSetting user) { 20400 mSharedUser = user; 20401 } 20402 } 20403 20404 @Override 20405 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20406 FileDescriptor err, String[] args, ShellCallback callback, 20407 ResultReceiver resultReceiver) { 20408 (new PackageManagerShellCommand(this)).exec( 20409 this, in, out, err, args, callback, resultReceiver); 20410 } 20411 20412 @Override 20413 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20414 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20415 20416 DumpState dumpState = new DumpState(); 20417 boolean fullPreferred = false; 20418 boolean checkin = false; 20419 20420 String packageName = null; 20421 ArraySet<String> permissionNames = null; 20422 20423 int opti = 0; 20424 while (opti < args.length) { 20425 String opt = args[opti]; 20426 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20427 break; 20428 } 20429 opti++; 20430 20431 if ("-a".equals(opt)) { 20432 // Right now we only know how to print all. 20433 } else if ("-h".equals(opt)) { 20434 pw.println("Package manager dump options:"); 20435 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20436 pw.println(" --checkin: dump for a checkin"); 20437 pw.println(" -f: print details of intent filters"); 20438 pw.println(" -h: print this help"); 20439 pw.println(" cmd may be one of:"); 20440 pw.println(" l[ibraries]: list known shared libraries"); 20441 pw.println(" f[eatures]: list device features"); 20442 pw.println(" k[eysets]: print known keysets"); 20443 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20444 pw.println(" perm[issions]: dump permissions"); 20445 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20446 pw.println(" pref[erred]: print preferred package settings"); 20447 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20448 pw.println(" prov[iders]: dump content providers"); 20449 pw.println(" p[ackages]: dump installed packages"); 20450 pw.println(" s[hared-users]: dump shared user IDs"); 20451 pw.println(" m[essages]: print collected runtime messages"); 20452 pw.println(" v[erifiers]: print package verifier info"); 20453 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20454 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20455 pw.println(" version: print database version info"); 20456 pw.println(" write: write current settings now"); 20457 pw.println(" installs: details about install sessions"); 20458 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20459 pw.println(" dexopt: dump dexopt state"); 20460 pw.println(" compiler-stats: dump compiler statistics"); 20461 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20462 pw.println(" <package.name>: info about given package"); 20463 return; 20464 } else if ("--checkin".equals(opt)) { 20465 checkin = true; 20466 } else if ("-f".equals(opt)) { 20467 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20468 } else if ("--proto".equals(opt)) { 20469 dumpProto(fd); 20470 return; 20471 } else { 20472 pw.println("Unknown argument: " + opt + "; use -h for help"); 20473 } 20474 } 20475 20476 // Is the caller requesting to dump a particular piece of data? 20477 if (opti < args.length) { 20478 String cmd = args[opti]; 20479 opti++; 20480 // Is this a package name? 20481 if ("android".equals(cmd) || cmd.contains(".")) { 20482 packageName = cmd; 20483 // When dumping a single package, we always dump all of its 20484 // filter information since the amount of data will be reasonable. 20485 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20486 } else if ("check-permission".equals(cmd)) { 20487 if (opti >= args.length) { 20488 pw.println("Error: check-permission missing permission argument"); 20489 return; 20490 } 20491 String perm = args[opti]; 20492 opti++; 20493 if (opti >= args.length) { 20494 pw.println("Error: check-permission missing package argument"); 20495 return; 20496 } 20497 20498 String pkg = args[opti]; 20499 opti++; 20500 int user = UserHandle.getUserId(Binder.getCallingUid()); 20501 if (opti < args.length) { 20502 try { 20503 user = Integer.parseInt(args[opti]); 20504 } catch (NumberFormatException e) { 20505 pw.println("Error: check-permission user argument is not a number: " 20506 + args[opti]); 20507 return; 20508 } 20509 } 20510 20511 // Normalize package name to handle renamed packages and static libs 20512 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20513 20514 pw.println(checkPermission(perm, pkg, user)); 20515 return; 20516 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20517 dumpState.setDump(DumpState.DUMP_LIBS); 20518 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20519 dumpState.setDump(DumpState.DUMP_FEATURES); 20520 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20521 if (opti >= args.length) { 20522 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20523 | DumpState.DUMP_SERVICE_RESOLVERS 20524 | DumpState.DUMP_RECEIVER_RESOLVERS 20525 | DumpState.DUMP_CONTENT_RESOLVERS); 20526 } else { 20527 while (opti < args.length) { 20528 String name = args[opti]; 20529 if ("a".equals(name) || "activity".equals(name)) { 20530 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20531 } else if ("s".equals(name) || "service".equals(name)) { 20532 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20533 } else if ("r".equals(name) || "receiver".equals(name)) { 20534 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20535 } else if ("c".equals(name) || "content".equals(name)) { 20536 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20537 } else { 20538 pw.println("Error: unknown resolver table type: " + name); 20539 return; 20540 } 20541 opti++; 20542 } 20543 } 20544 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20545 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20546 } else if ("permission".equals(cmd)) { 20547 if (opti >= args.length) { 20548 pw.println("Error: permission requires permission name"); 20549 return; 20550 } 20551 permissionNames = new ArraySet<>(); 20552 while (opti < args.length) { 20553 permissionNames.add(args[opti]); 20554 opti++; 20555 } 20556 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20557 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20558 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20559 dumpState.setDump(DumpState.DUMP_PREFERRED); 20560 } else if ("preferred-xml".equals(cmd)) { 20561 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20562 if (opti < args.length && "--full".equals(args[opti])) { 20563 fullPreferred = true; 20564 opti++; 20565 } 20566 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20567 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20568 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20569 dumpState.setDump(DumpState.DUMP_PACKAGES); 20570 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20571 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20572 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20573 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20574 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20575 dumpState.setDump(DumpState.DUMP_MESSAGES); 20576 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20577 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20578 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20579 || "intent-filter-verifiers".equals(cmd)) { 20580 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20581 } else if ("version".equals(cmd)) { 20582 dumpState.setDump(DumpState.DUMP_VERSION); 20583 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20584 dumpState.setDump(DumpState.DUMP_KEYSETS); 20585 } else if ("installs".equals(cmd)) { 20586 dumpState.setDump(DumpState.DUMP_INSTALLS); 20587 } else if ("frozen".equals(cmd)) { 20588 dumpState.setDump(DumpState.DUMP_FROZEN); 20589 } else if ("dexopt".equals(cmd)) { 20590 dumpState.setDump(DumpState.DUMP_DEXOPT); 20591 } else if ("compiler-stats".equals(cmd)) { 20592 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20593 } else if ("enabled-overlays".equals(cmd)) { 20594 dumpState.setDump(DumpState.DUMP_ENABLED_OVERLAYS); 20595 } else if ("write".equals(cmd)) { 20596 synchronized (mPackages) { 20597 mSettings.writeLPr(); 20598 pw.println("Settings written."); 20599 return; 20600 } 20601 } 20602 } 20603 20604 if (checkin) { 20605 pw.println("vers,1"); 20606 } 20607 20608 // reader 20609 synchronized (mPackages) { 20610 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20611 if (!checkin) { 20612 if (dumpState.onTitlePrinted()) 20613 pw.println(); 20614 pw.println("Database versions:"); 20615 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20616 } 20617 } 20618 20619 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20620 if (!checkin) { 20621 if (dumpState.onTitlePrinted()) 20622 pw.println(); 20623 pw.println("Verifiers:"); 20624 pw.print(" Required: "); 20625 pw.print(mRequiredVerifierPackage); 20626 pw.print(" (uid="); 20627 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20628 UserHandle.USER_SYSTEM)); 20629 pw.println(")"); 20630 } else if (mRequiredVerifierPackage != null) { 20631 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20632 pw.print(","); 20633 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20634 UserHandle.USER_SYSTEM)); 20635 } 20636 } 20637 20638 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20639 packageName == null) { 20640 if (mIntentFilterVerifierComponent != null) { 20641 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20642 if (!checkin) { 20643 if (dumpState.onTitlePrinted()) 20644 pw.println(); 20645 pw.println("Intent Filter Verifier:"); 20646 pw.print(" Using: "); 20647 pw.print(verifierPackageName); 20648 pw.print(" (uid="); 20649 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20650 UserHandle.USER_SYSTEM)); 20651 pw.println(")"); 20652 } else if (verifierPackageName != null) { 20653 pw.print("ifv,"); pw.print(verifierPackageName); 20654 pw.print(","); 20655 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20656 UserHandle.USER_SYSTEM)); 20657 } 20658 } else { 20659 pw.println(); 20660 pw.println("No Intent Filter Verifier available!"); 20661 } 20662 } 20663 20664 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20665 boolean printedHeader = false; 20666 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20667 while (it.hasNext()) { 20668 String libName = it.next(); 20669 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 20670 if (versionedLib == null) { 20671 continue; 20672 } 20673 final int versionCount = versionedLib.size(); 20674 for (int i = 0; i < versionCount; i++) { 20675 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20676 if (!checkin) { 20677 if (!printedHeader) { 20678 if (dumpState.onTitlePrinted()) 20679 pw.println(); 20680 pw.println("Libraries:"); 20681 printedHeader = true; 20682 } 20683 pw.print(" "); 20684 } else { 20685 pw.print("lib,"); 20686 } 20687 pw.print(libEntry.info.getName()); 20688 if (libEntry.info.isStatic()) { 20689 pw.print(" version=" + libEntry.info.getVersion()); 20690 } 20691 if (!checkin) { 20692 pw.print(" -> "); 20693 } 20694 if (libEntry.path != null) { 20695 pw.print(" (jar) "); 20696 pw.print(libEntry.path); 20697 } else { 20698 pw.print(" (apk) "); 20699 pw.print(libEntry.apk); 20700 } 20701 pw.println(); 20702 } 20703 } 20704 } 20705 20706 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20707 if (dumpState.onTitlePrinted()) 20708 pw.println(); 20709 if (!checkin) { 20710 pw.println("Features:"); 20711 } 20712 20713 synchronized (mAvailableFeatures) { 20714 for (FeatureInfo feat : mAvailableFeatures.values()) { 20715 if (checkin) { 20716 pw.print("feat,"); 20717 pw.print(feat.name); 20718 pw.print(","); 20719 pw.println(feat.version); 20720 } else { 20721 pw.print(" "); 20722 pw.print(feat.name); 20723 if (feat.version > 0) { 20724 pw.print(" version="); 20725 pw.print(feat.version); 20726 } 20727 pw.println(); 20728 } 20729 } 20730 } 20731 } 20732 20733 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20734 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20735 : "Activity Resolver Table:", " ", packageName, 20736 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20737 dumpState.setTitlePrinted(true); 20738 } 20739 } 20740 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20741 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20742 : "Receiver Resolver Table:", " ", packageName, 20743 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20744 dumpState.setTitlePrinted(true); 20745 } 20746 } 20747 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20748 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20749 : "Service Resolver Table:", " ", packageName, 20750 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20751 dumpState.setTitlePrinted(true); 20752 } 20753 } 20754 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20755 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20756 : "Provider Resolver Table:", " ", packageName, 20757 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20758 dumpState.setTitlePrinted(true); 20759 } 20760 } 20761 20762 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20763 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20764 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20765 int user = mSettings.mPreferredActivities.keyAt(i); 20766 if (pir.dump(pw, 20767 dumpState.getTitlePrinted() 20768 ? "\nPreferred Activities User " + user + ":" 20769 : "Preferred Activities User " + user + ":", " ", 20770 packageName, true, false)) { 20771 dumpState.setTitlePrinted(true); 20772 } 20773 } 20774 } 20775 20776 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20777 pw.flush(); 20778 FileOutputStream fout = new FileOutputStream(fd); 20779 BufferedOutputStream str = new BufferedOutputStream(fout); 20780 XmlSerializer serializer = new FastXmlSerializer(); 20781 try { 20782 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20783 serializer.startDocument(null, true); 20784 serializer.setFeature( 20785 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20786 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20787 serializer.endDocument(); 20788 serializer.flush(); 20789 } catch (IllegalArgumentException e) { 20790 pw.println("Failed writing: " + e); 20791 } catch (IllegalStateException e) { 20792 pw.println("Failed writing: " + e); 20793 } catch (IOException e) { 20794 pw.println("Failed writing: " + e); 20795 } 20796 } 20797 20798 if (!checkin 20799 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20800 && packageName == null) { 20801 pw.println(); 20802 int count = mSettings.mPackages.size(); 20803 if (count == 0) { 20804 pw.println("No applications!"); 20805 pw.println(); 20806 } else { 20807 final String prefix = " "; 20808 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20809 if (allPackageSettings.size() == 0) { 20810 pw.println("No domain preferred apps!"); 20811 pw.println(); 20812 } else { 20813 pw.println("App verification status:"); 20814 pw.println(); 20815 count = 0; 20816 for (PackageSetting ps : allPackageSettings) { 20817 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20818 if (ivi == null || ivi.getPackageName() == null) continue; 20819 pw.println(prefix + "Package: " + ivi.getPackageName()); 20820 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20821 pw.println(prefix + "Status: " + ivi.getStatusString()); 20822 pw.println(); 20823 count++; 20824 } 20825 if (count == 0) { 20826 pw.println(prefix + "No app verification established."); 20827 pw.println(); 20828 } 20829 for (int userId : sUserManager.getUserIds()) { 20830 pw.println("App linkages for user " + userId + ":"); 20831 pw.println(); 20832 count = 0; 20833 for (PackageSetting ps : allPackageSettings) { 20834 final long status = ps.getDomainVerificationStatusForUser(userId); 20835 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20836 && !DEBUG_DOMAIN_VERIFICATION) { 20837 continue; 20838 } 20839 pw.println(prefix + "Package: " + ps.name); 20840 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20841 String statusStr = IntentFilterVerificationInfo. 20842 getStatusStringFromValue(status); 20843 pw.println(prefix + "Status: " + statusStr); 20844 pw.println(); 20845 count++; 20846 } 20847 if (count == 0) { 20848 pw.println(prefix + "No configured app linkages."); 20849 pw.println(); 20850 } 20851 } 20852 } 20853 } 20854 } 20855 20856 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 20857 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 20858 if (packageName == null && permissionNames == null) { 20859 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 20860 if (iperm == 0) { 20861 if (dumpState.onTitlePrinted()) 20862 pw.println(); 20863 pw.println("AppOp Permissions:"); 20864 } 20865 pw.print(" AppOp Permission "); 20866 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 20867 pw.println(":"); 20868 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 20869 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 20870 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 20871 } 20872 } 20873 } 20874 } 20875 20876 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 20877 boolean printedSomething = false; 20878 for (PackageParser.Provider p : mProviders.mProviders.values()) { 20879 if (packageName != null && !packageName.equals(p.info.packageName)) { 20880 continue; 20881 } 20882 if (!printedSomething) { 20883 if (dumpState.onTitlePrinted()) 20884 pw.println(); 20885 pw.println("Registered ContentProviders:"); 20886 printedSomething = true; 20887 } 20888 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 20889 pw.print(" "); pw.println(p.toString()); 20890 } 20891 printedSomething = false; 20892 for (Map.Entry<String, PackageParser.Provider> entry : 20893 mProvidersByAuthority.entrySet()) { 20894 PackageParser.Provider p = entry.getValue(); 20895 if (packageName != null && !packageName.equals(p.info.packageName)) { 20896 continue; 20897 } 20898 if (!printedSomething) { 20899 if (dumpState.onTitlePrinted()) 20900 pw.println(); 20901 pw.println("ContentProvider Authorities:"); 20902 printedSomething = true; 20903 } 20904 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 20905 pw.print(" "); pw.println(p.toString()); 20906 if (p.info != null && p.info.applicationInfo != null) { 20907 final String appInfo = p.info.applicationInfo.toString(); 20908 pw.print(" applicationInfo="); pw.println(appInfo); 20909 } 20910 } 20911 } 20912 20913 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 20914 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 20915 } 20916 20917 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 20918 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 20919 } 20920 20921 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 20922 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 20923 } 20924 20925 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 20926 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 20927 } 20928 20929 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 20930 // XXX should handle packageName != null by dumping only install data that 20931 // the given package is involved with. 20932 if (dumpState.onTitlePrinted()) pw.println(); 20933 20934 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 20935 ipw.println(); 20936 ipw.println("Frozen packages:"); 20937 ipw.increaseIndent(); 20938 if (mFrozenPackages.size() == 0) { 20939 ipw.println("(none)"); 20940 } else { 20941 for (int i = 0; i < mFrozenPackages.size(); i++) { 20942 ipw.println(mFrozenPackages.valueAt(i)); 20943 } 20944 } 20945 ipw.decreaseIndent(); 20946 } 20947 20948 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 20949 if (dumpState.onTitlePrinted()) pw.println(); 20950 dumpDexoptStateLPr(pw, packageName); 20951 } 20952 20953 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 20954 if (dumpState.onTitlePrinted()) pw.println(); 20955 dumpCompilerStatsLPr(pw, packageName); 20956 } 20957 20958 if (!checkin && dumpState.isDumping(DumpState.DUMP_ENABLED_OVERLAYS)) { 20959 if (dumpState.onTitlePrinted()) pw.println(); 20960 dumpEnabledOverlaysLPr(pw); 20961 } 20962 20963 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 20964 if (dumpState.onTitlePrinted()) pw.println(); 20965 mSettings.dumpReadMessagesLPr(pw, dumpState); 20966 20967 pw.println(); 20968 pw.println("Package warning messages:"); 20969 BufferedReader in = null; 20970 String line = null; 20971 try { 20972 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20973 while ((line = in.readLine()) != null) { 20974 if (line.contains("ignored: updated version")) continue; 20975 pw.println(line); 20976 } 20977 } catch (IOException ignored) { 20978 } finally { 20979 IoUtils.closeQuietly(in); 20980 } 20981 } 20982 20983 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 20984 BufferedReader in = null; 20985 String line = null; 20986 try { 20987 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 20988 while ((line = in.readLine()) != null) { 20989 if (line.contains("ignored: updated version")) continue; 20990 pw.print("msg,"); 20991 pw.println(line); 20992 } 20993 } catch (IOException ignored) { 20994 } finally { 20995 IoUtils.closeQuietly(in); 20996 } 20997 } 20998 } 20999 21000 // PackageInstaller should be called outside of mPackages lock 21001 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21002 // XXX should handle packageName != null by dumping only install data that 21003 // the given package is involved with. 21004 if (dumpState.onTitlePrinted()) pw.println(); 21005 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21006 } 21007 } 21008 21009 private void dumpProto(FileDescriptor fd) { 21010 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21011 21012 synchronized (mPackages) { 21013 final long requiredVerifierPackageToken = 21014 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21015 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21016 proto.write( 21017 PackageServiceDumpProto.PackageShortProto.UID, 21018 getPackageUid( 21019 mRequiredVerifierPackage, 21020 MATCH_DEBUG_TRIAGED_MISSING, 21021 UserHandle.USER_SYSTEM)); 21022 proto.end(requiredVerifierPackageToken); 21023 21024 if (mIntentFilterVerifierComponent != null) { 21025 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21026 final long verifierPackageToken = 21027 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21028 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21029 proto.write( 21030 PackageServiceDumpProto.PackageShortProto.UID, 21031 getPackageUid( 21032 verifierPackageName, 21033 MATCH_DEBUG_TRIAGED_MISSING, 21034 UserHandle.USER_SYSTEM)); 21035 proto.end(verifierPackageToken); 21036 } 21037 21038 dumpSharedLibrariesProto(proto); 21039 dumpFeaturesProto(proto); 21040 mSettings.dumpPackagesProto(proto); 21041 mSettings.dumpSharedUsersProto(proto); 21042 dumpMessagesProto(proto); 21043 } 21044 proto.flush(); 21045 } 21046 21047 private void dumpMessagesProto(ProtoOutputStream proto) { 21048 BufferedReader in = null; 21049 String line = null; 21050 try { 21051 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 21052 while ((line = in.readLine()) != null) { 21053 if (line.contains("ignored: updated version")) continue; 21054 proto.write(PackageServiceDumpProto.MESSAGES, line); 21055 } 21056 } catch (IOException ignored) { 21057 } finally { 21058 IoUtils.closeQuietly(in); 21059 } 21060 } 21061 21062 private void dumpFeaturesProto(ProtoOutputStream proto) { 21063 synchronized (mAvailableFeatures) { 21064 final int count = mAvailableFeatures.size(); 21065 for (int i = 0; i < count; i++) { 21066 final FeatureInfo feat = mAvailableFeatures.valueAt(i); 21067 final long featureToken = proto.start(PackageServiceDumpProto.FEATURES); 21068 proto.write(PackageServiceDumpProto.FeatureProto.NAME, feat.name); 21069 proto.write(PackageServiceDumpProto.FeatureProto.VERSION, feat.version); 21070 proto.end(featureToken); 21071 } 21072 } 21073 } 21074 21075 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21076 final int count = mSharedLibraries.size(); 21077 for (int i = 0; i < count; i++) { 21078 final String libName = mSharedLibraries.keyAt(i); 21079 SparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21080 if (versionedLib == null) { 21081 continue; 21082 } 21083 final int versionCount = versionedLib.size(); 21084 for (int j = 0; j < versionCount; j++) { 21085 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21086 final long sharedLibraryToken = 21087 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21088 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21089 final boolean isJar = (libEntry.path != null); 21090 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21091 if (isJar) { 21092 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21093 } else { 21094 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21095 } 21096 proto.end(sharedLibraryToken); 21097 } 21098 } 21099 } 21100 21101 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21102 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21103 ipw.println(); 21104 ipw.println("Dexopt state:"); 21105 ipw.increaseIndent(); 21106 Collection<PackageParser.Package> packages = null; 21107 if (packageName != null) { 21108 PackageParser.Package targetPackage = mPackages.get(packageName); 21109 if (targetPackage != null) { 21110 packages = Collections.singletonList(targetPackage); 21111 } else { 21112 ipw.println("Unable to find package: " + packageName); 21113 return; 21114 } 21115 } else { 21116 packages = mPackages.values(); 21117 } 21118 21119 for (PackageParser.Package pkg : packages) { 21120 ipw.println("[" + pkg.packageName + "]"); 21121 ipw.increaseIndent(); 21122 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 21123 ipw.decreaseIndent(); 21124 } 21125 } 21126 21127 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21128 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21129 ipw.println(); 21130 ipw.println("Compiler stats:"); 21131 ipw.increaseIndent(); 21132 Collection<PackageParser.Package> packages = null; 21133 if (packageName != null) { 21134 PackageParser.Package targetPackage = mPackages.get(packageName); 21135 if (targetPackage != null) { 21136 packages = Collections.singletonList(targetPackage); 21137 } else { 21138 ipw.println("Unable to find package: " + packageName); 21139 return; 21140 } 21141 } else { 21142 packages = mPackages.values(); 21143 } 21144 21145 for (PackageParser.Package pkg : packages) { 21146 ipw.println("[" + pkg.packageName + "]"); 21147 ipw.increaseIndent(); 21148 21149 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21150 if (stats == null) { 21151 ipw.println("(No recorded stats)"); 21152 } else { 21153 stats.dump(ipw); 21154 } 21155 ipw.decreaseIndent(); 21156 } 21157 } 21158 21159 private void dumpEnabledOverlaysLPr(PrintWriter pw) { 21160 pw.println("Enabled overlay paths:"); 21161 final int N = mEnabledOverlayPaths.size(); 21162 for (int i = 0; i < N; i++) { 21163 final int userId = mEnabledOverlayPaths.keyAt(i); 21164 pw.println(String.format(" User %d:", userId)); 21165 final ArrayMap<String, ArrayList<String>> userSpecificOverlays = 21166 mEnabledOverlayPaths.valueAt(i); 21167 final int M = userSpecificOverlays.size(); 21168 for (int j = 0; j < M; j++) { 21169 final String targetPackageName = userSpecificOverlays.keyAt(j); 21170 final ArrayList<String> overlayPackagePaths = userSpecificOverlays.valueAt(j); 21171 pw.println(String.format(" %s: %s", targetPackageName, overlayPackagePaths)); 21172 } 21173 } 21174 } 21175 21176 private String dumpDomainString(String packageName) { 21177 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21178 .getList(); 21179 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21180 21181 ArraySet<String> result = new ArraySet<>(); 21182 if (iviList.size() > 0) { 21183 for (IntentFilterVerificationInfo ivi : iviList) { 21184 for (String host : ivi.getDomains()) { 21185 result.add(host); 21186 } 21187 } 21188 } 21189 if (filters != null && filters.size() > 0) { 21190 for (IntentFilter filter : filters) { 21191 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21192 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21193 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21194 result.addAll(filter.getHostsList()); 21195 } 21196 } 21197 } 21198 21199 StringBuilder sb = new StringBuilder(result.size() * 16); 21200 for (String domain : result) { 21201 if (sb.length() > 0) sb.append(" "); 21202 sb.append(domain); 21203 } 21204 return sb.toString(); 21205 } 21206 21207 // ------- apps on sdcard specific code ------- 21208 static final boolean DEBUG_SD_INSTALL = false; 21209 21210 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21211 21212 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21213 21214 private boolean mMediaMounted = false; 21215 21216 static String getEncryptKey() { 21217 try { 21218 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21219 SD_ENCRYPTION_KEYSTORE_NAME); 21220 if (sdEncKey == null) { 21221 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21222 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21223 if (sdEncKey == null) { 21224 Slog.e(TAG, "Failed to create encryption keys"); 21225 return null; 21226 } 21227 } 21228 return sdEncKey; 21229 } catch (NoSuchAlgorithmException nsae) { 21230 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21231 return null; 21232 } catch (IOException ioe) { 21233 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21234 return null; 21235 } 21236 } 21237 21238 /* 21239 * Update media status on PackageManager. 21240 */ 21241 @Override 21242 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 21243 int callingUid = Binder.getCallingUid(); 21244 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 21245 throw new SecurityException("Media status can only be updated by the system"); 21246 } 21247 // reader; this apparently protects mMediaMounted, but should probably 21248 // be a different lock in that case. 21249 synchronized (mPackages) { 21250 Log.i(TAG, "Updating external media status from " 21251 + (mMediaMounted ? "mounted" : "unmounted") + " to " 21252 + (mediaStatus ? "mounted" : "unmounted")); 21253 if (DEBUG_SD_INSTALL) 21254 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 21255 + ", mMediaMounted=" + mMediaMounted); 21256 if (mediaStatus == mMediaMounted) { 21257 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 21258 : 0, -1); 21259 mHandler.sendMessage(msg); 21260 return; 21261 } 21262 mMediaMounted = mediaStatus; 21263 } 21264 // Queue up an async operation since the package installation may take a 21265 // little while. 21266 mHandler.post(new Runnable() { 21267 public void run() { 21268 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 21269 } 21270 }); 21271 } 21272 21273 /** 21274 * Called by StorageManagerService when the initial ASECs to scan are available. 21275 * Should block until all the ASEC containers are finished being scanned. 21276 */ 21277 public void scanAvailableAsecs() { 21278 updateExternalMediaStatusInner(true, false, false); 21279 } 21280 21281 /* 21282 * Collect information of applications on external media, map them against 21283 * existing containers and update information based on current mount status. 21284 * Please note that we always have to report status if reportStatus has been 21285 * set to true especially when unloading packages. 21286 */ 21287 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 21288 boolean externalStorage) { 21289 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 21290 int[] uidArr = EmptyArray.INT; 21291 21292 final String[] list = PackageHelper.getSecureContainerList(); 21293 if (ArrayUtils.isEmpty(list)) { 21294 Log.i(TAG, "No secure containers found"); 21295 } else { 21296 // Process list of secure containers and categorize them 21297 // as active or stale based on their package internal state. 21298 21299 // reader 21300 synchronized (mPackages) { 21301 for (String cid : list) { 21302 // Leave stages untouched for now; installer service owns them 21303 if (PackageInstallerService.isStageName(cid)) continue; 21304 21305 if (DEBUG_SD_INSTALL) 21306 Log.i(TAG, "Processing container " + cid); 21307 String pkgName = getAsecPackageName(cid); 21308 if (pkgName == null) { 21309 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 21310 continue; 21311 } 21312 if (DEBUG_SD_INSTALL) 21313 Log.i(TAG, "Looking for pkg : " + pkgName); 21314 21315 final PackageSetting ps = mSettings.mPackages.get(pkgName); 21316 if (ps == null) { 21317 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 21318 continue; 21319 } 21320 21321 /* 21322 * Skip packages that are not external if we're unmounting 21323 * external storage. 21324 */ 21325 if (externalStorage && !isMounted && !isExternal(ps)) { 21326 continue; 21327 } 21328 21329 final AsecInstallArgs args = new AsecInstallArgs(cid, 21330 getAppDexInstructionSets(ps), ps.isForwardLocked()); 21331 // The package status is changed only if the code path 21332 // matches between settings and the container id. 21333 if (ps.codePathString != null 21334 && ps.codePathString.startsWith(args.getCodePath())) { 21335 if (DEBUG_SD_INSTALL) { 21336 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 21337 + " at code path: " + ps.codePathString); 21338 } 21339 21340 // We do have a valid package installed on sdcard 21341 processCids.put(args, ps.codePathString); 21342 final int uid = ps.appId; 21343 if (uid != -1) { 21344 uidArr = ArrayUtils.appendInt(uidArr, uid); 21345 } 21346 } else { 21347 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 21348 + ps.codePathString); 21349 } 21350 } 21351 } 21352 21353 Arrays.sort(uidArr); 21354 } 21355 21356 // Process packages with valid entries. 21357 if (isMounted) { 21358 if (DEBUG_SD_INSTALL) 21359 Log.i(TAG, "Loading packages"); 21360 loadMediaPackages(processCids, uidArr, externalStorage); 21361 startCleaningPackages(); 21362 mInstallerService.onSecureContainersAvailable(); 21363 } else { 21364 if (DEBUG_SD_INSTALL) 21365 Log.i(TAG, "Unloading packages"); 21366 unloadMediaPackages(processCids, uidArr, reportStatus); 21367 } 21368 } 21369 21370 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21371 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21372 final int size = infos.size(); 21373 final String[] packageNames = new String[size]; 21374 final int[] packageUids = new int[size]; 21375 for (int i = 0; i < size; i++) { 21376 final ApplicationInfo info = infos.get(i); 21377 packageNames[i] = info.packageName; 21378 packageUids[i] = info.uid; 21379 } 21380 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21381 finishedReceiver); 21382 } 21383 21384 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21385 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21386 sendResourcesChangedBroadcast(mediaStatus, replacing, 21387 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21388 } 21389 21390 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21391 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21392 int size = pkgList.length; 21393 if (size > 0) { 21394 // Send broadcasts here 21395 Bundle extras = new Bundle(); 21396 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21397 if (uidArr != null) { 21398 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21399 } 21400 if (replacing) { 21401 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21402 } 21403 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21404 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21405 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 21406 } 21407 } 21408 21409 /* 21410 * Look at potentially valid container ids from processCids If package 21411 * information doesn't match the one on record or package scanning fails, 21412 * the cid is added to list of removeCids. We currently don't delete stale 21413 * containers. 21414 */ 21415 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 21416 boolean externalStorage) { 21417 ArrayList<String> pkgList = new ArrayList<String>(); 21418 Set<AsecInstallArgs> keys = processCids.keySet(); 21419 21420 for (AsecInstallArgs args : keys) { 21421 String codePath = processCids.get(args); 21422 if (DEBUG_SD_INSTALL) 21423 Log.i(TAG, "Loading container : " + args.cid); 21424 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 21425 try { 21426 // Make sure there are no container errors first. 21427 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 21428 Slog.e(TAG, "Failed to mount cid : " + args.cid 21429 + " when installing from sdcard"); 21430 continue; 21431 } 21432 // Check code path here. 21433 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 21434 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 21435 + " does not match one in settings " + codePath); 21436 continue; 21437 } 21438 // Parse package 21439 int parseFlags = mDefParseFlags; 21440 if (args.isExternalAsec()) { 21441 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 21442 } 21443 if (args.isFwdLocked()) { 21444 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 21445 } 21446 21447 synchronized (mInstallLock) { 21448 PackageParser.Package pkg = null; 21449 try { 21450 // Sadly we don't know the package name yet to freeze it 21451 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 21452 SCAN_IGNORE_FROZEN, 0, null); 21453 } catch (PackageManagerException e) { 21454 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 21455 } 21456 // Scan the package 21457 if (pkg != null) { 21458 /* 21459 * TODO why is the lock being held? doPostInstall is 21460 * called in other places without the lock. This needs 21461 * to be straightened out. 21462 */ 21463 // writer 21464 synchronized (mPackages) { 21465 retCode = PackageManager.INSTALL_SUCCEEDED; 21466 pkgList.add(pkg.packageName); 21467 // Post process args 21468 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 21469 pkg.applicationInfo.uid); 21470 } 21471 } else { 21472 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 21473 } 21474 } 21475 21476 } finally { 21477 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 21478 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 21479 } 21480 } 21481 } 21482 // writer 21483 synchronized (mPackages) { 21484 // If the platform SDK has changed since the last time we booted, 21485 // we need to re-grant app permission to catch any new ones that 21486 // appear. This is really a hack, and means that apps can in some 21487 // cases get permissions that the user didn't initially explicitly 21488 // allow... it would be nice to have some better way to handle 21489 // this situation. 21490 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 21491 : mSettings.getInternalVersion(); 21492 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 21493 : StorageManager.UUID_PRIVATE_INTERNAL; 21494 21495 int updateFlags = UPDATE_PERMISSIONS_ALL; 21496 if (ver.sdkVersion != mSdkVersion) { 21497 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21498 + mSdkVersion + "; regranting permissions for external"); 21499 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21500 } 21501 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21502 21503 // Yay, everything is now upgraded 21504 ver.forceCurrent(); 21505 21506 // can downgrade to reader 21507 // Persist settings 21508 mSettings.writeLPr(); 21509 } 21510 // Send a broadcast to let everyone know we are done processing 21511 if (pkgList.size() > 0) { 21512 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 21513 } 21514 } 21515 21516 /* 21517 * Utility method to unload a list of specified containers 21518 */ 21519 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 21520 // Just unmount all valid containers. 21521 for (AsecInstallArgs arg : cidArgs) { 21522 synchronized (mInstallLock) { 21523 arg.doPostDeleteLI(false); 21524 } 21525 } 21526 } 21527 21528 /* 21529 * Unload packages mounted on external media. This involves deleting package 21530 * data from internal structures, sending broadcasts about disabled packages, 21531 * gc'ing to free up references, unmounting all secure containers 21532 * corresponding to packages on external media, and posting a 21533 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 21534 * that we always have to post this message if status has been requested no 21535 * matter what. 21536 */ 21537 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 21538 final boolean reportStatus) { 21539 if (DEBUG_SD_INSTALL) 21540 Log.i(TAG, "unloading media packages"); 21541 ArrayList<String> pkgList = new ArrayList<String>(); 21542 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 21543 final Set<AsecInstallArgs> keys = processCids.keySet(); 21544 for (AsecInstallArgs args : keys) { 21545 String pkgName = args.getPackageName(); 21546 if (DEBUG_SD_INSTALL) 21547 Log.i(TAG, "Trying to unload pkg : " + pkgName); 21548 // Delete package internally 21549 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21550 synchronized (mInstallLock) { 21551 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21552 final boolean res; 21553 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 21554 "unloadMediaPackages")) { 21555 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 21556 null); 21557 } 21558 if (res) { 21559 pkgList.add(pkgName); 21560 } else { 21561 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 21562 failedList.add(args); 21563 } 21564 } 21565 } 21566 21567 // reader 21568 synchronized (mPackages) { 21569 // We didn't update the settings after removing each package; 21570 // write them now for all packages. 21571 mSettings.writeLPr(); 21572 } 21573 21574 // We have to absolutely send UPDATED_MEDIA_STATUS only 21575 // after confirming that all the receivers processed the ordered 21576 // broadcast when packages get disabled, force a gc to clean things up. 21577 // and unload all the containers. 21578 if (pkgList.size() > 0) { 21579 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 21580 new IIntentReceiver.Stub() { 21581 public void performReceive(Intent intent, int resultCode, String data, 21582 Bundle extras, boolean ordered, boolean sticky, 21583 int sendingUser) throws RemoteException { 21584 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 21585 reportStatus ? 1 : 0, 1, keys); 21586 mHandler.sendMessage(msg); 21587 } 21588 }); 21589 } else { 21590 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 21591 keys); 21592 mHandler.sendMessage(msg); 21593 } 21594 } 21595 21596 private void loadPrivatePackages(final VolumeInfo vol) { 21597 mHandler.post(new Runnable() { 21598 @Override 21599 public void run() { 21600 loadPrivatePackagesInner(vol); 21601 } 21602 }); 21603 } 21604 21605 private void loadPrivatePackagesInner(VolumeInfo vol) { 21606 final String volumeUuid = vol.fsUuid; 21607 if (TextUtils.isEmpty(volumeUuid)) { 21608 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21609 return; 21610 } 21611 21612 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21613 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21614 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21615 21616 final VersionInfo ver; 21617 final List<PackageSetting> packages; 21618 synchronized (mPackages) { 21619 ver = mSettings.findOrCreateVersion(volumeUuid); 21620 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21621 } 21622 21623 for (PackageSetting ps : packages) { 21624 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21625 synchronized (mInstallLock) { 21626 final PackageParser.Package pkg; 21627 try { 21628 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21629 loaded.add(pkg.applicationInfo); 21630 21631 } catch (PackageManagerException e) { 21632 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21633 } 21634 21635 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21636 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21637 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21638 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21639 } 21640 } 21641 } 21642 21643 // Reconcile app data for all started/unlocked users 21644 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21645 final UserManager um = mContext.getSystemService(UserManager.class); 21646 UserManagerInternal umInternal = getUserManagerInternal(); 21647 for (UserInfo user : um.getUsers()) { 21648 final int flags; 21649 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21650 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21651 } else if (umInternal.isUserRunning(user.id)) { 21652 flags = StorageManager.FLAG_STORAGE_DE; 21653 } else { 21654 continue; 21655 } 21656 21657 try { 21658 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21659 synchronized (mInstallLock) { 21660 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21661 } 21662 } catch (IllegalStateException e) { 21663 // Device was probably ejected, and we'll process that event momentarily 21664 Slog.w(TAG, "Failed to prepare storage: " + e); 21665 } 21666 } 21667 21668 synchronized (mPackages) { 21669 int updateFlags = UPDATE_PERMISSIONS_ALL; 21670 if (ver.sdkVersion != mSdkVersion) { 21671 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21672 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21673 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 21674 } 21675 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 21676 21677 // Yay, everything is now upgraded 21678 ver.forceCurrent(); 21679 21680 mSettings.writeLPr(); 21681 } 21682 21683 for (PackageFreezer freezer : freezers) { 21684 freezer.close(); 21685 } 21686 21687 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21688 sendResourcesChangedBroadcast(true, false, loaded, null); 21689 } 21690 21691 private void unloadPrivatePackages(final VolumeInfo vol) { 21692 mHandler.post(new Runnable() { 21693 @Override 21694 public void run() { 21695 unloadPrivatePackagesInner(vol); 21696 } 21697 }); 21698 } 21699 21700 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21701 final String volumeUuid = vol.fsUuid; 21702 if (TextUtils.isEmpty(volumeUuid)) { 21703 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21704 return; 21705 } 21706 21707 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21708 synchronized (mInstallLock) { 21709 synchronized (mPackages) { 21710 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21711 for (PackageSetting ps : packages) { 21712 if (ps.pkg == null) continue; 21713 21714 final ApplicationInfo info = ps.pkg.applicationInfo; 21715 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21716 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 21717 21718 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21719 "unloadPrivatePackagesInner")) { 21720 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21721 false, null)) { 21722 unloaded.add(info); 21723 } else { 21724 Slog.w(TAG, "Failed to unload " + ps.codePath); 21725 } 21726 } 21727 21728 // Try very hard to release any references to this package 21729 // so we don't risk the system server being killed due to 21730 // open FDs 21731 AttributeCache.instance().removePackage(ps.name); 21732 } 21733 21734 mSettings.writeLPr(); 21735 } 21736 } 21737 21738 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21739 sendResourcesChangedBroadcast(false, false, unloaded, null); 21740 21741 // Try very hard to release any references to this path so we don't risk 21742 // the system server being killed due to open FDs 21743 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21744 21745 for (int i = 0; i < 3; i++) { 21746 System.gc(); 21747 System.runFinalization(); 21748 } 21749 } 21750 21751 private void assertPackageKnown(String volumeUuid, String packageName) 21752 throws PackageManagerException { 21753 synchronized (mPackages) { 21754 // Normalize package name to handle renamed packages 21755 packageName = normalizePackageNameLPr(packageName); 21756 21757 final PackageSetting ps = mSettings.mPackages.get(packageName); 21758 if (ps == null) { 21759 throw new PackageManagerException("Package " + packageName + " is unknown"); 21760 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21761 throw new PackageManagerException( 21762 "Package " + packageName + " found on unknown volume " + volumeUuid 21763 + "; expected volume " + ps.volumeUuid); 21764 } 21765 } 21766 } 21767 21768 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21769 throws PackageManagerException { 21770 synchronized (mPackages) { 21771 // Normalize package name to handle renamed packages 21772 packageName = normalizePackageNameLPr(packageName); 21773 21774 final PackageSetting ps = mSettings.mPackages.get(packageName); 21775 if (ps == null) { 21776 throw new PackageManagerException("Package " + packageName + " is unknown"); 21777 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21778 throw new PackageManagerException( 21779 "Package " + packageName + " found on unknown volume " + volumeUuid 21780 + "; expected volume " + ps.volumeUuid); 21781 } else if (!ps.getInstalled(userId)) { 21782 throw new PackageManagerException( 21783 "Package " + packageName + " not installed for user " + userId); 21784 } 21785 } 21786 } 21787 21788 private List<String> collectAbsoluteCodePaths() { 21789 synchronized (mPackages) { 21790 List<String> codePaths = new ArrayList<>(); 21791 final int packageCount = mSettings.mPackages.size(); 21792 for (int i = 0; i < packageCount; i++) { 21793 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21794 codePaths.add(ps.codePath.getAbsolutePath()); 21795 } 21796 return codePaths; 21797 } 21798 } 21799 21800 /** 21801 * Examine all apps present on given mounted volume, and destroy apps that 21802 * aren't expected, either due to uninstallation or reinstallation on 21803 * another volume. 21804 */ 21805 private void reconcileApps(String volumeUuid) { 21806 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21807 List<File> filesToDelete = null; 21808 21809 final File[] files = FileUtils.listFilesOrEmpty( 21810 Environment.getDataAppDirectory(volumeUuid)); 21811 for (File file : files) { 21812 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21813 && !PackageInstallerService.isStageName(file.getName()); 21814 if (!isPackage) { 21815 // Ignore entries which are not packages 21816 continue; 21817 } 21818 21819 String absolutePath = file.getAbsolutePath(); 21820 21821 boolean pathValid = false; 21822 final int absoluteCodePathCount = absoluteCodePaths.size(); 21823 for (int i = 0; i < absoluteCodePathCount; i++) { 21824 String absoluteCodePath = absoluteCodePaths.get(i); 21825 if (absolutePath.startsWith(absoluteCodePath)) { 21826 pathValid = true; 21827 break; 21828 } 21829 } 21830 21831 if (!pathValid) { 21832 if (filesToDelete == null) { 21833 filesToDelete = new ArrayList<>(); 21834 } 21835 filesToDelete.add(file); 21836 } 21837 } 21838 21839 if (filesToDelete != null) { 21840 final int fileToDeleteCount = filesToDelete.size(); 21841 for (int i = 0; i < fileToDeleteCount; i++) { 21842 File fileToDelete = filesToDelete.get(i); 21843 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21844 synchronized (mInstallLock) { 21845 removeCodePathLI(fileToDelete); 21846 } 21847 } 21848 } 21849 } 21850 21851 /** 21852 * Reconcile all app data for the given user. 21853 * <p> 21854 * Verifies that directories exist and that ownership and labeling is 21855 * correct for all installed apps on all mounted volumes. 21856 */ 21857 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21858 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21859 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21860 final String volumeUuid = vol.getFsUuid(); 21861 synchronized (mInstallLock) { 21862 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21863 } 21864 } 21865 } 21866 21867 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21868 boolean migrateAppData) { 21869 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21870 } 21871 21872 /** 21873 * Reconcile all app data on given mounted volume. 21874 * <p> 21875 * Destroys app data that isn't expected, either due to uninstallation or 21876 * reinstallation on another volume. 21877 * <p> 21878 * Verifies that directories exist and that ownership and labeling is 21879 * correct for all installed apps. 21880 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21881 */ 21882 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21883 boolean migrateAppData, boolean onlyCoreApps) { 21884 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21885 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21886 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21887 21888 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21889 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21890 21891 // First look for stale data that doesn't belong, and check if things 21892 // have changed since we did our last restorecon 21893 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21894 if (StorageManager.isFileEncryptedNativeOrEmulated() 21895 && !StorageManager.isUserKeyUnlocked(userId)) { 21896 throw new RuntimeException( 21897 "Yikes, someone asked us to reconcile CE storage while " + userId 21898 + " was still locked; this would have caused massive data loss!"); 21899 } 21900 21901 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21902 for (File file : files) { 21903 final String packageName = file.getName(); 21904 try { 21905 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21906 } catch (PackageManagerException e) { 21907 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21908 try { 21909 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21910 StorageManager.FLAG_STORAGE_CE, 0); 21911 } catch (InstallerException e2) { 21912 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21913 } 21914 } 21915 } 21916 } 21917 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21918 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21919 for (File file : files) { 21920 final String packageName = file.getName(); 21921 try { 21922 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21923 } catch (PackageManagerException e) { 21924 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21925 try { 21926 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21927 StorageManager.FLAG_STORAGE_DE, 0); 21928 } catch (InstallerException e2) { 21929 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21930 } 21931 } 21932 } 21933 } 21934 21935 // Ensure that data directories are ready to roll for all packages 21936 // installed for this volume and user 21937 final List<PackageSetting> packages; 21938 synchronized (mPackages) { 21939 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21940 } 21941 int preparedCount = 0; 21942 for (PackageSetting ps : packages) { 21943 final String packageName = ps.name; 21944 if (ps.pkg == null) { 21945 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21946 // TODO: might be due to legacy ASEC apps; we should circle back 21947 // and reconcile again once they're scanned 21948 continue; 21949 } 21950 // Skip non-core apps if requested 21951 if (onlyCoreApps && !ps.pkg.coreApp) { 21952 result.add(packageName); 21953 continue; 21954 } 21955 21956 if (ps.getInstalled(userId)) { 21957 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21958 preparedCount++; 21959 } 21960 } 21961 21962 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21963 return result; 21964 } 21965 21966 /** 21967 * Prepare app data for the given app just after it was installed or 21968 * upgraded. This method carefully only touches users that it's installed 21969 * for, and it forces a restorecon to handle any seinfo changes. 21970 * <p> 21971 * Verifies that directories exist and that ownership and labeling is 21972 * correct for all installed apps. If there is an ownership mismatch, it 21973 * will try recovering system apps by wiping data; third-party app data is 21974 * left intact. 21975 * <p> 21976 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21977 */ 21978 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21979 final PackageSetting ps; 21980 synchronized (mPackages) { 21981 ps = mSettings.mPackages.get(pkg.packageName); 21982 mSettings.writeKernelMappingLPr(ps); 21983 } 21984 21985 final UserManager um = mContext.getSystemService(UserManager.class); 21986 UserManagerInternal umInternal = getUserManagerInternal(); 21987 for (UserInfo user : um.getUsers()) { 21988 final int flags; 21989 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21990 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21991 } else if (umInternal.isUserRunning(user.id)) { 21992 flags = StorageManager.FLAG_STORAGE_DE; 21993 } else { 21994 continue; 21995 } 21996 21997 if (ps.getInstalled(user.id)) { 21998 // TODO: when user data is locked, mark that we're still dirty 21999 prepareAppDataLIF(pkg, user.id, flags); 22000 } 22001 } 22002 } 22003 22004 /** 22005 * Prepare app data for the given app. 22006 * <p> 22007 * Verifies that directories exist and that ownership and labeling is 22008 * correct for all installed apps. If there is an ownership mismatch, this 22009 * will try recovering system apps by wiping data; third-party app data is 22010 * left intact. 22011 */ 22012 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22013 if (pkg == null) { 22014 Slog.wtf(TAG, "Package was null!", new Throwable()); 22015 return; 22016 } 22017 prepareAppDataLeafLIF(pkg, userId, flags); 22018 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22019 for (int i = 0; i < childCount; i++) { 22020 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22021 } 22022 } 22023 22024 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22025 boolean maybeMigrateAppData) { 22026 prepareAppDataLIF(pkg, userId, flags); 22027 22028 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22029 // We may have just shuffled around app data directories, so 22030 // prepare them one more time 22031 prepareAppDataLIF(pkg, userId, flags); 22032 } 22033 } 22034 22035 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22036 if (DEBUG_APP_DATA) { 22037 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22038 + Integer.toHexString(flags)); 22039 } 22040 22041 final String volumeUuid = pkg.volumeUuid; 22042 final String packageName = pkg.packageName; 22043 final ApplicationInfo app = pkg.applicationInfo; 22044 final int appId = UserHandle.getAppId(app.uid); 22045 22046 Preconditions.checkNotNull(app.seInfo); 22047 22048 long ceDataInode = -1; 22049 try { 22050 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22051 appId, app.seInfo, app.targetSdkVersion); 22052 } catch (InstallerException e) { 22053 if (app.isSystemApp()) { 22054 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22055 + ", but trying to recover: " + e); 22056 destroyAppDataLeafLIF(pkg, userId, flags); 22057 try { 22058 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22059 appId, app.seInfo, app.targetSdkVersion); 22060 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22061 } catch (InstallerException e2) { 22062 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22063 } 22064 } else { 22065 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22066 } 22067 } 22068 22069 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22070 // TODO: mark this structure as dirty so we persist it! 22071 synchronized (mPackages) { 22072 final PackageSetting ps = mSettings.mPackages.get(packageName); 22073 if (ps != null) { 22074 ps.setCeDataInode(ceDataInode, userId); 22075 } 22076 } 22077 } 22078 22079 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22080 } 22081 22082 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22083 if (pkg == null) { 22084 Slog.wtf(TAG, "Package was null!", new Throwable()); 22085 return; 22086 } 22087 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22088 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22089 for (int i = 0; i < childCount; i++) { 22090 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22091 } 22092 } 22093 22094 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22095 final String volumeUuid = pkg.volumeUuid; 22096 final String packageName = pkg.packageName; 22097 final ApplicationInfo app = pkg.applicationInfo; 22098 22099 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22100 // Create a native library symlink only if we have native libraries 22101 // and if the native libraries are 32 bit libraries. We do not provide 22102 // this symlink for 64 bit libraries. 22103 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22104 final String nativeLibPath = app.nativeLibraryDir; 22105 try { 22106 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22107 nativeLibPath, userId); 22108 } catch (InstallerException e) { 22109 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22110 } 22111 } 22112 } 22113 } 22114 22115 /** 22116 * For system apps on non-FBE devices, this method migrates any existing 22117 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22118 * requested by the app. 22119 */ 22120 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22121 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 22122 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22123 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22124 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22125 try { 22126 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22127 storageTarget); 22128 } catch (InstallerException e) { 22129 logCriticalInfo(Log.WARN, 22130 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22131 } 22132 return true; 22133 } else { 22134 return false; 22135 } 22136 } 22137 22138 public PackageFreezer freezePackage(String packageName, String killReason) { 22139 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22140 } 22141 22142 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22143 return new PackageFreezer(packageName, userId, killReason); 22144 } 22145 22146 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22147 String killReason) { 22148 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22149 } 22150 22151 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22152 String killReason) { 22153 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22154 return new PackageFreezer(); 22155 } else { 22156 return freezePackage(packageName, userId, killReason); 22157 } 22158 } 22159 22160 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22161 String killReason) { 22162 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22163 } 22164 22165 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22166 String killReason) { 22167 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22168 return new PackageFreezer(); 22169 } else { 22170 return freezePackage(packageName, userId, killReason); 22171 } 22172 } 22173 22174 /** 22175 * Class that freezes and kills the given package upon creation, and 22176 * unfreezes it upon closing. This is typically used when doing surgery on 22177 * app code/data to prevent the app from running while you're working. 22178 */ 22179 private class PackageFreezer implements AutoCloseable { 22180 private final String mPackageName; 22181 private final PackageFreezer[] mChildren; 22182 22183 private final boolean mWeFroze; 22184 22185 private final AtomicBoolean mClosed = new AtomicBoolean(); 22186 private final CloseGuard mCloseGuard = CloseGuard.get(); 22187 22188 /** 22189 * Create and return a stub freezer that doesn't actually do anything, 22190 * typically used when someone requested 22191 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22192 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22193 */ 22194 public PackageFreezer() { 22195 mPackageName = null; 22196 mChildren = null; 22197 mWeFroze = false; 22198 mCloseGuard.open("close"); 22199 } 22200 22201 public PackageFreezer(String packageName, int userId, String killReason) { 22202 synchronized (mPackages) { 22203 mPackageName = packageName; 22204 mWeFroze = mFrozenPackages.add(mPackageName); 22205 22206 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22207 if (ps != null) { 22208 killApplication(ps.name, ps.appId, userId, killReason); 22209 } 22210 22211 final PackageParser.Package p = mPackages.get(packageName); 22212 if (p != null && p.childPackages != null) { 22213 final int N = p.childPackages.size(); 22214 mChildren = new PackageFreezer[N]; 22215 for (int i = 0; i < N; i++) { 22216 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22217 userId, killReason); 22218 } 22219 } else { 22220 mChildren = null; 22221 } 22222 } 22223 mCloseGuard.open("close"); 22224 } 22225 22226 @Override 22227 protected void finalize() throws Throwable { 22228 try { 22229 mCloseGuard.warnIfOpen(); 22230 close(); 22231 } finally { 22232 super.finalize(); 22233 } 22234 } 22235 22236 @Override 22237 public void close() { 22238 mCloseGuard.close(); 22239 if (mClosed.compareAndSet(false, true)) { 22240 synchronized (mPackages) { 22241 if (mWeFroze) { 22242 mFrozenPackages.remove(mPackageName); 22243 } 22244 22245 if (mChildren != null) { 22246 for (PackageFreezer freezer : mChildren) { 22247 freezer.close(); 22248 } 22249 } 22250 } 22251 } 22252 } 22253 } 22254 22255 /** 22256 * Verify that given package is currently frozen. 22257 */ 22258 private void checkPackageFrozen(String packageName) { 22259 synchronized (mPackages) { 22260 if (!mFrozenPackages.contains(packageName)) { 22261 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22262 } 22263 } 22264 } 22265 22266 @Override 22267 public int movePackage(final String packageName, final String volumeUuid) { 22268 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22269 22270 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 22271 final int moveId = mNextMoveId.getAndIncrement(); 22272 mHandler.post(new Runnable() { 22273 @Override 22274 public void run() { 22275 try { 22276 movePackageInternal(packageName, volumeUuid, moveId, user); 22277 } catch (PackageManagerException e) { 22278 Slog.w(TAG, "Failed to move " + packageName, e); 22279 mMoveCallbacks.notifyStatusChanged(moveId, 22280 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22281 } 22282 } 22283 }); 22284 return moveId; 22285 } 22286 22287 private void movePackageInternal(final String packageName, final String volumeUuid, 22288 final int moveId, UserHandle user) throws PackageManagerException { 22289 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22290 final PackageManager pm = mContext.getPackageManager(); 22291 22292 final boolean currentAsec; 22293 final String currentVolumeUuid; 22294 final File codeFile; 22295 final String installerPackageName; 22296 final String packageAbiOverride; 22297 final int appId; 22298 final String seinfo; 22299 final String label; 22300 final int targetSdkVersion; 22301 final PackageFreezer freezer; 22302 final int[] installedUserIds; 22303 22304 // reader 22305 synchronized (mPackages) { 22306 final PackageParser.Package pkg = mPackages.get(packageName); 22307 final PackageSetting ps = mSettings.mPackages.get(packageName); 22308 if (pkg == null || ps == null) { 22309 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22310 } 22311 22312 if (pkg.applicationInfo.isSystemApp()) { 22313 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22314 "Cannot move system application"); 22315 } 22316 22317 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22318 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22319 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22320 if (isInternalStorage && !allow3rdPartyOnInternal) { 22321 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22322 "3rd party apps are not allowed on internal storage"); 22323 } 22324 22325 if (pkg.applicationInfo.isExternalAsec()) { 22326 currentAsec = true; 22327 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22328 } else if (pkg.applicationInfo.isForwardLocked()) { 22329 currentAsec = true; 22330 currentVolumeUuid = "forward_locked"; 22331 } else { 22332 currentAsec = false; 22333 currentVolumeUuid = ps.volumeUuid; 22334 22335 final File probe = new File(pkg.codePath); 22336 final File probeOat = new File(probe, "oat"); 22337 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22338 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22339 "Move only supported for modern cluster style installs"); 22340 } 22341 } 22342 22343 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22344 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22345 "Package already moved to " + volumeUuid); 22346 } 22347 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22348 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22349 "Device admin cannot be moved"); 22350 } 22351 22352 if (mFrozenPackages.contains(packageName)) { 22353 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22354 "Failed to move already frozen package"); 22355 } 22356 22357 codeFile = new File(pkg.codePath); 22358 installerPackageName = ps.installerPackageName; 22359 packageAbiOverride = ps.cpuAbiOverrideString; 22360 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22361 seinfo = pkg.applicationInfo.seInfo; 22362 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22363 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22364 freezer = freezePackage(packageName, "movePackageInternal"); 22365 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22366 } 22367 22368 final Bundle extras = new Bundle(); 22369 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22370 extras.putString(Intent.EXTRA_TITLE, label); 22371 mMoveCallbacks.notifyCreated(moveId, extras); 22372 22373 int installFlags; 22374 final boolean moveCompleteApp; 22375 final File measurePath; 22376 22377 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22378 installFlags = INSTALL_INTERNAL; 22379 moveCompleteApp = !currentAsec; 22380 measurePath = Environment.getDataAppDirectory(volumeUuid); 22381 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22382 installFlags = INSTALL_EXTERNAL; 22383 moveCompleteApp = false; 22384 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22385 } else { 22386 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22387 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22388 || !volume.isMountedWritable()) { 22389 freezer.close(); 22390 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22391 "Move location not mounted private volume"); 22392 } 22393 22394 Preconditions.checkState(!currentAsec); 22395 22396 installFlags = INSTALL_INTERNAL; 22397 moveCompleteApp = true; 22398 measurePath = Environment.getDataAppDirectory(volumeUuid); 22399 } 22400 22401 final PackageStats stats = new PackageStats(null, -1); 22402 synchronized (mInstaller) { 22403 for (int userId : installedUserIds) { 22404 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22405 freezer.close(); 22406 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22407 "Failed to measure package size"); 22408 } 22409 } 22410 } 22411 22412 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22413 + stats.dataSize); 22414 22415 final long startFreeBytes = measurePath.getUsableSpace(); 22416 final long sizeBytes; 22417 if (moveCompleteApp) { 22418 sizeBytes = stats.codeSize + stats.dataSize; 22419 } else { 22420 sizeBytes = stats.codeSize; 22421 } 22422 22423 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22424 freezer.close(); 22425 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22426 "Not enough free space to move"); 22427 } 22428 22429 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22430 22431 final CountDownLatch installedLatch = new CountDownLatch(1); 22432 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22433 @Override 22434 public void onUserActionRequired(Intent intent) throws RemoteException { 22435 throw new IllegalStateException(); 22436 } 22437 22438 @Override 22439 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22440 Bundle extras) throws RemoteException { 22441 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22442 + PackageManager.installStatusToString(returnCode, msg)); 22443 22444 installedLatch.countDown(); 22445 freezer.close(); 22446 22447 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22448 switch (status) { 22449 case PackageInstaller.STATUS_SUCCESS: 22450 mMoveCallbacks.notifyStatusChanged(moveId, 22451 PackageManager.MOVE_SUCCEEDED); 22452 break; 22453 case PackageInstaller.STATUS_FAILURE_STORAGE: 22454 mMoveCallbacks.notifyStatusChanged(moveId, 22455 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22456 break; 22457 default: 22458 mMoveCallbacks.notifyStatusChanged(moveId, 22459 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22460 break; 22461 } 22462 } 22463 }; 22464 22465 final MoveInfo move; 22466 if (moveCompleteApp) { 22467 // Kick off a thread to report progress estimates 22468 new Thread() { 22469 @Override 22470 public void run() { 22471 while (true) { 22472 try { 22473 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22474 break; 22475 } 22476 } catch (InterruptedException ignored) { 22477 } 22478 22479 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22480 final int progress = 10 + (int) MathUtils.constrain( 22481 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22482 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22483 } 22484 } 22485 }.start(); 22486 22487 final String dataAppName = codeFile.getName(); 22488 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22489 dataAppName, appId, seinfo, targetSdkVersion); 22490 } else { 22491 move = null; 22492 } 22493 22494 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22495 22496 final Message msg = mHandler.obtainMessage(INIT_COPY); 22497 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22498 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22499 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22500 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/, 22501 PackageManager.INSTALL_REASON_UNKNOWN); 22502 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22503 msg.obj = params; 22504 22505 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22506 System.identityHashCode(msg.obj)); 22507 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22508 System.identityHashCode(msg.obj)); 22509 22510 mHandler.sendMessage(msg); 22511 } 22512 22513 @Override 22514 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22515 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22516 22517 final int realMoveId = mNextMoveId.getAndIncrement(); 22518 final Bundle extras = new Bundle(); 22519 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22520 mMoveCallbacks.notifyCreated(realMoveId, extras); 22521 22522 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22523 @Override 22524 public void onCreated(int moveId, Bundle extras) { 22525 // Ignored 22526 } 22527 22528 @Override 22529 public void onStatusChanged(int moveId, int status, long estMillis) { 22530 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22531 } 22532 }; 22533 22534 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22535 storage.setPrimaryStorageUuid(volumeUuid, callback); 22536 return realMoveId; 22537 } 22538 22539 @Override 22540 public int getMoveStatus(int moveId) { 22541 mContext.enforceCallingOrSelfPermission( 22542 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22543 return mMoveCallbacks.mLastStatus.get(moveId); 22544 } 22545 22546 @Override 22547 public void registerMoveCallback(IPackageMoveObserver callback) { 22548 mContext.enforceCallingOrSelfPermission( 22549 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22550 mMoveCallbacks.register(callback); 22551 } 22552 22553 @Override 22554 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22555 mContext.enforceCallingOrSelfPermission( 22556 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22557 mMoveCallbacks.unregister(callback); 22558 } 22559 22560 @Override 22561 public boolean setInstallLocation(int loc) { 22562 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22563 null); 22564 if (getInstallLocation() == loc) { 22565 return true; 22566 } 22567 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22568 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22569 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22570 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22571 return true; 22572 } 22573 return false; 22574 } 22575 22576 @Override 22577 public int getInstallLocation() { 22578 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22579 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22580 PackageHelper.APP_INSTALL_AUTO); 22581 } 22582 22583 /** Called by UserManagerService */ 22584 void cleanUpUser(UserManagerService userManager, int userHandle) { 22585 synchronized (mPackages) { 22586 mDirtyUsers.remove(userHandle); 22587 mUserNeedsBadging.delete(userHandle); 22588 mSettings.removeUserLPw(userHandle); 22589 mPendingBroadcasts.remove(userHandle); 22590 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22591 removeUnusedPackagesLPw(userManager, userHandle); 22592 } 22593 } 22594 22595 /** 22596 * We're removing userHandle and would like to remove any downloaded packages 22597 * that are no longer in use by any other user. 22598 * @param userHandle the user being removed 22599 */ 22600 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22601 final boolean DEBUG_CLEAN_APKS = false; 22602 int [] users = userManager.getUserIds(); 22603 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22604 while (psit.hasNext()) { 22605 PackageSetting ps = psit.next(); 22606 if (ps.pkg == null) { 22607 continue; 22608 } 22609 final String packageName = ps.pkg.packageName; 22610 // Skip over if system app 22611 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22612 continue; 22613 } 22614 if (DEBUG_CLEAN_APKS) { 22615 Slog.i(TAG, "Checking package " + packageName); 22616 } 22617 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22618 if (keep) { 22619 if (DEBUG_CLEAN_APKS) { 22620 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22621 } 22622 } else { 22623 for (int i = 0; i < users.length; i++) { 22624 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22625 keep = true; 22626 if (DEBUG_CLEAN_APKS) { 22627 Slog.i(TAG, " Keeping package " + packageName + " for user " 22628 + users[i]); 22629 } 22630 break; 22631 } 22632 } 22633 } 22634 if (!keep) { 22635 if (DEBUG_CLEAN_APKS) { 22636 Slog.i(TAG, " Removing package " + packageName); 22637 } 22638 mHandler.post(new Runnable() { 22639 public void run() { 22640 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22641 userHandle, 0); 22642 } //end run 22643 }); 22644 } 22645 } 22646 } 22647 22648 /** Called by UserManagerService */ 22649 void createNewUser(int userId, String[] disallowedPackages) { 22650 synchronized (mInstallLock) { 22651 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22652 } 22653 synchronized (mPackages) { 22654 scheduleWritePackageRestrictionsLocked(userId); 22655 scheduleWritePackageListLocked(userId); 22656 applyFactoryDefaultBrowserLPw(userId); 22657 primeDomainVerificationsLPw(userId); 22658 } 22659 } 22660 22661 void onNewUserCreated(final int userId) { 22662 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22663 // If permission review for legacy apps is required, we represent 22664 // dagerous permissions for such apps as always granted runtime 22665 // permissions to keep per user flag state whether review is needed. 22666 // Hence, if a new user is added we have to propagate dangerous 22667 // permission grants for these legacy apps. 22668 if (mPermissionReviewRequired) { 22669 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 22670 | UPDATE_PERMISSIONS_REPLACE_ALL); 22671 } 22672 } 22673 22674 @Override 22675 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22676 mContext.enforceCallingOrSelfPermission( 22677 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22678 "Only package verification agents can read the verifier device identity"); 22679 22680 synchronized (mPackages) { 22681 return mSettings.getVerifierDeviceIdentityLPw(); 22682 } 22683 } 22684 22685 @Override 22686 public void setPermissionEnforced(String permission, boolean enforced) { 22687 // TODO: Now that we no longer change GID for storage, this should to away. 22688 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22689 "setPermissionEnforced"); 22690 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22691 synchronized (mPackages) { 22692 if (mSettings.mReadExternalStorageEnforced == null 22693 || mSettings.mReadExternalStorageEnforced != enforced) { 22694 mSettings.mReadExternalStorageEnforced = enforced; 22695 mSettings.writeLPr(); 22696 } 22697 } 22698 // kill any non-foreground processes so we restart them and 22699 // grant/revoke the GID. 22700 final IActivityManager am = ActivityManager.getService(); 22701 if (am != null) { 22702 final long token = Binder.clearCallingIdentity(); 22703 try { 22704 am.killProcessesBelowForeground("setPermissionEnforcement"); 22705 } catch (RemoteException e) { 22706 } finally { 22707 Binder.restoreCallingIdentity(token); 22708 } 22709 } 22710 } else { 22711 throw new IllegalArgumentException("No selective enforcement for " + permission); 22712 } 22713 } 22714 22715 @Override 22716 @Deprecated 22717 public boolean isPermissionEnforced(String permission) { 22718 return true; 22719 } 22720 22721 @Override 22722 public boolean isStorageLow() { 22723 final long token = Binder.clearCallingIdentity(); 22724 try { 22725 final DeviceStorageMonitorInternal 22726 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22727 if (dsm != null) { 22728 return dsm.isMemoryLow(); 22729 } else { 22730 return false; 22731 } 22732 } finally { 22733 Binder.restoreCallingIdentity(token); 22734 } 22735 } 22736 22737 @Override 22738 public IPackageInstaller getPackageInstaller() { 22739 return mInstallerService; 22740 } 22741 22742 private boolean userNeedsBadging(int userId) { 22743 int index = mUserNeedsBadging.indexOfKey(userId); 22744 if (index < 0) { 22745 final UserInfo userInfo; 22746 final long token = Binder.clearCallingIdentity(); 22747 try { 22748 userInfo = sUserManager.getUserInfo(userId); 22749 } finally { 22750 Binder.restoreCallingIdentity(token); 22751 } 22752 final boolean b; 22753 if (userInfo != null && userInfo.isManagedProfile()) { 22754 b = true; 22755 } else { 22756 b = false; 22757 } 22758 mUserNeedsBadging.put(userId, b); 22759 return b; 22760 } 22761 return mUserNeedsBadging.valueAt(index); 22762 } 22763 22764 @Override 22765 public KeySet getKeySetByAlias(String packageName, String alias) { 22766 if (packageName == null || alias == null) { 22767 return null; 22768 } 22769 synchronized(mPackages) { 22770 final PackageParser.Package pkg = mPackages.get(packageName); 22771 if (pkg == null) { 22772 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22773 throw new IllegalArgumentException("Unknown package: " + packageName); 22774 } 22775 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22776 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22777 } 22778 } 22779 22780 @Override 22781 public KeySet getSigningKeySet(String packageName) { 22782 if (packageName == null) { 22783 return null; 22784 } 22785 synchronized(mPackages) { 22786 final PackageParser.Package pkg = mPackages.get(packageName); 22787 if (pkg == null) { 22788 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22789 throw new IllegalArgumentException("Unknown package: " + packageName); 22790 } 22791 if (pkg.applicationInfo.uid != Binder.getCallingUid() 22792 && Process.SYSTEM_UID != Binder.getCallingUid()) { 22793 throw new SecurityException("May not access signing KeySet of other apps."); 22794 } 22795 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22796 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22797 } 22798 } 22799 22800 @Override 22801 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22802 if (packageName == null || ks == null) { 22803 return false; 22804 } 22805 synchronized(mPackages) { 22806 final PackageParser.Package pkg = mPackages.get(packageName); 22807 if (pkg == null) { 22808 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22809 throw new IllegalArgumentException("Unknown package: " + packageName); 22810 } 22811 IBinder ksh = ks.getToken(); 22812 if (ksh instanceof KeySetHandle) { 22813 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22814 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22815 } 22816 return false; 22817 } 22818 } 22819 22820 @Override 22821 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22822 if (packageName == null || ks == null) { 22823 return false; 22824 } 22825 synchronized(mPackages) { 22826 final PackageParser.Package pkg = mPackages.get(packageName); 22827 if (pkg == null) { 22828 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22829 throw new IllegalArgumentException("Unknown package: " + packageName); 22830 } 22831 IBinder ksh = ks.getToken(); 22832 if (ksh instanceof KeySetHandle) { 22833 KeySetManagerService ksms = mSettings.mKeySetManagerService; 22834 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22835 } 22836 return false; 22837 } 22838 } 22839 22840 private void deletePackageIfUnusedLPr(final String packageName) { 22841 PackageSetting ps = mSettings.mPackages.get(packageName); 22842 if (ps == null) { 22843 return; 22844 } 22845 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22846 // TODO Implement atomic delete if package is unused 22847 // It is currently possible that the package will be deleted even if it is installed 22848 // after this method returns. 22849 mHandler.post(new Runnable() { 22850 public void run() { 22851 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22852 0, PackageManager.DELETE_ALL_USERS); 22853 } 22854 }); 22855 } 22856 } 22857 22858 /** 22859 * Check and throw if the given before/after packages would be considered a 22860 * downgrade. 22861 */ 22862 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22863 throws PackageManagerException { 22864 if (after.versionCode < before.mVersionCode) { 22865 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22866 "Update version code " + after.versionCode + " is older than current " 22867 + before.mVersionCode); 22868 } else if (after.versionCode == before.mVersionCode) { 22869 if (after.baseRevisionCode < before.baseRevisionCode) { 22870 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22871 "Update base revision code " + after.baseRevisionCode 22872 + " is older than current " + before.baseRevisionCode); 22873 } 22874 22875 if (!ArrayUtils.isEmpty(after.splitNames)) { 22876 for (int i = 0; i < after.splitNames.length; i++) { 22877 final String splitName = after.splitNames[i]; 22878 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22879 if (j != -1) { 22880 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22881 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22882 "Update split " + splitName + " revision code " 22883 + after.splitRevisionCodes[i] + " is older than current " 22884 + before.splitRevisionCodes[j]); 22885 } 22886 } 22887 } 22888 } 22889 } 22890 } 22891 22892 private static class MoveCallbacks extends Handler { 22893 private static final int MSG_CREATED = 1; 22894 private static final int MSG_STATUS_CHANGED = 2; 22895 22896 private final RemoteCallbackList<IPackageMoveObserver> 22897 mCallbacks = new RemoteCallbackList<>(); 22898 22899 private final SparseIntArray mLastStatus = new SparseIntArray(); 22900 22901 public MoveCallbacks(Looper looper) { 22902 super(looper); 22903 } 22904 22905 public void register(IPackageMoveObserver callback) { 22906 mCallbacks.register(callback); 22907 } 22908 22909 public void unregister(IPackageMoveObserver callback) { 22910 mCallbacks.unregister(callback); 22911 } 22912 22913 @Override 22914 public void handleMessage(Message msg) { 22915 final SomeArgs args = (SomeArgs) msg.obj; 22916 final int n = mCallbacks.beginBroadcast(); 22917 for (int i = 0; i < n; i++) { 22918 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22919 try { 22920 invokeCallback(callback, msg.what, args); 22921 } catch (RemoteException ignored) { 22922 } 22923 } 22924 mCallbacks.finishBroadcast(); 22925 args.recycle(); 22926 } 22927 22928 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22929 throws RemoteException { 22930 switch (what) { 22931 case MSG_CREATED: { 22932 callback.onCreated(args.argi1, (Bundle) args.arg2); 22933 break; 22934 } 22935 case MSG_STATUS_CHANGED: { 22936 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22937 break; 22938 } 22939 } 22940 } 22941 22942 private void notifyCreated(int moveId, Bundle extras) { 22943 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22944 22945 final SomeArgs args = SomeArgs.obtain(); 22946 args.argi1 = moveId; 22947 args.arg2 = extras; 22948 obtainMessage(MSG_CREATED, args).sendToTarget(); 22949 } 22950 22951 private void notifyStatusChanged(int moveId, int status) { 22952 notifyStatusChanged(moveId, status, -1); 22953 } 22954 22955 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22956 Slog.v(TAG, "Move " + moveId + " status " + status); 22957 22958 final SomeArgs args = SomeArgs.obtain(); 22959 args.argi1 = moveId; 22960 args.argi2 = status; 22961 args.arg3 = estMillis; 22962 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22963 22964 synchronized (mLastStatus) { 22965 mLastStatus.put(moveId, status); 22966 } 22967 } 22968 } 22969 22970 private final static class OnPermissionChangeListeners extends Handler { 22971 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22972 22973 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22974 new RemoteCallbackList<>(); 22975 22976 public OnPermissionChangeListeners(Looper looper) { 22977 super(looper); 22978 } 22979 22980 @Override 22981 public void handleMessage(Message msg) { 22982 switch (msg.what) { 22983 case MSG_ON_PERMISSIONS_CHANGED: { 22984 final int uid = msg.arg1; 22985 handleOnPermissionsChanged(uid); 22986 } break; 22987 } 22988 } 22989 22990 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22991 mPermissionListeners.register(listener); 22992 22993 } 22994 22995 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22996 mPermissionListeners.unregister(listener); 22997 } 22998 22999 public void onPermissionsChanged(int uid) { 23000 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23001 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23002 } 23003 } 23004 23005 private void handleOnPermissionsChanged(int uid) { 23006 final int count = mPermissionListeners.beginBroadcast(); 23007 try { 23008 for (int i = 0; i < count; i++) { 23009 IOnPermissionsChangeListener callback = mPermissionListeners 23010 .getBroadcastItem(i); 23011 try { 23012 callback.onPermissionsChanged(uid); 23013 } catch (RemoteException e) { 23014 Log.e(TAG, "Permission listener is dead", e); 23015 } 23016 } 23017 } finally { 23018 mPermissionListeners.finishBroadcast(); 23019 } 23020 } 23021 } 23022 23023 private class PackageManagerInternalImpl extends PackageManagerInternal { 23024 @Override 23025 public void setLocationPackagesProvider(PackagesProvider provider) { 23026 synchronized (mPackages) { 23027 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 23028 } 23029 } 23030 23031 @Override 23032 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23033 synchronized (mPackages) { 23034 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 23035 } 23036 } 23037 23038 @Override 23039 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23040 synchronized (mPackages) { 23041 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 23042 } 23043 } 23044 23045 @Override 23046 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23047 synchronized (mPackages) { 23048 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 23049 } 23050 } 23051 23052 @Override 23053 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23054 synchronized (mPackages) { 23055 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 23056 } 23057 } 23058 23059 @Override 23060 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23061 synchronized (mPackages) { 23062 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 23063 } 23064 } 23065 23066 @Override 23067 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23068 synchronized (mPackages) { 23069 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 23070 packageName, userId); 23071 } 23072 } 23073 23074 @Override 23075 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23076 synchronized (mPackages) { 23077 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23078 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 23079 packageName, userId); 23080 } 23081 } 23082 23083 @Override 23084 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23085 synchronized (mPackages) { 23086 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 23087 packageName, userId); 23088 } 23089 } 23090 23091 @Override 23092 public void setKeepUninstalledPackages(final List<String> packageList) { 23093 Preconditions.checkNotNull(packageList); 23094 List<String> removedFromList = null; 23095 synchronized (mPackages) { 23096 if (mKeepUninstalledPackages != null) { 23097 final int packagesCount = mKeepUninstalledPackages.size(); 23098 for (int i = 0; i < packagesCount; i++) { 23099 String oldPackage = mKeepUninstalledPackages.get(i); 23100 if (packageList != null && packageList.contains(oldPackage)) { 23101 continue; 23102 } 23103 if (removedFromList == null) { 23104 removedFromList = new ArrayList<>(); 23105 } 23106 removedFromList.add(oldPackage); 23107 } 23108 } 23109 mKeepUninstalledPackages = new ArrayList<>(packageList); 23110 if (removedFromList != null) { 23111 final int removedCount = removedFromList.size(); 23112 for (int i = 0; i < removedCount; i++) { 23113 deletePackageIfUnusedLPr(removedFromList.get(i)); 23114 } 23115 } 23116 } 23117 } 23118 23119 @Override 23120 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23121 synchronized (mPackages) { 23122 // If we do not support permission review, done. 23123 if (!mPermissionReviewRequired) { 23124 return false; 23125 } 23126 23127 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23128 if (packageSetting == null) { 23129 return false; 23130 } 23131 23132 // Permission review applies only to apps not supporting the new permission model. 23133 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 23134 return false; 23135 } 23136 23137 // Legacy apps have the permission and get user consent on launch. 23138 PermissionsState permissionsState = packageSetting.getPermissionsState(); 23139 return permissionsState.isPermissionReviewRequired(userId); 23140 } 23141 } 23142 23143 @Override 23144 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 23145 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 23146 } 23147 23148 @Override 23149 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23150 int userId) { 23151 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23152 } 23153 23154 @Override 23155 public void setDeviceAndProfileOwnerPackages( 23156 int deviceOwnerUserId, String deviceOwnerPackage, 23157 SparseArray<String> profileOwnerPackages) { 23158 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23159 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23160 } 23161 23162 @Override 23163 public boolean isPackageDataProtected(int userId, String packageName) { 23164 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23165 } 23166 23167 @Override 23168 public boolean isPackageEphemeral(int userId, String packageName) { 23169 synchronized (mPackages) { 23170 final PackageSetting ps = mSettings.mPackages.get(packageName); 23171 return ps != null ? ps.getInstantApp(userId) : false; 23172 } 23173 } 23174 23175 @Override 23176 public boolean wasPackageEverLaunched(String packageName, int userId) { 23177 synchronized (mPackages) { 23178 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23179 } 23180 } 23181 23182 @Override 23183 public void grantRuntimePermission(String packageName, String name, int userId, 23184 boolean overridePolicy) { 23185 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 23186 overridePolicy); 23187 } 23188 23189 @Override 23190 public void revokeRuntimePermission(String packageName, String name, int userId, 23191 boolean overridePolicy) { 23192 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 23193 overridePolicy); 23194 } 23195 23196 @Override 23197 public String getNameForUid(int uid) { 23198 return PackageManagerService.this.getNameForUid(uid); 23199 } 23200 23201 @Override 23202 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23203 Intent origIntent, String resolvedType, String callingPackage, int userId) { 23204 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23205 responseObj, origIntent, resolvedType, callingPackage, userId); 23206 } 23207 23208 @Override 23209 public void grantEphemeralAccess(int userId, Intent intent, 23210 int targetAppId, int ephemeralAppId) { 23211 synchronized (mPackages) { 23212 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23213 targetAppId, ephemeralAppId); 23214 } 23215 } 23216 23217 @Override 23218 public boolean isInstantAppInstallerComponent(ComponentName component) { 23219 synchronized (mPackages) { 23220 return mInstantAppInstallerActivity != null 23221 && mInstantAppInstallerActivity.getComponentName().equals(component); 23222 } 23223 } 23224 23225 @Override 23226 public void pruneInstantApps() { 23227 synchronized (mPackages) { 23228 mInstantAppRegistry.pruneInstantAppsLPw(); 23229 } 23230 } 23231 23232 @Override 23233 public String getSetupWizardPackageName() { 23234 return mSetupWizardPackage; 23235 } 23236 23237 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23238 if (policy != null) { 23239 mExternalSourcesPolicy = policy; 23240 } 23241 } 23242 23243 @Override 23244 public boolean isPackagePersistent(String packageName) { 23245 synchronized (mPackages) { 23246 PackageParser.Package pkg = mPackages.get(packageName); 23247 return pkg != null 23248 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23249 | ApplicationInfo.FLAG_PERSISTENT)) == 23250 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23251 : false; 23252 } 23253 } 23254 23255 @Override 23256 public List<PackageInfo> getOverlayPackages(int userId) { 23257 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23258 synchronized (mPackages) { 23259 for (PackageParser.Package p : mPackages.values()) { 23260 if (p.mOverlayTarget != null) { 23261 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23262 if (pkg != null) { 23263 overlayPackages.add(pkg); 23264 } 23265 } 23266 } 23267 } 23268 return overlayPackages; 23269 } 23270 23271 @Override 23272 public List<String> getTargetPackageNames(int userId) { 23273 List<String> targetPackages = new ArrayList<>(); 23274 synchronized (mPackages) { 23275 for (PackageParser.Package p : mPackages.values()) { 23276 if (p.mOverlayTarget == null) { 23277 targetPackages.add(p.packageName); 23278 } 23279 } 23280 } 23281 return targetPackages; 23282 } 23283 23284 @Override 23285 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23286 @Nullable List<String> overlayPackageNames) { 23287 synchronized (mPackages) { 23288 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23289 Slog.e(TAG, "failed to find package " + targetPackageName); 23290 return false; 23291 } 23292 23293 ArrayList<String> paths = null; 23294 if (overlayPackageNames != null) { 23295 final int N = overlayPackageNames.size(); 23296 paths = new ArrayList<>(N); 23297 for (int i = 0; i < N; i++) { 23298 final String packageName = overlayPackageNames.get(i); 23299 final PackageParser.Package pkg = mPackages.get(packageName); 23300 if (pkg == null) { 23301 Slog.e(TAG, "failed to find package " + packageName); 23302 return false; 23303 } 23304 paths.add(pkg.baseCodePath); 23305 } 23306 } 23307 23308 ArrayMap<String, ArrayList<String>> userSpecificOverlays = 23309 mEnabledOverlayPaths.get(userId); 23310 if (userSpecificOverlays == null) { 23311 userSpecificOverlays = new ArrayMap<>(); 23312 mEnabledOverlayPaths.put(userId, userSpecificOverlays); 23313 } 23314 23315 if (paths != null && paths.size() > 0) { 23316 userSpecificOverlays.put(targetPackageName, paths); 23317 } else { 23318 userSpecificOverlays.remove(targetPackageName); 23319 } 23320 return true; 23321 } 23322 } 23323 23324 @Override 23325 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23326 int flags, int userId) { 23327 return resolveIntentInternal( 23328 intent, resolvedType, flags, userId, true /*includeInstantApps*/); 23329 } 23330 23331 @Override 23332 public ResolveInfo resolveService(Intent intent, String resolvedType, 23333 int flags, int userId, int callingUid) { 23334 return resolveServiceInternal( 23335 intent, resolvedType, flags, userId, callingUid, true /*includeInstantApps*/); 23336 } 23337 23338 23339 @Override 23340 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23341 synchronized (mPackages) { 23342 mIsolatedOwners.put(isolatedUid, ownerUid); 23343 } 23344 } 23345 23346 @Override 23347 public void removeIsolatedUid(int isolatedUid) { 23348 synchronized (mPackages) { 23349 mIsolatedOwners.delete(isolatedUid); 23350 } 23351 } 23352 } 23353 23354 @Override 23355 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23356 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23357 synchronized (mPackages) { 23358 final long identity = Binder.clearCallingIdentity(); 23359 try { 23360 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 23361 packageNames, userId); 23362 } finally { 23363 Binder.restoreCallingIdentity(identity); 23364 } 23365 } 23366 } 23367 23368 @Override 23369 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23370 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23371 synchronized (mPackages) { 23372 final long identity = Binder.clearCallingIdentity(); 23373 try { 23374 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServicesLPr( 23375 packageNames, userId); 23376 } finally { 23377 Binder.restoreCallingIdentity(identity); 23378 } 23379 } 23380 } 23381 23382 private static void enforceSystemOrPhoneCaller(String tag) { 23383 int callingUid = Binder.getCallingUid(); 23384 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23385 throw new SecurityException( 23386 "Cannot call " + tag + " from UID " + callingUid); 23387 } 23388 } 23389 23390 boolean isHistoricalPackageUsageAvailable() { 23391 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23392 } 23393 23394 /** 23395 * Return a <b>copy</b> of the collection of packages known to the package manager. 23396 * @return A copy of the values of mPackages. 23397 */ 23398 Collection<PackageParser.Package> getPackages() { 23399 synchronized (mPackages) { 23400 return new ArrayList<>(mPackages.values()); 23401 } 23402 } 23403 23404 /** 23405 * Logs process start information (including base APK hash) to the security log. 23406 * @hide 23407 */ 23408 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23409 String apkFile, int pid) { 23410 if (!SecurityLog.isLoggingEnabled()) { 23411 return; 23412 } 23413 Bundle data = new Bundle(); 23414 data.putLong("startTimestamp", System.currentTimeMillis()); 23415 data.putString("processName", processName); 23416 data.putInt("uid", uid); 23417 data.putString("seinfo", seinfo); 23418 data.putString("apkFile", apkFile); 23419 data.putInt("pid", pid); 23420 Message msg = mProcessLoggingHandler.obtainMessage( 23421 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23422 msg.setData(data); 23423 mProcessLoggingHandler.sendMessage(msg); 23424 } 23425 23426 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23427 return mCompilerStats.getPackageStats(pkgName); 23428 } 23429 23430 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23431 return getOrCreateCompilerPackageStats(pkg.packageName); 23432 } 23433 23434 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23435 return mCompilerStats.getOrCreatePackageStats(pkgName); 23436 } 23437 23438 public void deleteCompilerPackageStats(String pkgName) { 23439 mCompilerStats.deletePackageStats(pkgName); 23440 } 23441 23442 @Override 23443 public int getInstallReason(String packageName, int userId) { 23444 enforceCrossUserPermission(Binder.getCallingUid(), userId, 23445 true /* requireFullPermission */, false /* checkShell */, 23446 "get install reason"); 23447 synchronized (mPackages) { 23448 final PackageSetting ps = mSettings.mPackages.get(packageName); 23449 if (ps != null) { 23450 return ps.getInstallReason(userId); 23451 } 23452 } 23453 return PackageManager.INSTALL_REASON_UNKNOWN; 23454 } 23455 23456 @Override 23457 public boolean canRequestPackageInstalls(String packageName, int userId) { 23458 int callingUid = Binder.getCallingUid(); 23459 int uid = getPackageUid(packageName, 0, userId); 23460 if (callingUid != uid && callingUid != Process.ROOT_UID 23461 && callingUid != Process.SYSTEM_UID) { 23462 throw new SecurityException( 23463 "Caller uid " + callingUid + " does not own package " + packageName); 23464 } 23465 ApplicationInfo info = getApplicationInfo(packageName, 0, userId); 23466 if (info == null) { 23467 return false; 23468 } 23469 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23470 throw new UnsupportedOperationException( 23471 "Operation only supported on apps targeting Android O or higher"); 23472 } 23473 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23474 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23475 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23476 throw new SecurityException("Need to declare " + appOpPermission + " to call this api"); 23477 } 23478 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23479 return false; 23480 } 23481 if (mExternalSourcesPolicy != null) { 23482 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23483 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23484 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23485 } 23486 } 23487 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23488 } 23489 23490 @Override 23491 public ComponentName getInstantAppResolverSettingsComponent() { 23492 return mInstantAppResolverSettingsComponent; 23493 } 23494} 23495