PackageManagerService.java revision 811825a582812e51412fee5d712259502a7f023b
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.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 40import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 41import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 46import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 47import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 48import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 50import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 51import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 53import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 54import static android.content.pm.PackageManager.INSTALL_INTERNAL; 55import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 56import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 61import static android.content.pm.PackageManager.MATCH_ALL; 62import static android.content.pm.PackageManager.MATCH_ANY_USER; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 69import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 70import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 71import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 72import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 73import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 74import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 75import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 76import static android.content.pm.PackageManager.PERMISSION_DENIED; 77import static android.content.pm.PackageManager.PERMISSION_GRANTED; 78import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 79import static android.content.pm.PackageParser.isApkFile; 80import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 81import static android.system.OsConstants.O_CREAT; 82import static android.system.OsConstants.O_RDWR; 83 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 86import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 87import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 88import static com.android.internal.util.ArrayUtils.appendInt; 89import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 90import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 93import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 94import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.annotation.UserIdInt; 106import android.app.ActivityManager; 107import android.app.AppOpsManager; 108import android.app.IActivityManager; 109import android.app.ResourcesManager; 110import android.app.admin.IDevicePolicyManager; 111import android.app.admin.SecurityLog; 112import android.app.backup.IBackupManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.ContentResolver; 116import android.content.Context; 117import android.content.IIntentReceiver; 118import android.content.Intent; 119import android.content.IntentFilter; 120import android.content.IntentSender; 121import android.content.IntentSender.SendIntentException; 122import android.content.ServiceConnection; 123import android.content.pm.ActivityInfo; 124import android.content.pm.ApplicationInfo; 125import android.content.pm.AppsQueryHelper; 126import android.content.pm.ComponentInfo; 127import android.content.pm.EphemeralApplicationInfo; 128import android.content.pm.EphemeralRequest; 129import android.content.pm.EphemeralResolveInfo; 130import android.content.pm.EphemeralResponse; 131import android.content.pm.FeatureInfo; 132import android.content.pm.IOnPermissionsChangeListener; 133import android.content.pm.IPackageDataObserver; 134import android.content.pm.IPackageDeleteObserver; 135import android.content.pm.IPackageDeleteObserver2; 136import android.content.pm.IPackageInstallObserver2; 137import android.content.pm.IPackageInstaller; 138import android.content.pm.IPackageManager; 139import android.content.pm.IPackageMoveObserver; 140import android.content.pm.IPackageStatsObserver; 141import android.content.pm.InstrumentationInfo; 142import android.content.pm.IntentFilterVerificationInfo; 143import android.content.pm.KeySet; 144import android.content.pm.PackageCleanItem; 145import android.content.pm.PackageInfo; 146import android.content.pm.PackageInfoLite; 147import android.content.pm.PackageInstaller; 148import android.content.pm.PackageManager; 149import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 150import android.content.pm.PackageManagerInternal; 151import android.content.pm.PackageParser; 152import android.content.pm.PackageParser.ActivityIntentInfo; 153import android.content.pm.PackageParser.PackageLite; 154import android.content.pm.PackageParser.PackageParserException; 155import android.content.pm.PackageStats; 156import android.content.pm.PackageUserState; 157import android.content.pm.ParceledListSlice; 158import android.content.pm.PermissionGroupInfo; 159import android.content.pm.PermissionInfo; 160import android.content.pm.ProviderInfo; 161import android.content.pm.ResolveInfo; 162import android.content.pm.ServiceInfo; 163import android.content.pm.Signature; 164import android.content.pm.UserInfo; 165import android.content.pm.VerifierDeviceIdentity; 166import android.content.pm.VerifierInfo; 167import android.content.res.Resources; 168import android.graphics.Bitmap; 169import android.hardware.display.DisplayManager; 170import android.net.Uri; 171import android.os.Binder; 172import android.os.Build; 173import android.os.Bundle; 174import android.os.Debug; 175import android.os.Environment; 176import android.os.Environment.UserEnvironment; 177import android.os.FileUtils; 178import android.os.Handler; 179import android.os.IBinder; 180import android.os.Looper; 181import android.os.Message; 182import android.os.Parcel; 183import android.os.ParcelFileDescriptor; 184import android.os.PatternMatcher; 185import android.os.Process; 186import android.os.RemoteCallbackList; 187import android.os.RemoteException; 188import android.os.ResultReceiver; 189import android.os.SELinux; 190import android.os.ServiceManager; 191import android.os.ShellCallback; 192import android.os.SystemClock; 193import android.os.SystemProperties; 194import android.os.Trace; 195import android.os.UserHandle; 196import android.os.UserManager; 197import android.os.UserManagerInternal; 198import android.os.storage.IStorageManager; 199import android.os.storage.StorageManagerInternal; 200import android.os.storage.StorageEventListener; 201import android.os.storage.StorageManager; 202import android.os.storage.VolumeInfo; 203import android.os.storage.VolumeRecord; 204import android.provider.Settings.Global; 205import android.provider.Settings.Secure; 206import android.security.KeyStore; 207import android.security.SystemKeyStore; 208import android.system.ErrnoException; 209import android.system.Os; 210import android.text.TextUtils; 211import android.text.format.DateUtils; 212import android.util.ArrayMap; 213import android.util.ArraySet; 214import android.util.Base64; 215import android.util.DisplayMetrics; 216import android.util.EventLog; 217import android.util.ExceptionUtils; 218import android.util.Log; 219import android.util.LogPrinter; 220import android.util.MathUtils; 221import android.util.Pair; 222import android.util.PrintStreamPrinter; 223import android.util.Slog; 224import android.util.SparseArray; 225import android.util.SparseBooleanArray; 226import android.util.SparseIntArray; 227import android.util.Xml; 228import android.util.jar.StrictJarFile; 229import android.view.Display; 230 231import com.android.internal.R; 232import com.android.internal.annotations.GuardedBy; 233import com.android.internal.app.IMediaContainerService; 234import com.android.internal.app.ResolverActivity; 235import com.android.internal.content.NativeLibraryHelper; 236import com.android.internal.content.PackageHelper; 237import com.android.internal.logging.MetricsLogger; 238import com.android.internal.logging.nano.MetricsProto.MetricsEvent; 239import com.android.internal.os.IParcelFileDescriptorFactory; 240import com.android.internal.os.InstallerConnection.InstallerException; 241import com.android.internal.os.RoSystemProperties; 242import com.android.internal.os.SomeArgs; 243import com.android.internal.os.Zygote; 244import com.android.internal.telephony.CarrierAppUtils; 245import com.android.internal.util.ArrayUtils; 246import com.android.internal.util.FastPrintWriter; 247import com.android.internal.util.FastXmlSerializer; 248import com.android.internal.util.IndentingPrintWriter; 249import com.android.internal.util.Preconditions; 250import com.android.internal.util.XmlUtils; 251import com.android.server.AttributeCache; 252import com.android.server.EventLogTags; 253import com.android.server.FgThread; 254import com.android.server.IntentResolver; 255import com.android.server.LocalServices; 256import com.android.server.ServiceThread; 257import com.android.server.SystemConfig; 258import com.android.server.Watchdog; 259import com.android.server.net.NetworkPolicyManagerInternal; 260import com.android.server.pm.PermissionsState.PermissionState; 261import com.android.server.pm.Settings.DatabaseVersion; 262import com.android.server.pm.Settings.VersionInfo; 263import com.android.server.storage.DeviceStorageMonitorInternal; 264 265import dalvik.system.CloseGuard; 266import dalvik.system.DexFile; 267import dalvik.system.VMRuntime; 268 269import libcore.io.IoUtils; 270import libcore.util.EmptyArray; 271 272import org.xmlpull.v1.XmlPullParser; 273import org.xmlpull.v1.XmlPullParserException; 274import org.xmlpull.v1.XmlSerializer; 275 276import java.io.BufferedOutputStream; 277import java.io.BufferedReader; 278import java.io.ByteArrayInputStream; 279import java.io.ByteArrayOutputStream; 280import java.io.File; 281import java.io.FileDescriptor; 282import java.io.FileInputStream; 283import java.io.FileNotFoundException; 284import java.io.FileOutputStream; 285import java.io.FileReader; 286import java.io.FilenameFilter; 287import java.io.IOException; 288import java.io.PrintWriter; 289import java.nio.charset.StandardCharsets; 290import java.security.DigestInputStream; 291import java.security.MessageDigest; 292import java.security.NoSuchAlgorithmException; 293import java.security.PublicKey; 294import java.security.SecureRandom; 295import java.security.cert.Certificate; 296import java.security.cert.CertificateEncodingException; 297import java.security.cert.CertificateException; 298import java.text.SimpleDateFormat; 299import java.util.ArrayList; 300import java.util.Arrays; 301import java.util.Collection; 302import java.util.Collections; 303import java.util.Comparator; 304import java.util.Date; 305import java.util.HashSet; 306import java.util.Iterator; 307import java.util.List; 308import java.util.Map; 309import java.util.Objects; 310import java.util.Set; 311import java.util.concurrent.CountDownLatch; 312import java.util.concurrent.TimeUnit; 313import java.util.concurrent.atomic.AtomicBoolean; 314import java.util.concurrent.atomic.AtomicInteger; 315 316/** 317 * Keep track of all those APKs everywhere. 318 * <p> 319 * Internally there are two important locks: 320 * <ul> 321 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 322 * and other related state. It is a fine-grained lock that should only be held 323 * momentarily, as it's one of the most contended locks in the system. 324 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 325 * operations typically involve heavy lifting of application data on disk. Since 326 * {@code installd} is single-threaded, and it's operations can often be slow, 327 * this lock should never be acquired while already holding {@link #mPackages}. 328 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 329 * holding {@link #mInstallLock}. 330 * </ul> 331 * Many internal methods rely on the caller to hold the appropriate locks, and 332 * this contract is expressed through method name suffixes: 333 * <ul> 334 * <li>fooLI(): the caller must hold {@link #mInstallLock} 335 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 336 * being modified must be frozen 337 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 338 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 339 * </ul> 340 * <p> 341 * Because this class is very central to the platform's security; please run all 342 * CTS and unit tests whenever making modifications: 343 * 344 * <pre> 345 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 346 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 347 * </pre> 348 */ 349public class PackageManagerService extends IPackageManager.Stub { 350 static final String TAG = "PackageManager"; 351 static final boolean DEBUG_SETTINGS = false; 352 static final boolean DEBUG_PREFERRED = false; 353 static final boolean DEBUG_UPGRADE = false; 354 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 355 private static final boolean DEBUG_BACKUP = false; 356 private static final boolean DEBUG_INSTALL = false; 357 private static final boolean DEBUG_REMOVE = false; 358 private static final boolean DEBUG_BROADCASTS = false; 359 private static final boolean DEBUG_SHOW_INFO = false; 360 private static final boolean DEBUG_PACKAGE_INFO = false; 361 private static final boolean DEBUG_INTENT_MATCHING = false; 362 private static final boolean DEBUG_PACKAGE_SCANNING = false; 363 private static final boolean DEBUG_VERIFY = false; 364 private static final boolean DEBUG_FILTERS = false; 365 366 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 367 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 368 // user, but by default initialize to this. 369 static final boolean DEBUG_DEXOPT = false; 370 371 private static final boolean DEBUG_ABI_SELECTION = false; 372 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 373 private static final boolean DEBUG_TRIAGED_MISSING = false; 374 private static final boolean DEBUG_APP_DATA = false; 375 376 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 377 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 378 379 private static final boolean DISABLE_EPHEMERAL_APPS = false; 380 private static final boolean HIDE_EPHEMERAL_APIS = true; 381 382 private static final int RADIO_UID = Process.PHONE_UID; 383 private static final int LOG_UID = Process.LOG_UID; 384 private static final int NFC_UID = Process.NFC_UID; 385 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 386 private static final int SHELL_UID = Process.SHELL_UID; 387 388 // Cap the size of permission trees that 3rd party apps can define 389 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 390 391 // Suffix used during package installation when copying/moving 392 // package apks to install directory. 393 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 394 395 static final int SCAN_NO_DEX = 1<<1; 396 static final int SCAN_FORCE_DEX = 1<<2; 397 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 398 static final int SCAN_NEW_INSTALL = 1<<4; 399 static final int SCAN_UPDATE_TIME = 1<<5; 400 static final int SCAN_BOOTING = 1<<6; 401 static final int SCAN_TRUSTED_OVERLAY = 1<<7; 402 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<8; 403 static final int SCAN_REPLACING = 1<<9; 404 static final int SCAN_REQUIRE_KNOWN = 1<<10; 405 static final int SCAN_MOVE = 1<<11; 406 static final int SCAN_INITIAL = 1<<12; 407 static final int SCAN_CHECK_ONLY = 1<<13; 408 static final int SCAN_DONT_KILL_APP = 1<<14; 409 static final int SCAN_IGNORE_FROZEN = 1<<15; 410 static final int REMOVE_CHATTY = 1<<16; 411 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<17; 412 413 private static final int[] EMPTY_INT_ARRAY = new int[0]; 414 415 /** 416 * Timeout (in milliseconds) after which the watchdog should declare that 417 * our handler thread is wedged. The usual default for such things is one 418 * minute but we sometimes do very lengthy I/O operations on this thread, 419 * such as installing multi-gigabyte applications, so ours needs to be longer. 420 */ 421 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 422 423 /** 424 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 425 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 426 * settings entry if available, otherwise we use the hardcoded default. If it's been 427 * more than this long since the last fstrim, we force one during the boot sequence. 428 * 429 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 430 * one gets run at the next available charging+idle time. This final mandatory 431 * no-fstrim check kicks in only of the other scheduling criteria is never met. 432 */ 433 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 434 435 /** 436 * Whether verification is enabled by default. 437 */ 438 private static final boolean DEFAULT_VERIFY_ENABLE = true; 439 440 /** 441 * The default maximum time to wait for the verification agent to return in 442 * milliseconds. 443 */ 444 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 445 446 /** 447 * The default response for package verification timeout. 448 * 449 * This can be either PackageManager.VERIFICATION_ALLOW or 450 * PackageManager.VERIFICATION_REJECT. 451 */ 452 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 453 454 static final String PLATFORM_PACKAGE_NAME = "android"; 455 456 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 457 458 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 459 DEFAULT_CONTAINER_PACKAGE, 460 "com.android.defcontainer.DefaultContainerService"); 461 462 private static final String KILL_APP_REASON_GIDS_CHANGED = 463 "permission grant or revoke changed gids"; 464 465 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 466 "permissions revoked"; 467 468 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 469 470 private static final String PACKAGE_SCHEME = "package"; 471 472 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 473 /** 474 * If VENDOR_OVERLAY_THEME_PROPERTY is set, search for runtime resource overlay APKs also in 475 * VENDOR_OVERLAY_DIR/<value of VENDOR_OVERLAY_THEME_PROPERTY> in addition to 476 * VENDOR_OVERLAY_DIR. 477 */ 478 private static final String VENDOR_OVERLAY_THEME_PROPERTY = "ro.boot.vendor.overlay.theme"; 479 /** 480 * Same as VENDOR_OVERLAY_THEME_PROPERTY, except persistent. If set will override whatever 481 * is in VENDOR_OVERLAY_THEME_PROPERTY. 482 */ 483 private static final String VENDOR_OVERLAY_THEME_PERSIST_PROPERTY 484 = "persist.vendor.overlay.theme"; 485 486 /** Permission grant: not grant the permission. */ 487 private static final int GRANT_DENIED = 1; 488 489 /** Permission grant: grant the permission as an install permission. */ 490 private static final int GRANT_INSTALL = 2; 491 492 /** Permission grant: grant the permission as a runtime one. */ 493 private static final int GRANT_RUNTIME = 3; 494 495 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 496 private static final int GRANT_UPGRADE = 4; 497 498 /** Canonical intent used to identify what counts as a "web browser" app */ 499 private static final Intent sBrowserIntent; 500 static { 501 sBrowserIntent = new Intent(); 502 sBrowserIntent.setAction(Intent.ACTION_VIEW); 503 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 504 sBrowserIntent.setData(Uri.parse("http:")); 505 } 506 507 /** 508 * The set of all protected actions [i.e. those actions for which a high priority 509 * intent filter is disallowed]. 510 */ 511 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 512 static { 513 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 514 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 515 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 516 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 517 } 518 519 // Compilation reasons. 520 public static final int REASON_FIRST_BOOT = 0; 521 public static final int REASON_BOOT = 1; 522 public static final int REASON_INSTALL = 2; 523 public static final int REASON_BACKGROUND_DEXOPT = 3; 524 public static final int REASON_AB_OTA = 4; 525 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 526 public static final int REASON_SHARED_APK = 6; 527 public static final int REASON_FORCED_DEXOPT = 7; 528 public static final int REASON_CORE_APP = 8; 529 530 public static final int REASON_LAST = REASON_CORE_APP; 531 532 /** Special library name that skips shared libraries check during compilation. */ 533 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 534 535 /** All dangerous permission names in the same order as the events in MetricsEvent */ 536 private static final List<String> ALL_DANGEROUS_PERMISSIONS = Arrays.asList( 537 Manifest.permission.READ_CALENDAR, 538 Manifest.permission.WRITE_CALENDAR, 539 Manifest.permission.CAMERA, 540 Manifest.permission.READ_CONTACTS, 541 Manifest.permission.WRITE_CONTACTS, 542 Manifest.permission.GET_ACCOUNTS, 543 Manifest.permission.ACCESS_FINE_LOCATION, 544 Manifest.permission.ACCESS_COARSE_LOCATION, 545 Manifest.permission.RECORD_AUDIO, 546 Manifest.permission.READ_PHONE_STATE, 547 Manifest.permission.CALL_PHONE, 548 Manifest.permission.READ_CALL_LOG, 549 Manifest.permission.WRITE_CALL_LOG, 550 Manifest.permission.ADD_VOICEMAIL, 551 Manifest.permission.USE_SIP, 552 Manifest.permission.PROCESS_OUTGOING_CALLS, 553 Manifest.permission.READ_CELL_BROADCASTS, 554 Manifest.permission.BODY_SENSORS, 555 Manifest.permission.SEND_SMS, 556 Manifest.permission.RECEIVE_SMS, 557 Manifest.permission.READ_SMS, 558 Manifest.permission.RECEIVE_WAP_PUSH, 559 Manifest.permission.RECEIVE_MMS, 560 Manifest.permission.READ_EXTERNAL_STORAGE, 561 Manifest.permission.WRITE_EXTERNAL_STORAGE, 562 Manifest.permission.READ_PHONE_NUMBER); 563 564 final ServiceThread mHandlerThread; 565 566 final PackageHandler mHandler; 567 568 private final ProcessLoggingHandler mProcessLoggingHandler; 569 570 /** 571 * Messages for {@link #mHandler} that need to wait for system ready before 572 * being dispatched. 573 */ 574 private ArrayList<Message> mPostSystemReadyMessages; 575 576 final int mSdkVersion = Build.VERSION.SDK_INT; 577 578 final Context mContext; 579 final boolean mFactoryTest; 580 final boolean mOnlyCore; 581 final DisplayMetrics mMetrics; 582 final int mDefParseFlags; 583 final String[] mSeparateProcesses; 584 final boolean mIsUpgrade; 585 final boolean mIsPreNUpgrade; 586 final boolean mIsPreNMR1Upgrade; 587 588 @GuardedBy("mPackages") 589 private boolean mDexOptDialogShown; 590 591 /** The location for ASEC container files on internal storage. */ 592 final String mAsecInternalPath; 593 594 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 595 // LOCK HELD. Can be called with mInstallLock held. 596 @GuardedBy("mInstallLock") 597 final Installer mInstaller; 598 599 /** Directory where installed third-party apps stored */ 600 final File mAppInstallDir; 601 final File mEphemeralInstallDir; 602 603 /** 604 * Directory to which applications installed internally have their 605 * 32 bit native libraries copied. 606 */ 607 private File mAppLib32InstallDir; 608 609 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 610 // apps. 611 final File mDrmAppPrivateInstallDir; 612 613 // ---------------------------------------------------------------- 614 615 // Lock for state used when installing and doing other long running 616 // operations. Methods that must be called with this lock held have 617 // the suffix "LI". 618 final Object mInstallLock = new Object(); 619 620 // ---------------------------------------------------------------- 621 622 // Keys are String (package name), values are Package. This also serves 623 // as the lock for the global state. Methods that must be called with 624 // this lock held have the prefix "LP". 625 @GuardedBy("mPackages") 626 final ArrayMap<String, PackageParser.Package> mPackages = 627 new ArrayMap<String, PackageParser.Package>(); 628 629 final ArrayMap<String, Set<String>> mKnownCodebase = 630 new ArrayMap<String, Set<String>>(); 631 632 // Tracks available target package names -> overlay package paths. 633 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 634 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 635 636 /** 637 * Tracks new system packages [received in an OTA] that we expect to 638 * find updated user-installed versions. Keys are package name, values 639 * are package location. 640 */ 641 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 642 /** 643 * Tracks high priority intent filters for protected actions. During boot, certain 644 * filter actions are protected and should never be allowed to have a high priority 645 * intent filter for them. However, there is one, and only one exception -- the 646 * setup wizard. It must be able to define a high priority intent filter for these 647 * actions to ensure there are no escapes from the wizard. We need to delay processing 648 * of these during boot as we need to look at all of the system packages in order 649 * to know which component is the setup wizard. 650 */ 651 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 652 /** 653 * Whether or not processing protected filters should be deferred. 654 */ 655 private boolean mDeferProtectedFilters = true; 656 657 /** 658 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 659 */ 660 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 661 /** 662 * Whether or not system app permissions should be promoted from install to runtime. 663 */ 664 boolean mPromoteSystemApps; 665 666 @GuardedBy("mPackages") 667 final Settings mSettings; 668 669 /** 670 * Set of package names that are currently "frozen", which means active 671 * surgery is being done on the code/data for that package. The platform 672 * will refuse to launch frozen packages to avoid race conditions. 673 * 674 * @see PackageFreezer 675 */ 676 @GuardedBy("mPackages") 677 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 678 679 final ProtectedPackages mProtectedPackages; 680 681 boolean mFirstBoot; 682 683 // System configuration read by SystemConfig. 684 final int[] mGlobalGids; 685 final SparseArray<ArraySet<String>> mSystemPermissions; 686 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 687 688 // If mac_permissions.xml was found for seinfo labeling. 689 boolean mFoundPolicyFile; 690 691 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 692 693 public static final class SharedLibraryEntry { 694 public final String path; 695 public final String apk; 696 697 SharedLibraryEntry(String _path, String _apk) { 698 path = _path; 699 apk = _apk; 700 } 701 } 702 703 // Currently known shared libraries. 704 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 705 new ArrayMap<String, SharedLibraryEntry>(); 706 707 // All available activities, for your resolving pleasure. 708 final ActivityIntentResolver mActivities = 709 new ActivityIntentResolver(); 710 711 // All available receivers, for your resolving pleasure. 712 final ActivityIntentResolver mReceivers = 713 new ActivityIntentResolver(); 714 715 // All available services, for your resolving pleasure. 716 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 717 718 // All available providers, for your resolving pleasure. 719 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 720 721 // Mapping from provider base names (first directory in content URI codePath) 722 // to the provider information. 723 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 724 new ArrayMap<String, PackageParser.Provider>(); 725 726 // Mapping from instrumentation class names to info about them. 727 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 728 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 729 730 // Mapping from permission names to info about them. 731 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 732 new ArrayMap<String, PackageParser.PermissionGroup>(); 733 734 // Packages whose data we have transfered into another package, thus 735 // should no longer exist. 736 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 737 738 // Broadcast actions that are only available to the system. 739 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 740 741 /** List of packages waiting for verification. */ 742 final SparseArray<PackageVerificationState> mPendingVerification 743 = new SparseArray<PackageVerificationState>(); 744 745 /** Set of packages associated with each app op permission. */ 746 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 747 748 final PackageInstallerService mInstallerService; 749 750 private final PackageDexOptimizer mPackageDexOptimizer; 751 752 private AtomicInteger mNextMoveId = new AtomicInteger(); 753 private final MoveCallbacks mMoveCallbacks; 754 755 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 756 757 // Cache of users who need badging. 758 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 759 760 /** Token for keys in mPendingVerification. */ 761 private int mPendingVerificationToken = 0; 762 763 volatile boolean mSystemReady; 764 volatile boolean mSafeMode; 765 volatile boolean mHasSystemUidErrors; 766 767 ApplicationInfo mAndroidApplication; 768 final ActivityInfo mResolveActivity = new ActivityInfo(); 769 final ResolveInfo mResolveInfo = new ResolveInfo(); 770 ComponentName mResolveComponentName; 771 PackageParser.Package mPlatformPackage; 772 ComponentName mCustomResolverComponentName; 773 774 boolean mResolverReplaced = false; 775 776 private final @Nullable ComponentName mIntentFilterVerifierComponent; 777 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 778 779 private int mIntentFilterVerificationToken = 0; 780 781 /** The service connection to the ephemeral resolver */ 782 final EphemeralResolverConnection mEphemeralResolverConnection; 783 784 /** Component used to install ephemeral applications */ 785 ComponentName mEphemeralInstallerComponent; 786 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 787 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 788 789 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 790 = new SparseArray<IntentFilterVerificationState>(); 791 792 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 793 794 // List of packages names to keep cached, even if they are uninstalled for all users 795 private List<String> mKeepUninstalledPackages; 796 797 private UserManagerInternal mUserManagerInternal; 798 799 private static class IFVerificationParams { 800 PackageParser.Package pkg; 801 boolean replacing; 802 int userId; 803 int verifierUid; 804 805 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 806 int _userId, int _verifierUid) { 807 pkg = _pkg; 808 replacing = _replacing; 809 userId = _userId; 810 replacing = _replacing; 811 verifierUid = _verifierUid; 812 } 813 } 814 815 private interface IntentFilterVerifier<T extends IntentFilter> { 816 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 817 T filter, String packageName); 818 void startVerifications(int userId); 819 void receiveVerificationResponse(int verificationId); 820 } 821 822 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 823 private Context mContext; 824 private ComponentName mIntentFilterVerifierComponent; 825 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 826 827 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 828 mContext = context; 829 mIntentFilterVerifierComponent = verifierComponent; 830 } 831 832 private String getDefaultScheme() { 833 return IntentFilter.SCHEME_HTTPS; 834 } 835 836 @Override 837 public void startVerifications(int userId) { 838 // Launch verifications requests 839 int count = mCurrentIntentFilterVerifications.size(); 840 for (int n=0; n<count; n++) { 841 int verificationId = mCurrentIntentFilterVerifications.get(n); 842 final IntentFilterVerificationState ivs = 843 mIntentFilterVerificationStates.get(verificationId); 844 845 String packageName = ivs.getPackageName(); 846 847 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 848 final int filterCount = filters.size(); 849 ArraySet<String> domainsSet = new ArraySet<>(); 850 for (int m=0; m<filterCount; m++) { 851 PackageParser.ActivityIntentInfo filter = filters.get(m); 852 domainsSet.addAll(filter.getHostsList()); 853 } 854 synchronized (mPackages) { 855 if (mSettings.createIntentFilterVerificationIfNeededLPw( 856 packageName, domainsSet) != null) { 857 scheduleWriteSettingsLocked(); 858 } 859 } 860 sendVerificationRequest(userId, verificationId, ivs); 861 } 862 mCurrentIntentFilterVerifications.clear(); 863 } 864 865 private void sendVerificationRequest(int userId, int verificationId, 866 IntentFilterVerificationState ivs) { 867 868 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 869 verificationIntent.putExtra( 870 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 871 verificationId); 872 verificationIntent.putExtra( 873 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 874 getDefaultScheme()); 875 verificationIntent.putExtra( 876 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 877 ivs.getHostsString()); 878 verificationIntent.putExtra( 879 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 880 ivs.getPackageName()); 881 verificationIntent.setComponent(mIntentFilterVerifierComponent); 882 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 883 884 UserHandle user = new UserHandle(userId); 885 mContext.sendBroadcastAsUser(verificationIntent, user); 886 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 887 "Sending IntentFilter verification broadcast"); 888 } 889 890 public void receiveVerificationResponse(int verificationId) { 891 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 892 893 final boolean verified = ivs.isVerified(); 894 895 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 896 final int count = filters.size(); 897 if (DEBUG_DOMAIN_VERIFICATION) { 898 Slog.i(TAG, "Received verification response " + verificationId 899 + " for " + count + " filters, verified=" + verified); 900 } 901 for (int n=0; n<count; n++) { 902 PackageParser.ActivityIntentInfo filter = filters.get(n); 903 filter.setVerified(verified); 904 905 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 906 + " verified with result:" + verified + " and hosts:" 907 + ivs.getHostsString()); 908 } 909 910 mIntentFilterVerificationStates.remove(verificationId); 911 912 final String packageName = ivs.getPackageName(); 913 IntentFilterVerificationInfo ivi = null; 914 915 synchronized (mPackages) { 916 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 917 } 918 if (ivi == null) { 919 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 920 + verificationId + " packageName:" + packageName); 921 return; 922 } 923 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 924 "Updating IntentFilterVerificationInfo for package " + packageName 925 +" verificationId:" + verificationId); 926 927 synchronized (mPackages) { 928 if (verified) { 929 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 930 } else { 931 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 932 } 933 scheduleWriteSettingsLocked(); 934 935 final int userId = ivs.getUserId(); 936 if (userId != UserHandle.USER_ALL) { 937 final int userStatus = 938 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 939 940 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 941 boolean needUpdate = false; 942 943 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 944 // already been set by the User thru the Disambiguation dialog 945 switch (userStatus) { 946 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 947 if (verified) { 948 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 949 } else { 950 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 951 } 952 needUpdate = true; 953 break; 954 955 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 956 if (verified) { 957 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 958 needUpdate = true; 959 } 960 break; 961 962 default: 963 // Nothing to do 964 } 965 966 if (needUpdate) { 967 mSettings.updateIntentFilterVerificationStatusLPw( 968 packageName, updatedStatus, userId); 969 scheduleWritePackageRestrictionsLocked(userId); 970 } 971 } 972 } 973 } 974 975 @Override 976 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 977 ActivityIntentInfo filter, String packageName) { 978 if (!hasValidDomains(filter)) { 979 return false; 980 } 981 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 982 if (ivs == null) { 983 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 984 packageName); 985 } 986 if (DEBUG_DOMAIN_VERIFICATION) { 987 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 988 } 989 ivs.addFilter(filter); 990 return true; 991 } 992 993 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 994 int userId, int verificationId, String packageName) { 995 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 996 verifierUid, userId, packageName); 997 ivs.setPendingState(); 998 synchronized (mPackages) { 999 mIntentFilterVerificationStates.append(verificationId, ivs); 1000 mCurrentIntentFilterVerifications.add(verificationId); 1001 } 1002 return ivs; 1003 } 1004 } 1005 1006 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1007 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1008 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1009 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1010 } 1011 1012 // Set of pending broadcasts for aggregating enable/disable of components. 1013 static class PendingPackageBroadcasts { 1014 // for each user id, a map of <package name -> components within that package> 1015 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1016 1017 public PendingPackageBroadcasts() { 1018 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1019 } 1020 1021 public ArrayList<String> get(int userId, String packageName) { 1022 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1023 return packages.get(packageName); 1024 } 1025 1026 public void put(int userId, String packageName, ArrayList<String> components) { 1027 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1028 packages.put(packageName, components); 1029 } 1030 1031 public void remove(int userId, String packageName) { 1032 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1033 if (packages != null) { 1034 packages.remove(packageName); 1035 } 1036 } 1037 1038 public void remove(int userId) { 1039 mUidMap.remove(userId); 1040 } 1041 1042 public int userIdCount() { 1043 return mUidMap.size(); 1044 } 1045 1046 public int userIdAt(int n) { 1047 return mUidMap.keyAt(n); 1048 } 1049 1050 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1051 return mUidMap.get(userId); 1052 } 1053 1054 public int size() { 1055 // total number of pending broadcast entries across all userIds 1056 int num = 0; 1057 for (int i = 0; i< mUidMap.size(); i++) { 1058 num += mUidMap.valueAt(i).size(); 1059 } 1060 return num; 1061 } 1062 1063 public void clear() { 1064 mUidMap.clear(); 1065 } 1066 1067 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1068 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1069 if (map == null) { 1070 map = new ArrayMap<String, ArrayList<String>>(); 1071 mUidMap.put(userId, map); 1072 } 1073 return map; 1074 } 1075 } 1076 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1077 1078 // Service Connection to remote media container service to copy 1079 // package uri's from external media onto secure containers 1080 // or internal storage. 1081 private IMediaContainerService mContainerService = null; 1082 1083 static final int SEND_PENDING_BROADCAST = 1; 1084 static final int MCS_BOUND = 3; 1085 static final int END_COPY = 4; 1086 static final int INIT_COPY = 5; 1087 static final int MCS_UNBIND = 6; 1088 static final int START_CLEANING_PACKAGE = 7; 1089 static final int FIND_INSTALL_LOC = 8; 1090 static final int POST_INSTALL = 9; 1091 static final int MCS_RECONNECT = 10; 1092 static final int MCS_GIVE_UP = 11; 1093 static final int UPDATED_MEDIA_STATUS = 12; 1094 static final int WRITE_SETTINGS = 13; 1095 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1096 static final int PACKAGE_VERIFIED = 15; 1097 static final int CHECK_PENDING_VERIFICATION = 16; 1098 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1099 static final int INTENT_FILTER_VERIFIED = 18; 1100 static final int WRITE_PACKAGE_LIST = 19; 1101 static final int EPHEMERAL_RESOLUTION_PHASE_TWO = 20; 1102 1103 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1104 1105 // Delay time in millisecs 1106 static final int BROADCAST_DELAY = 10 * 1000; 1107 1108 static UserManagerService sUserManager; 1109 1110 // Stores a list of users whose package restrictions file needs to be updated 1111 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1112 1113 final private DefaultContainerConnection mDefContainerConn = 1114 new DefaultContainerConnection(); 1115 class DefaultContainerConnection implements ServiceConnection { 1116 public void onServiceConnected(ComponentName name, IBinder service) { 1117 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1118 final IMediaContainerService imcs = IMediaContainerService.Stub 1119 .asInterface(Binder.allowBlocking(service)); 1120 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1121 } 1122 1123 public void onServiceDisconnected(ComponentName name) { 1124 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1125 } 1126 } 1127 1128 // Recordkeeping of restore-after-install operations that are currently in flight 1129 // between the Package Manager and the Backup Manager 1130 static class PostInstallData { 1131 public InstallArgs args; 1132 public PackageInstalledInfo res; 1133 1134 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1135 args = _a; 1136 res = _r; 1137 } 1138 } 1139 1140 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1141 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1142 1143 // XML tags for backup/restore of various bits of state 1144 private static final String TAG_PREFERRED_BACKUP = "pa"; 1145 private static final String TAG_DEFAULT_APPS = "da"; 1146 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1147 1148 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1149 private static final String TAG_ALL_GRANTS = "rt-grants"; 1150 private static final String TAG_GRANT = "grant"; 1151 private static final String ATTR_PACKAGE_NAME = "pkg"; 1152 1153 private static final String TAG_PERMISSION = "perm"; 1154 private static final String ATTR_PERMISSION_NAME = "name"; 1155 private static final String ATTR_IS_GRANTED = "g"; 1156 private static final String ATTR_USER_SET = "set"; 1157 private static final String ATTR_USER_FIXED = "fixed"; 1158 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1159 1160 // System/policy permission grants are not backed up 1161 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1162 FLAG_PERMISSION_POLICY_FIXED 1163 | FLAG_PERMISSION_SYSTEM_FIXED 1164 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1165 1166 // And we back up these user-adjusted states 1167 private static final int USER_RUNTIME_GRANT_MASK = 1168 FLAG_PERMISSION_USER_SET 1169 | FLAG_PERMISSION_USER_FIXED 1170 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1171 1172 final @Nullable String mRequiredVerifierPackage; 1173 final @NonNull String mRequiredInstallerPackage; 1174 final @NonNull String mRequiredUninstallerPackage; 1175 final @Nullable String mSetupWizardPackage; 1176 final @Nullable String mStorageManagerPackage; 1177 final @NonNull String mServicesSystemSharedLibraryPackageName; 1178 final @NonNull String mSharedSystemSharedLibraryPackageName; 1179 1180 final boolean mPermissionReviewRequired; 1181 1182 private final PackageUsage mPackageUsage = new PackageUsage(); 1183 private final CompilerStats mCompilerStats = new CompilerStats(); 1184 1185 class PackageHandler extends Handler { 1186 private boolean mBound = false; 1187 final ArrayList<HandlerParams> mPendingInstalls = 1188 new ArrayList<HandlerParams>(); 1189 1190 private boolean connectToService() { 1191 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1192 " DefaultContainerService"); 1193 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1194 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1195 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1196 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1197 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1198 mBound = true; 1199 return true; 1200 } 1201 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1202 return false; 1203 } 1204 1205 private void disconnectService() { 1206 mContainerService = null; 1207 mBound = false; 1208 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1209 mContext.unbindService(mDefContainerConn); 1210 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1211 } 1212 1213 PackageHandler(Looper looper) { 1214 super(looper); 1215 } 1216 1217 public void handleMessage(Message msg) { 1218 try { 1219 doHandleMessage(msg); 1220 } finally { 1221 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1222 } 1223 } 1224 1225 void doHandleMessage(Message msg) { 1226 switch (msg.what) { 1227 case INIT_COPY: { 1228 HandlerParams params = (HandlerParams) msg.obj; 1229 int idx = mPendingInstalls.size(); 1230 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1231 // If a bind was already initiated we dont really 1232 // need to do anything. The pending install 1233 // will be processed later on. 1234 if (!mBound) { 1235 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1236 System.identityHashCode(mHandler)); 1237 // If this is the only one pending we might 1238 // have to bind to the service again. 1239 if (!connectToService()) { 1240 Slog.e(TAG, "Failed to bind to media container service"); 1241 params.serviceError(); 1242 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1243 System.identityHashCode(mHandler)); 1244 if (params.traceMethod != null) { 1245 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1246 params.traceCookie); 1247 } 1248 return; 1249 } else { 1250 // Once we bind to the service, the first 1251 // pending request will be processed. 1252 mPendingInstalls.add(idx, params); 1253 } 1254 } else { 1255 mPendingInstalls.add(idx, params); 1256 // Already bound to the service. Just make 1257 // sure we trigger off processing the first request. 1258 if (idx == 0) { 1259 mHandler.sendEmptyMessage(MCS_BOUND); 1260 } 1261 } 1262 break; 1263 } 1264 case MCS_BOUND: { 1265 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1266 if (msg.obj != null) { 1267 mContainerService = (IMediaContainerService) msg.obj; 1268 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1269 System.identityHashCode(mHandler)); 1270 } 1271 if (mContainerService == null) { 1272 if (!mBound) { 1273 // Something seriously wrong since we are not bound and we are not 1274 // waiting for connection. Bail out. 1275 Slog.e(TAG, "Cannot bind to media container service"); 1276 for (HandlerParams params : mPendingInstalls) { 1277 // Indicate service bind error 1278 params.serviceError(); 1279 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1280 System.identityHashCode(params)); 1281 if (params.traceMethod != null) { 1282 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1283 params.traceMethod, params.traceCookie); 1284 } 1285 return; 1286 } 1287 mPendingInstalls.clear(); 1288 } else { 1289 Slog.w(TAG, "Waiting to connect to media container service"); 1290 } 1291 } else if (mPendingInstalls.size() > 0) { 1292 HandlerParams params = mPendingInstalls.get(0); 1293 if (params != null) { 1294 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1295 System.identityHashCode(params)); 1296 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1297 if (params.startCopy()) { 1298 // We are done... look for more work or to 1299 // go idle. 1300 if (DEBUG_SD_INSTALL) Log.i(TAG, 1301 "Checking for more work or unbind..."); 1302 // Delete pending install 1303 if (mPendingInstalls.size() > 0) { 1304 mPendingInstalls.remove(0); 1305 } 1306 if (mPendingInstalls.size() == 0) { 1307 if (mBound) { 1308 if (DEBUG_SD_INSTALL) Log.i(TAG, 1309 "Posting delayed MCS_UNBIND"); 1310 removeMessages(MCS_UNBIND); 1311 Message ubmsg = obtainMessage(MCS_UNBIND); 1312 // Unbind after a little delay, to avoid 1313 // continual thrashing. 1314 sendMessageDelayed(ubmsg, 10000); 1315 } 1316 } else { 1317 // There are more pending requests in queue. 1318 // Just post MCS_BOUND message to trigger processing 1319 // of next pending install. 1320 if (DEBUG_SD_INSTALL) Log.i(TAG, 1321 "Posting MCS_BOUND for next work"); 1322 mHandler.sendEmptyMessage(MCS_BOUND); 1323 } 1324 } 1325 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1326 } 1327 } else { 1328 // Should never happen ideally. 1329 Slog.w(TAG, "Empty queue"); 1330 } 1331 break; 1332 } 1333 case MCS_RECONNECT: { 1334 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1335 if (mPendingInstalls.size() > 0) { 1336 if (mBound) { 1337 disconnectService(); 1338 } 1339 if (!connectToService()) { 1340 Slog.e(TAG, "Failed to bind to media container service"); 1341 for (HandlerParams params : mPendingInstalls) { 1342 // Indicate service bind error 1343 params.serviceError(); 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1345 System.identityHashCode(params)); 1346 } 1347 mPendingInstalls.clear(); 1348 } 1349 } 1350 break; 1351 } 1352 case MCS_UNBIND: { 1353 // If there is no actual work left, then time to unbind. 1354 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1355 1356 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1357 if (mBound) { 1358 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1359 1360 disconnectService(); 1361 } 1362 } else if (mPendingInstalls.size() > 0) { 1363 // There are more pending requests in queue. 1364 // Just post MCS_BOUND message to trigger processing 1365 // of next pending install. 1366 mHandler.sendEmptyMessage(MCS_BOUND); 1367 } 1368 1369 break; 1370 } 1371 case MCS_GIVE_UP: { 1372 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1373 HandlerParams params = mPendingInstalls.remove(0); 1374 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1375 System.identityHashCode(params)); 1376 break; 1377 } 1378 case SEND_PENDING_BROADCAST: { 1379 String packages[]; 1380 ArrayList<String> components[]; 1381 int size = 0; 1382 int uids[]; 1383 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1384 synchronized (mPackages) { 1385 if (mPendingBroadcasts == null) { 1386 return; 1387 } 1388 size = mPendingBroadcasts.size(); 1389 if (size <= 0) { 1390 // Nothing to be done. Just return 1391 return; 1392 } 1393 packages = new String[size]; 1394 components = new ArrayList[size]; 1395 uids = new int[size]; 1396 int i = 0; // filling out the above arrays 1397 1398 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1399 int packageUserId = mPendingBroadcasts.userIdAt(n); 1400 Iterator<Map.Entry<String, ArrayList<String>>> it 1401 = mPendingBroadcasts.packagesForUserId(packageUserId) 1402 .entrySet().iterator(); 1403 while (it.hasNext() && i < size) { 1404 Map.Entry<String, ArrayList<String>> ent = it.next(); 1405 packages[i] = ent.getKey(); 1406 components[i] = ent.getValue(); 1407 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1408 uids[i] = (ps != null) 1409 ? UserHandle.getUid(packageUserId, ps.appId) 1410 : -1; 1411 i++; 1412 } 1413 } 1414 size = i; 1415 mPendingBroadcasts.clear(); 1416 } 1417 // Send broadcasts 1418 for (int i = 0; i < size; i++) { 1419 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1420 } 1421 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1422 break; 1423 } 1424 case START_CLEANING_PACKAGE: { 1425 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1426 final String packageName = (String)msg.obj; 1427 final int userId = msg.arg1; 1428 final boolean andCode = msg.arg2 != 0; 1429 synchronized (mPackages) { 1430 if (userId == UserHandle.USER_ALL) { 1431 int[] users = sUserManager.getUserIds(); 1432 for (int user : users) { 1433 mSettings.addPackageToCleanLPw( 1434 new PackageCleanItem(user, packageName, andCode)); 1435 } 1436 } else { 1437 mSettings.addPackageToCleanLPw( 1438 new PackageCleanItem(userId, packageName, andCode)); 1439 } 1440 } 1441 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1442 startCleaningPackages(); 1443 } break; 1444 case POST_INSTALL: { 1445 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1446 1447 PostInstallData data = mRunningInstalls.get(msg.arg1); 1448 final boolean didRestore = (msg.arg2 != 0); 1449 mRunningInstalls.delete(msg.arg1); 1450 1451 if (data != null) { 1452 InstallArgs args = data.args; 1453 PackageInstalledInfo parentRes = data.res; 1454 1455 final boolean grantPermissions = (args.installFlags 1456 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1457 final boolean killApp = (args.installFlags 1458 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1459 final String[] grantedPermissions = args.installGrantPermissions; 1460 1461 // Handle the parent package 1462 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1463 grantedPermissions, didRestore, args.installerPackageName, 1464 args.observer); 1465 1466 // Handle the child packages 1467 final int childCount = (parentRes.addedChildPackages != null) 1468 ? parentRes.addedChildPackages.size() : 0; 1469 for (int i = 0; i < childCount; i++) { 1470 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1471 handlePackagePostInstall(childRes, grantPermissions, killApp, 1472 grantedPermissions, false, args.installerPackageName, 1473 args.observer); 1474 } 1475 1476 // Log tracing if needed 1477 if (args.traceMethod != null) { 1478 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1479 args.traceCookie); 1480 } 1481 } else { 1482 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1483 } 1484 1485 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1486 } break; 1487 case UPDATED_MEDIA_STATUS: { 1488 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1489 boolean reportStatus = msg.arg1 == 1; 1490 boolean doGc = msg.arg2 == 1; 1491 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1492 if (doGc) { 1493 // Force a gc to clear up stale containers. 1494 Runtime.getRuntime().gc(); 1495 } 1496 if (msg.obj != null) { 1497 @SuppressWarnings("unchecked") 1498 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1499 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1500 // Unload containers 1501 unloadAllContainers(args); 1502 } 1503 if (reportStatus) { 1504 try { 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, 1506 "Invoking StorageManagerService call back"); 1507 PackageHelper.getStorageManager().finishMediaUpdate(); 1508 } catch (RemoteException e) { 1509 Log.e(TAG, "StorageManagerService not running?"); 1510 } 1511 } 1512 } break; 1513 case WRITE_SETTINGS: { 1514 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1515 synchronized (mPackages) { 1516 removeMessages(WRITE_SETTINGS); 1517 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1518 mSettings.writeLPr(); 1519 mDirtyUsers.clear(); 1520 } 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1522 } break; 1523 case WRITE_PACKAGE_RESTRICTIONS: { 1524 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1525 synchronized (mPackages) { 1526 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1527 for (int userId : mDirtyUsers) { 1528 mSettings.writePackageRestrictionsLPr(userId); 1529 } 1530 mDirtyUsers.clear(); 1531 } 1532 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1533 } break; 1534 case WRITE_PACKAGE_LIST: { 1535 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1536 synchronized (mPackages) { 1537 removeMessages(WRITE_PACKAGE_LIST); 1538 mSettings.writePackageListLPr(msg.arg1); 1539 } 1540 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1541 } break; 1542 case CHECK_PENDING_VERIFICATION: { 1543 final int verificationId = msg.arg1; 1544 final PackageVerificationState state = mPendingVerification.get(verificationId); 1545 1546 if ((state != null) && !state.timeoutExtended()) { 1547 final InstallArgs args = state.getInstallArgs(); 1548 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1549 1550 Slog.i(TAG, "Verification timed out for " + originUri); 1551 mPendingVerification.remove(verificationId); 1552 1553 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1554 1555 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1556 Slog.i(TAG, "Continuing with installation of " + originUri); 1557 state.setVerifierResponse(Binder.getCallingUid(), 1558 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1559 broadcastPackageVerified(verificationId, originUri, 1560 PackageManager.VERIFICATION_ALLOW, 1561 state.getInstallArgs().getUser()); 1562 try { 1563 ret = args.copyApk(mContainerService, true); 1564 } catch (RemoteException e) { 1565 Slog.e(TAG, "Could not contact the ContainerService"); 1566 } 1567 } else { 1568 broadcastPackageVerified(verificationId, originUri, 1569 PackageManager.VERIFICATION_REJECT, 1570 state.getInstallArgs().getUser()); 1571 } 1572 1573 Trace.asyncTraceEnd( 1574 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1575 1576 processPendingInstall(args, ret); 1577 mHandler.sendEmptyMessage(MCS_UNBIND); 1578 } 1579 break; 1580 } 1581 case PACKAGE_VERIFIED: { 1582 final int verificationId = msg.arg1; 1583 1584 final PackageVerificationState state = mPendingVerification.get(verificationId); 1585 if (state == null) { 1586 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1587 break; 1588 } 1589 1590 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1591 1592 state.setVerifierResponse(response.callerUid, response.code); 1593 1594 if (state.isVerificationComplete()) { 1595 mPendingVerification.remove(verificationId); 1596 1597 final InstallArgs args = state.getInstallArgs(); 1598 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1599 1600 int ret; 1601 if (state.isInstallAllowed()) { 1602 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1603 broadcastPackageVerified(verificationId, originUri, 1604 response.code, state.getInstallArgs().getUser()); 1605 try { 1606 ret = args.copyApk(mContainerService, true); 1607 } catch (RemoteException e) { 1608 Slog.e(TAG, "Could not contact the ContainerService"); 1609 } 1610 } else { 1611 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1612 } 1613 1614 Trace.asyncTraceEnd( 1615 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1616 1617 processPendingInstall(args, ret); 1618 mHandler.sendEmptyMessage(MCS_UNBIND); 1619 } 1620 1621 break; 1622 } 1623 case START_INTENT_FILTER_VERIFICATIONS: { 1624 IFVerificationParams params = (IFVerificationParams) msg.obj; 1625 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1626 params.replacing, params.pkg); 1627 break; 1628 } 1629 case INTENT_FILTER_VERIFIED: { 1630 final int verificationId = msg.arg1; 1631 1632 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1633 verificationId); 1634 if (state == null) { 1635 Slog.w(TAG, "Invalid IntentFilter verification token " 1636 + verificationId + " received"); 1637 break; 1638 } 1639 1640 final int userId = state.getUserId(); 1641 1642 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1643 "Processing IntentFilter verification with token:" 1644 + verificationId + " and userId:" + userId); 1645 1646 final IntentFilterVerificationResponse response = 1647 (IntentFilterVerificationResponse) msg.obj; 1648 1649 state.setVerifierResponse(response.callerUid, response.code); 1650 1651 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1652 "IntentFilter verification with token:" + verificationId 1653 + " and userId:" + userId 1654 + " is settings verifier response with response code:" 1655 + response.code); 1656 1657 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1658 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1659 + response.getFailedDomainsString()); 1660 } 1661 1662 if (state.isVerificationComplete()) { 1663 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1664 } else { 1665 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1666 "IntentFilter verification with token:" + verificationId 1667 + " was not said to be complete"); 1668 } 1669 1670 break; 1671 } 1672 case EPHEMERAL_RESOLUTION_PHASE_TWO: { 1673 EphemeralResolver.doEphemeralResolutionPhaseTwo(mContext, 1674 mEphemeralResolverConnection, 1675 (EphemeralRequest) msg.obj, 1676 mEphemeralInstallerActivity, 1677 mHandler); 1678 } 1679 } 1680 } 1681 } 1682 1683 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1684 boolean killApp, String[] grantedPermissions, 1685 boolean launchedForRestore, String installerPackage, 1686 IPackageInstallObserver2 installObserver) { 1687 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1688 // Send the removed broadcasts 1689 if (res.removedInfo != null) { 1690 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1691 } 1692 1693 // Now that we successfully installed the package, grant runtime 1694 // permissions if requested before broadcasting the install. 1695 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1696 >= Build.VERSION_CODES.M) { 1697 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1698 } 1699 1700 final boolean update = res.removedInfo != null 1701 && res.removedInfo.removedPackage != null; 1702 1703 // If this is the first time we have child packages for a disabled privileged 1704 // app that had no children, we grant requested runtime permissions to the new 1705 // children if the parent on the system image had them already granted. 1706 if (res.pkg.parentPackage != null) { 1707 synchronized (mPackages) { 1708 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1709 } 1710 } 1711 1712 synchronized (mPackages) { 1713 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1714 } 1715 1716 final String packageName = res.pkg.applicationInfo.packageName; 1717 1718 // Determine the set of users who are adding this package for 1719 // the first time vs. those who are seeing an update. 1720 int[] firstUsers = EMPTY_INT_ARRAY; 1721 int[] updateUsers = EMPTY_INT_ARRAY; 1722 if (res.origUsers == null || res.origUsers.length == 0) { 1723 firstUsers = res.newUsers; 1724 } else { 1725 for (int newUser : res.newUsers) { 1726 boolean isNew = true; 1727 for (int origUser : res.origUsers) { 1728 if (origUser == newUser) { 1729 isNew = false; 1730 break; 1731 } 1732 } 1733 if (isNew) { 1734 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1735 } else { 1736 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1737 } 1738 } 1739 } 1740 1741 // Send installed broadcasts if the install/update is not ephemeral 1742 if (!isEphemeral(res.pkg)) { 1743 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1744 1745 // Send added for users that see the package for the first time 1746 // sendPackageAddedForNewUsers also deals with system apps 1747 int appId = UserHandle.getAppId(res.uid); 1748 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1749 sendPackageAddedForNewUsers(packageName, isSystem, appId, firstUsers); 1750 1751 // Send added for users that don't see the package for the first time 1752 Bundle extras = new Bundle(1); 1753 extras.putInt(Intent.EXTRA_UID, res.uid); 1754 if (update) { 1755 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1756 } 1757 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1758 extras, 0 /*flags*/, null /*targetPackage*/, 1759 null /*finishedReceiver*/, updateUsers); 1760 1761 // Send replaced for users that don't see the package for the first time 1762 if (update) { 1763 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1764 packageName, extras, 0 /*flags*/, 1765 null /*targetPackage*/, null /*finishedReceiver*/, 1766 updateUsers); 1767 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1768 null /*package*/, null /*extras*/, 0 /*flags*/, 1769 packageName /*targetPackage*/, 1770 null /*finishedReceiver*/, updateUsers); 1771 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1772 // First-install and we did a restore, so we're responsible for the 1773 // first-launch broadcast. 1774 if (DEBUG_BACKUP) { 1775 Slog.i(TAG, "Post-restore of " + packageName 1776 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1777 } 1778 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1779 } 1780 1781 // Send broadcast package appeared if forward locked/external for all users 1782 // treat asec-hosted packages like removable media on upgrade 1783 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1784 if (DEBUG_INSTALL) { 1785 Slog.i(TAG, "upgrading pkg " + res.pkg 1786 + " is ASEC-hosted -> AVAILABLE"); 1787 } 1788 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1789 ArrayList<String> pkgList = new ArrayList<>(1); 1790 pkgList.add(packageName); 1791 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1792 } 1793 } 1794 1795 // Work that needs to happen on first install within each user 1796 if (firstUsers != null && firstUsers.length > 0) { 1797 synchronized (mPackages) { 1798 for (int userId : firstUsers) { 1799 // If this app is a browser and it's newly-installed for some 1800 // users, clear any default-browser state in those users. The 1801 // app's nature doesn't depend on the user, so we can just check 1802 // its browser nature in any user and generalize. 1803 if (packageIsBrowser(packageName, userId)) { 1804 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1805 } 1806 1807 // We may also need to apply pending (restored) runtime 1808 // permission grants within these users. 1809 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1810 } 1811 } 1812 } 1813 1814 // Log current value of "unknown sources" setting 1815 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1816 getUnknownSourcesSettings()); 1817 1818 // Force a gc to clear up things 1819 Runtime.getRuntime().gc(); 1820 1821 // Remove the replaced package's older resources safely now 1822 // We delete after a gc for applications on sdcard. 1823 if (res.removedInfo != null && res.removedInfo.args != null) { 1824 synchronized (mInstallLock) { 1825 res.removedInfo.args.doPostDeleteLI(true); 1826 } 1827 } 1828 } 1829 1830 // If someone is watching installs - notify them 1831 if (installObserver != null) { 1832 try { 1833 Bundle extras = extrasForInstallResult(res); 1834 installObserver.onPackageInstalled(res.name, res.returnCode, 1835 res.returnMsg, extras); 1836 } catch (RemoteException e) { 1837 Slog.i(TAG, "Observer no longer exists."); 1838 } 1839 } 1840 } 1841 1842 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1843 PackageParser.Package pkg) { 1844 if (pkg.parentPackage == null) { 1845 return; 1846 } 1847 if (pkg.requestedPermissions == null) { 1848 return; 1849 } 1850 final PackageSetting disabledSysParentPs = mSettings 1851 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1852 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1853 || !disabledSysParentPs.isPrivileged() 1854 || (disabledSysParentPs.childPackageNames != null 1855 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1856 return; 1857 } 1858 final int[] allUserIds = sUserManager.getUserIds(); 1859 final int permCount = pkg.requestedPermissions.size(); 1860 for (int i = 0; i < permCount; i++) { 1861 String permission = pkg.requestedPermissions.get(i); 1862 BasePermission bp = mSettings.mPermissions.get(permission); 1863 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1864 continue; 1865 } 1866 for (int userId : allUserIds) { 1867 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1868 permission, userId)) { 1869 grantRuntimePermission(pkg.packageName, permission, userId); 1870 } 1871 } 1872 } 1873 } 1874 1875 private StorageEventListener mStorageListener = new StorageEventListener() { 1876 @Override 1877 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1878 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1879 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1880 final String volumeUuid = vol.getFsUuid(); 1881 1882 // Clean up any users or apps that were removed or recreated 1883 // while this volume was missing 1884 reconcileUsers(volumeUuid); 1885 reconcileApps(volumeUuid); 1886 1887 // Clean up any install sessions that expired or were 1888 // cancelled while this volume was missing 1889 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1890 1891 loadPrivatePackages(vol); 1892 1893 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1894 unloadPrivatePackages(vol); 1895 } 1896 } 1897 1898 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1899 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1900 updateExternalMediaStatus(true, false); 1901 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1902 updateExternalMediaStatus(false, false); 1903 } 1904 } 1905 } 1906 1907 @Override 1908 public void onVolumeForgotten(String fsUuid) { 1909 if (TextUtils.isEmpty(fsUuid)) { 1910 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1911 return; 1912 } 1913 1914 // Remove any apps installed on the forgotten volume 1915 synchronized (mPackages) { 1916 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1917 for (PackageSetting ps : packages) { 1918 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1919 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1920 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1921 1922 // Try very hard to release any references to this package 1923 // so we don't risk the system server being killed due to 1924 // open FDs 1925 AttributeCache.instance().removePackage(ps.name); 1926 } 1927 1928 mSettings.onVolumeForgotten(fsUuid); 1929 mSettings.writeLPr(); 1930 } 1931 } 1932 }; 1933 1934 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1935 String[] grantedPermissions) { 1936 for (int userId : userIds) { 1937 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1938 } 1939 1940 // We could have touched GID membership, so flush out packages.list 1941 synchronized (mPackages) { 1942 mSettings.writePackageListLPr(); 1943 } 1944 } 1945 1946 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1947 String[] grantedPermissions) { 1948 SettingBase sb = (SettingBase) pkg.mExtras; 1949 if (sb == null) { 1950 return; 1951 } 1952 1953 PermissionsState permissionsState = sb.getPermissionsState(); 1954 1955 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1956 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1957 1958 for (String permission : pkg.requestedPermissions) { 1959 final BasePermission bp; 1960 synchronized (mPackages) { 1961 bp = mSettings.mPermissions.get(permission); 1962 } 1963 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1964 && (grantedPermissions == null 1965 || ArrayUtils.contains(grantedPermissions, permission))) { 1966 final int flags = permissionsState.getPermissionFlags(permission, userId); 1967 // Installer cannot change immutable permissions. 1968 if ((flags & immutableFlags) == 0) { 1969 grantRuntimePermission(pkg.packageName, permission, userId); 1970 } 1971 } 1972 } 1973 } 1974 1975 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1976 Bundle extras = null; 1977 switch (res.returnCode) { 1978 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1979 extras = new Bundle(); 1980 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1981 res.origPermission); 1982 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1983 res.origPackage); 1984 break; 1985 } 1986 case PackageManager.INSTALL_SUCCEEDED: { 1987 extras = new Bundle(); 1988 extras.putBoolean(Intent.EXTRA_REPLACING, 1989 res.removedInfo != null && res.removedInfo.removedPackage != null); 1990 break; 1991 } 1992 } 1993 return extras; 1994 } 1995 1996 void scheduleWriteSettingsLocked() { 1997 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1998 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1999 } 2000 } 2001 2002 void scheduleWritePackageListLocked(int userId) { 2003 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2004 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2005 msg.arg1 = userId; 2006 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2007 } 2008 } 2009 2010 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2011 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2012 scheduleWritePackageRestrictionsLocked(userId); 2013 } 2014 2015 void scheduleWritePackageRestrictionsLocked(int userId) { 2016 final int[] userIds = (userId == UserHandle.USER_ALL) 2017 ? sUserManager.getUserIds() : new int[]{userId}; 2018 for (int nextUserId : userIds) { 2019 if (!sUserManager.exists(nextUserId)) return; 2020 mDirtyUsers.add(nextUserId); 2021 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2022 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2023 } 2024 } 2025 } 2026 2027 public static PackageManagerService main(Context context, Installer installer, 2028 boolean factoryTest, boolean onlyCore) { 2029 // Self-check for initial settings. 2030 PackageManagerServiceCompilerMapping.checkProperties(); 2031 2032 PackageManagerService m = new PackageManagerService(context, installer, 2033 factoryTest, onlyCore); 2034 m.enableSystemUserPackages(); 2035 ServiceManager.addService("package", m); 2036 return m; 2037 } 2038 2039 private void enableSystemUserPackages() { 2040 if (!UserManager.isSplitSystemUser()) { 2041 return; 2042 } 2043 // For system user, enable apps based on the following conditions: 2044 // - app is whitelisted or belong to one of these groups: 2045 // -- system app which has no launcher icons 2046 // -- system app which has INTERACT_ACROSS_USERS permission 2047 // -- system IME app 2048 // - app is not in the blacklist 2049 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2050 Set<String> enableApps = new ArraySet<>(); 2051 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2052 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2053 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2054 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2055 enableApps.addAll(wlApps); 2056 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2057 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2058 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2059 enableApps.removeAll(blApps); 2060 Log.i(TAG, "Applications installed for system user: " + enableApps); 2061 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2062 UserHandle.SYSTEM); 2063 final int allAppsSize = allAps.size(); 2064 synchronized (mPackages) { 2065 for (int i = 0; i < allAppsSize; i++) { 2066 String pName = allAps.get(i); 2067 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2068 // Should not happen, but we shouldn't be failing if it does 2069 if (pkgSetting == null) { 2070 continue; 2071 } 2072 boolean install = enableApps.contains(pName); 2073 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2074 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2075 + " for system user"); 2076 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2077 } 2078 } 2079 } 2080 } 2081 2082 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2083 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2084 Context.DISPLAY_SERVICE); 2085 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2086 } 2087 2088 /** 2089 * Requests that files preopted on a secondary system partition be copied to the data partition 2090 * if possible. Note that the actual copying of the files is accomplished by init for security 2091 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2092 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2093 */ 2094 private static void requestCopyPreoptedFiles() { 2095 final int WAIT_TIME_MS = 100; 2096 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2097 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2098 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2099 // We will wait for up to 100 seconds. 2100 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2101 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2102 try { 2103 Thread.sleep(WAIT_TIME_MS); 2104 } catch (InterruptedException e) { 2105 // Do nothing 2106 } 2107 if (SystemClock.uptimeMillis() > timeEnd) { 2108 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2109 Slog.wtf(TAG, "cppreopt did not finish!"); 2110 break; 2111 } 2112 } 2113 } 2114 } 2115 2116 public PackageManagerService(Context context, Installer installer, 2117 boolean factoryTest, boolean onlyCore) { 2118 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2119 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2120 SystemClock.uptimeMillis()); 2121 2122 if (mSdkVersion <= 0) { 2123 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2124 } 2125 2126 mContext = context; 2127 2128 mPermissionReviewRequired = context.getResources().getBoolean( 2129 R.bool.config_permissionReviewRequired); 2130 2131 mFactoryTest = factoryTest; 2132 mOnlyCore = onlyCore; 2133 mMetrics = new DisplayMetrics(); 2134 mSettings = new Settings(mPackages); 2135 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2136 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2137 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2138 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2139 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2140 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2141 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2142 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2143 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2144 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2145 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2146 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2147 2148 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2149 if (separateProcesses != null && separateProcesses.length() > 0) { 2150 if ("*".equals(separateProcesses)) { 2151 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2152 mSeparateProcesses = null; 2153 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2154 } else { 2155 mDefParseFlags = 0; 2156 mSeparateProcesses = separateProcesses.split(","); 2157 Slog.w(TAG, "Running with debug.separate_processes: " 2158 + separateProcesses); 2159 } 2160 } else { 2161 mDefParseFlags = 0; 2162 mSeparateProcesses = null; 2163 } 2164 2165 mInstaller = installer; 2166 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2167 "*dexopt*"); 2168 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2169 2170 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2171 FgThread.get().getLooper()); 2172 2173 getDefaultDisplayMetrics(context, mMetrics); 2174 2175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2176 SystemConfig systemConfig = SystemConfig.getInstance(); 2177 mGlobalGids = systemConfig.getGlobalGids(); 2178 mSystemPermissions = systemConfig.getSystemPermissions(); 2179 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2181 2182 mProtectedPackages = new ProtectedPackages(mContext); 2183 2184 synchronized (mInstallLock) { 2185 // writer 2186 synchronized (mPackages) { 2187 mHandlerThread = new ServiceThread(TAG, 2188 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2189 mHandlerThread.start(); 2190 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2191 mProcessLoggingHandler = new ProcessLoggingHandler(); 2192 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2193 2194 mDefaultPermissionPolicy = new DefaultPermissionGrantPolicy(this); 2195 2196 File dataDir = Environment.getDataDirectory(); 2197 mAppInstallDir = new File(dataDir, "app"); 2198 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2199 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2200 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2201 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2202 2203 sUserManager = new UserManagerService(context, this, mPackages); 2204 2205 // Propagate permission configuration in to package manager. 2206 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2207 = systemConfig.getPermissions(); 2208 for (int i=0; i<permConfig.size(); i++) { 2209 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2210 BasePermission bp = mSettings.mPermissions.get(perm.name); 2211 if (bp == null) { 2212 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2213 mSettings.mPermissions.put(perm.name, bp); 2214 } 2215 if (perm.gids != null) { 2216 bp.setGids(perm.gids, perm.perUser); 2217 } 2218 } 2219 2220 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2221 for (int i=0; i<libConfig.size(); i++) { 2222 mSharedLibraries.put(libConfig.keyAt(i), 2223 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2224 } 2225 2226 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2227 2228 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2229 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2230 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2231 2232 if (mFirstBoot) { 2233 requestCopyPreoptedFiles(); 2234 } 2235 2236 String customResolverActivity = Resources.getSystem().getString( 2237 R.string.config_customResolverActivity); 2238 if (TextUtils.isEmpty(customResolverActivity)) { 2239 customResolverActivity = null; 2240 } else { 2241 mCustomResolverComponentName = ComponentName.unflattenFromString( 2242 customResolverActivity); 2243 } 2244 2245 long startTime = SystemClock.uptimeMillis(); 2246 2247 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2248 startTime); 2249 2250 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2251 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2252 2253 if (bootClassPath == null) { 2254 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2255 } 2256 2257 if (systemServerClassPath == null) { 2258 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2259 } 2260 2261 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2262 final String[] dexCodeInstructionSets = 2263 getDexCodeInstructionSets( 2264 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2265 2266 /** 2267 * Ensure all external libraries have had dexopt run on them. 2268 */ 2269 if (mSharedLibraries.size() > 0) { 2270 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 2271 // NOTE: For now, we're compiling these system "shared libraries" 2272 // (and framework jars) into all available architectures. It's possible 2273 // to compile them only when we come across an app that uses them (there's 2274 // already logic for that in scanPackageLI) but that adds some complexity. 2275 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2276 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2277 final String lib = libEntry.path; 2278 if (lib == null) { 2279 continue; 2280 } 2281 2282 try { 2283 // Shared libraries do not have profiles so we perform a full 2284 // AOT compilation (if needed). 2285 int dexoptNeeded = DexFile.getDexOptNeeded( 2286 lib, dexCodeInstructionSet, 2287 getCompilerFilterForReason(REASON_SHARED_APK), 2288 false /* newProfile */); 2289 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2290 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2291 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2292 getCompilerFilterForReason(REASON_SHARED_APK), 2293 StorageManager.UUID_PRIVATE_INTERNAL, 2294 SKIP_SHARED_LIBRARY_CHECK); 2295 } 2296 } catch (FileNotFoundException e) { 2297 Slog.w(TAG, "Library not found: " + lib); 2298 } catch (IOException | InstallerException e) { 2299 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2300 + e.getMessage()); 2301 } 2302 } 2303 } 2304 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2305 } 2306 2307 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2308 2309 final VersionInfo ver = mSettings.getInternalVersion(); 2310 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2311 2312 // when upgrading from pre-M, promote system app permissions from install to runtime 2313 mPromoteSystemApps = 2314 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2315 2316 // When upgrading from pre-N, we need to handle package extraction like first boot, 2317 // as there is no profiling data available. 2318 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2319 2320 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2321 2322 // save off the names of pre-existing system packages prior to scanning; we don't 2323 // want to automatically grant runtime permissions for new system apps 2324 if (mPromoteSystemApps) { 2325 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2326 while (pkgSettingIter.hasNext()) { 2327 PackageSetting ps = pkgSettingIter.next(); 2328 if (isSystemApp(ps)) { 2329 mExistingSystemPackages.add(ps.name); 2330 } 2331 } 2332 } 2333 2334 // Set flag to monitor and not change apk file paths when 2335 // scanning install directories. 2336 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2337 2338 if (mIsUpgrade || mFirstBoot) { 2339 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2340 } 2341 2342 // Collect vendor overlay packages. (Do this before scanning any apps.) 2343 // For security and version matching reason, only consider 2344 // overlay packages if they reside in the right directory. 2345 String overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PERSIST_PROPERTY); 2346 if (overlayThemeDir.isEmpty()) { 2347 overlayThemeDir = SystemProperties.get(VENDOR_OVERLAY_THEME_PROPERTY); 2348 } 2349 if (!overlayThemeDir.isEmpty()) { 2350 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR, overlayThemeDir), mDefParseFlags 2351 | PackageParser.PARSE_IS_SYSTEM 2352 | PackageParser.PARSE_IS_SYSTEM_DIR 2353 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2354 } 2355 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), mDefParseFlags 2356 | PackageParser.PARSE_IS_SYSTEM 2357 | PackageParser.PARSE_IS_SYSTEM_DIR 2358 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2359 2360 // Find base frameworks (resource packages without code). 2361 scanDirTracedLI(frameworkDir, mDefParseFlags 2362 | PackageParser.PARSE_IS_SYSTEM 2363 | PackageParser.PARSE_IS_SYSTEM_DIR 2364 | PackageParser.PARSE_IS_PRIVILEGED, 2365 scanFlags | SCAN_NO_DEX, 0); 2366 2367 // Collected privileged system packages. 2368 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2369 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2370 | PackageParser.PARSE_IS_SYSTEM 2371 | PackageParser.PARSE_IS_SYSTEM_DIR 2372 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2373 2374 // Collect ordinary system packages. 2375 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2376 scanDirTracedLI(systemAppDir, mDefParseFlags 2377 | PackageParser.PARSE_IS_SYSTEM 2378 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2379 2380 // Collect all vendor packages. 2381 File vendorAppDir = new File("/vendor/app"); 2382 try { 2383 vendorAppDir = vendorAppDir.getCanonicalFile(); 2384 } catch (IOException e) { 2385 // failed to look up canonical path, continue with original one 2386 } 2387 scanDirTracedLI(vendorAppDir, mDefParseFlags 2388 | PackageParser.PARSE_IS_SYSTEM 2389 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2390 2391 // Collect all OEM packages. 2392 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2393 scanDirTracedLI(oemAppDir, mDefParseFlags 2394 | PackageParser.PARSE_IS_SYSTEM 2395 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2396 2397 // Prune any system packages that no longer exist. 2398 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2399 if (!mOnlyCore) { 2400 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2401 while (psit.hasNext()) { 2402 PackageSetting ps = psit.next(); 2403 2404 /* 2405 * If this is not a system app, it can't be a 2406 * disable system app. 2407 */ 2408 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2409 continue; 2410 } 2411 2412 /* 2413 * If the package is scanned, it's not erased. 2414 */ 2415 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2416 if (scannedPkg != null) { 2417 /* 2418 * If the system app is both scanned and in the 2419 * disabled packages list, then it must have been 2420 * added via OTA. Remove it from the currently 2421 * scanned package so the previously user-installed 2422 * application can be scanned. 2423 */ 2424 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2425 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2426 + ps.name + "; removing system app. Last known codePath=" 2427 + ps.codePathString + ", installStatus=" + ps.installStatus 2428 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2429 + scannedPkg.mVersionCode); 2430 removePackageLI(scannedPkg, true); 2431 mExpectingBetter.put(ps.name, ps.codePath); 2432 } 2433 2434 continue; 2435 } 2436 2437 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2438 psit.remove(); 2439 logCriticalInfo(Log.WARN, "System package " + ps.name 2440 + " no longer exists; it's data will be wiped"); 2441 // Actual deletion of code and data will be handled by later 2442 // reconciliation step 2443 } else { 2444 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2445 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2446 possiblyDeletedUpdatedSystemApps.add(ps.name); 2447 } 2448 } 2449 } 2450 } 2451 2452 //look for any incomplete package installations 2453 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2454 for (int i = 0; i < deletePkgsList.size(); i++) { 2455 // Actual deletion of code and data will be handled by later 2456 // reconciliation step 2457 final String packageName = deletePkgsList.get(i).name; 2458 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2459 synchronized (mPackages) { 2460 mSettings.removePackageLPw(packageName); 2461 } 2462 } 2463 2464 //delete tmp files 2465 deleteTempPackageFiles(); 2466 2467 // Remove any shared userIDs that have no associated packages 2468 mSettings.pruneSharedUsersLPw(); 2469 2470 if (!mOnlyCore) { 2471 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2472 SystemClock.uptimeMillis()); 2473 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2474 2475 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2476 | PackageParser.PARSE_FORWARD_LOCK, 2477 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2478 2479 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2480 | PackageParser.PARSE_IS_EPHEMERAL, 2481 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2482 2483 /** 2484 * Remove disable package settings for any updated system 2485 * apps that were removed via an OTA. If they're not a 2486 * previously-updated app, remove them completely. 2487 * Otherwise, just revoke their system-level permissions. 2488 */ 2489 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2490 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2491 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2492 2493 String msg; 2494 if (deletedPkg == null) { 2495 msg = "Updated system package " + deletedAppName 2496 + " no longer exists; it's data will be wiped"; 2497 // Actual deletion of code and data will be handled by later 2498 // reconciliation step 2499 } else { 2500 msg = "Updated system app + " + deletedAppName 2501 + " no longer present; removing system privileges for " 2502 + deletedAppName; 2503 2504 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2505 2506 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2507 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2508 } 2509 logCriticalInfo(Log.WARN, msg); 2510 } 2511 2512 /** 2513 * Make sure all system apps that we expected to appear on 2514 * the userdata partition actually showed up. If they never 2515 * appeared, crawl back and revive the system version. 2516 */ 2517 for (int i = 0; i < mExpectingBetter.size(); i++) { 2518 final String packageName = mExpectingBetter.keyAt(i); 2519 if (!mPackages.containsKey(packageName)) { 2520 final File scanFile = mExpectingBetter.valueAt(i); 2521 2522 logCriticalInfo(Log.WARN, "Expected better " + packageName 2523 + " but never showed up; reverting to system"); 2524 2525 int reparseFlags = mDefParseFlags; 2526 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2527 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2528 | PackageParser.PARSE_IS_SYSTEM_DIR 2529 | PackageParser.PARSE_IS_PRIVILEGED; 2530 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2531 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2532 | PackageParser.PARSE_IS_SYSTEM_DIR; 2533 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2534 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2535 | PackageParser.PARSE_IS_SYSTEM_DIR; 2536 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2537 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2538 | PackageParser.PARSE_IS_SYSTEM_DIR; 2539 } else { 2540 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2541 continue; 2542 } 2543 2544 mSettings.enableSystemPackageLPw(packageName); 2545 2546 try { 2547 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2548 } catch (PackageManagerException e) { 2549 Slog.e(TAG, "Failed to parse original system package: " 2550 + e.getMessage()); 2551 } 2552 } 2553 } 2554 } 2555 mExpectingBetter.clear(); 2556 2557 // Resolve the storage manager. 2558 mStorageManagerPackage = getStorageManagerPackageName(); 2559 2560 // Resolve protected action filters. Only the setup wizard is allowed to 2561 // have a high priority filter for these actions. 2562 mSetupWizardPackage = getSetupWizardPackageName(); 2563 if (mProtectedFilters.size() > 0) { 2564 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2565 Slog.i(TAG, "No setup wizard;" 2566 + " All protected intents capped to priority 0"); 2567 } 2568 for (ActivityIntentInfo filter : mProtectedFilters) { 2569 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2570 if (DEBUG_FILTERS) { 2571 Slog.i(TAG, "Found setup wizard;" 2572 + " allow priority " + filter.getPriority() + ";" 2573 + " package: " + filter.activity.info.packageName 2574 + " activity: " + filter.activity.className 2575 + " priority: " + filter.getPriority()); 2576 } 2577 // skip setup wizard; allow it to keep the high priority filter 2578 continue; 2579 } 2580 Slog.w(TAG, "Protected action; cap priority to 0;" 2581 + " package: " + filter.activity.info.packageName 2582 + " activity: " + filter.activity.className 2583 + " origPrio: " + filter.getPriority()); 2584 filter.setPriority(0); 2585 } 2586 } 2587 mDeferProtectedFilters = false; 2588 mProtectedFilters.clear(); 2589 2590 // Now that we know all of the shared libraries, update all clients to have 2591 // the correct library paths. 2592 updateAllSharedLibrariesLPw(); 2593 2594 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2595 // NOTE: We ignore potential failures here during a system scan (like 2596 // the rest of the commands above) because there's precious little we 2597 // can do about it. A settings error is reported, though. 2598 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2599 } 2600 2601 // Now that we know all the packages we are keeping, 2602 // read and update their last usage times. 2603 mPackageUsage.read(mPackages); 2604 mCompilerStats.read(); 2605 2606 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2607 SystemClock.uptimeMillis()); 2608 Slog.i(TAG, "Time to scan packages: " 2609 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2610 + " seconds"); 2611 2612 // If the platform SDK has changed since the last time we booted, 2613 // we need to re-grant app permission to catch any new ones that 2614 // appear. This is really a hack, and means that apps can in some 2615 // cases get permissions that the user didn't initially explicitly 2616 // allow... it would be nice to have some better way to handle 2617 // this situation. 2618 int updateFlags = UPDATE_PERMISSIONS_ALL; 2619 if (ver.sdkVersion != mSdkVersion) { 2620 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2621 + mSdkVersion + "; regranting permissions for internal storage"); 2622 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2623 } 2624 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2625 ver.sdkVersion = mSdkVersion; 2626 2627 // If this is the first boot or an update from pre-M, and it is a normal 2628 // boot, then we need to initialize the default preferred apps across 2629 // all defined users. 2630 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2631 for (UserInfo user : sUserManager.getUsers(true)) { 2632 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2633 applyFactoryDefaultBrowserLPw(user.id); 2634 primeDomainVerificationsLPw(user.id); 2635 } 2636 } 2637 2638 // Prepare storage for system user really early during boot, 2639 // since core system apps like SettingsProvider and SystemUI 2640 // can't wait for user to start 2641 final int storageFlags; 2642 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2643 storageFlags = StorageManager.FLAG_STORAGE_DE; 2644 } else { 2645 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2646 } 2647 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2648 storageFlags, true /* migrateAppData */); 2649 2650 // If this is first boot after an OTA, and a normal boot, then 2651 // we need to clear code cache directories. 2652 // Note that we do *not* clear the application profiles. These remain valid 2653 // across OTAs and are used to drive profile verification (post OTA) and 2654 // profile compilation (without waiting to collect a fresh set of profiles). 2655 if (mIsUpgrade && !onlyCore) { 2656 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2657 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2658 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2659 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2660 // No apps are running this early, so no need to freeze 2661 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2662 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2663 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2664 } 2665 } 2666 ver.fingerprint = Build.FINGERPRINT; 2667 } 2668 2669 checkDefaultBrowser(); 2670 2671 // clear only after permissions and other defaults have been updated 2672 mExistingSystemPackages.clear(); 2673 mPromoteSystemApps = false; 2674 2675 // All the changes are done during package scanning. 2676 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2677 2678 // can downgrade to reader 2679 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 2680 mSettings.writeLPr(); 2681 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2682 2683 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2684 // early on (before the package manager declares itself as early) because other 2685 // components in the system server might ask for package contexts for these apps. 2686 // 2687 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2688 // (i.e, that the data partition is unavailable). 2689 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2690 long start = System.nanoTime(); 2691 List<PackageParser.Package> coreApps = new ArrayList<>(); 2692 for (PackageParser.Package pkg : mPackages.values()) { 2693 if (pkg.coreApp) { 2694 coreApps.add(pkg); 2695 } 2696 } 2697 2698 int[] stats = performDexOptUpgrade(coreApps, false, 2699 getCompilerFilterForReason(REASON_CORE_APP)); 2700 2701 final int elapsedTimeSeconds = 2702 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2703 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2704 2705 if (DEBUG_DEXOPT) { 2706 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2707 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2708 } 2709 2710 2711 // TODO: Should we log these stats to tron too ? 2712 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2713 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2714 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2715 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2716 } 2717 2718 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2719 SystemClock.uptimeMillis()); 2720 2721 if (!mOnlyCore) { 2722 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2723 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2724 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 2725 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2726 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2727 mIntentFilterVerifierComponent); 2728 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2729 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2730 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2731 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2732 } else { 2733 mRequiredVerifierPackage = null; 2734 mRequiredInstallerPackage = null; 2735 mRequiredUninstallerPackage = null; 2736 mIntentFilterVerifierComponent = null; 2737 mIntentFilterVerifier = null; 2738 mServicesSystemSharedLibraryPackageName = null; 2739 mSharedSystemSharedLibraryPackageName = null; 2740 } 2741 2742 mInstallerService = new PackageInstallerService(context, this); 2743 2744 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2745 if (ephemeralResolverComponent != null) { 2746 if (DEBUG_EPHEMERAL) { 2747 Slog.i(TAG, "Ephemeral resolver: " + ephemeralResolverComponent); 2748 } 2749 mEphemeralResolverConnection = 2750 new EphemeralResolverConnection(mContext, ephemeralResolverComponent); 2751 } else { 2752 mEphemeralResolverConnection = null; 2753 } 2754 mEphemeralInstallerComponent = getEphemeralInstallerLPr(); 2755 if (mEphemeralInstallerComponent != null) { 2756 if (DEBUG_EPHEMERAL) { 2757 Slog.i(TAG, "Ephemeral installer: " + mEphemeralInstallerComponent); 2758 } 2759 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2760 } 2761 2762 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2763 } // synchronized (mPackages) 2764 } // synchronized (mInstallLock) 2765 2766 // Now after opening every single application zip, make sure they 2767 // are all flushed. Not really needed, but keeps things nice and 2768 // tidy. 2769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 2770 Runtime.getRuntime().gc(); 2771 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2772 2773 // The initial scanning above does many calls into installd while 2774 // holding the mPackages lock, but we're mostly interested in yelling 2775 // once we have a booted system. 2776 mInstaller.setWarnIfHeld(mPackages); 2777 2778 // Expose private service for system components to use. 2779 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2780 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2781 } 2782 2783 @Override 2784 public boolean isFirstBoot() { 2785 return mFirstBoot; 2786 } 2787 2788 @Override 2789 public boolean isOnlyCoreApps() { 2790 return mOnlyCore; 2791 } 2792 2793 @Override 2794 public boolean isUpgrade() { 2795 return mIsUpgrade; 2796 } 2797 2798 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2799 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2800 2801 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2802 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2803 UserHandle.USER_SYSTEM); 2804 if (matches.size() == 1) { 2805 return matches.get(0).getComponentInfo().packageName; 2806 } else if (matches.size() == 0) { 2807 Log.e(TAG, "There should probably be a verifier, but, none were found"); 2808 return null; 2809 } 2810 throw new RuntimeException("There must be exactly one verifier; found " + matches); 2811 } 2812 2813 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2814 synchronized (mPackages) { 2815 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2816 if (libraryEntry == null) { 2817 throw new IllegalStateException("Missing required shared library:" + libraryName); 2818 } 2819 return libraryEntry.apk; 2820 } 2821 } 2822 2823 private @NonNull String getRequiredInstallerLPr() { 2824 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2825 intent.addCategory(Intent.CATEGORY_DEFAULT); 2826 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2827 2828 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2829 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2830 UserHandle.USER_SYSTEM); 2831 if (matches.size() == 1) { 2832 ResolveInfo resolveInfo = matches.get(0); 2833 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2834 throw new RuntimeException("The installer must be a privileged app"); 2835 } 2836 return matches.get(0).getComponentInfo().packageName; 2837 } else { 2838 throw new RuntimeException("There must be exactly one installer; found " + matches); 2839 } 2840 } 2841 2842 private @NonNull String getRequiredUninstallerLPr() { 2843 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2844 intent.addCategory(Intent.CATEGORY_DEFAULT); 2845 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2846 2847 final ResolveInfo resolveInfo = resolveIntent(intent, null, 2848 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2849 UserHandle.USER_SYSTEM); 2850 if (resolveInfo == null || 2851 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2852 throw new RuntimeException("There must be exactly one uninstaller; found " 2853 + resolveInfo); 2854 } 2855 return resolveInfo.getComponentInfo().packageName; 2856 } 2857 2858 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2859 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2860 2861 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2862 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2863 UserHandle.USER_SYSTEM); 2864 ResolveInfo best = null; 2865 final int N = matches.size(); 2866 for (int i = 0; i < N; i++) { 2867 final ResolveInfo cur = matches.get(i); 2868 final String packageName = cur.getComponentInfo().packageName; 2869 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2870 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2871 continue; 2872 } 2873 2874 if (best == null || cur.priority > best.priority) { 2875 best = cur; 2876 } 2877 } 2878 2879 if (best != null) { 2880 return best.getComponentInfo().getComponentName(); 2881 } else { 2882 throw new RuntimeException("There must be at least one intent filter verifier"); 2883 } 2884 } 2885 2886 private @Nullable ComponentName getEphemeralResolverLPr() { 2887 final String[] packageArray = 2888 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2889 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2890 if (DEBUG_EPHEMERAL) { 2891 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2892 } 2893 return null; 2894 } 2895 2896 final int resolveFlags = 2897 MATCH_DIRECT_BOOT_AWARE 2898 | MATCH_DIRECT_BOOT_UNAWARE 2899 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2900 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2901 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2902 resolveFlags, UserHandle.USER_SYSTEM); 2903 2904 final int N = resolvers.size(); 2905 if (N == 0) { 2906 if (DEBUG_EPHEMERAL) { 2907 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2908 } 2909 return null; 2910 } 2911 2912 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2913 for (int i = 0; i < N; i++) { 2914 final ResolveInfo info = resolvers.get(i); 2915 2916 if (info.serviceInfo == null) { 2917 continue; 2918 } 2919 2920 final String packageName = info.serviceInfo.packageName; 2921 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2922 if (DEBUG_EPHEMERAL) { 2923 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2924 + " pkg: " + packageName + ", info:" + info); 2925 } 2926 continue; 2927 } 2928 2929 if (DEBUG_EPHEMERAL) { 2930 Slog.v(TAG, "Ephemeral resolver found;" 2931 + " pkg: " + packageName + ", info:" + info); 2932 } 2933 return new ComponentName(packageName, info.serviceInfo.name); 2934 } 2935 if (DEBUG_EPHEMERAL) { 2936 Slog.v(TAG, "Ephemeral resolver NOT found"); 2937 } 2938 return null; 2939 } 2940 2941 private @Nullable ComponentName getEphemeralInstallerLPr() { 2942 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2943 intent.addCategory(Intent.CATEGORY_DEFAULT); 2944 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2945 2946 final int resolveFlags = 2947 MATCH_DIRECT_BOOT_AWARE 2948 | MATCH_DIRECT_BOOT_UNAWARE 2949 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2950 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2951 resolveFlags, UserHandle.USER_SYSTEM); 2952 Iterator<ResolveInfo> iter = matches.iterator(); 2953 while (iter.hasNext()) { 2954 final ResolveInfo rInfo = iter.next(); 2955 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 2956 if (ps != null) { 2957 final PermissionsState permissionsState = ps.getPermissionsState(); 2958 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 2959 continue; 2960 } 2961 } 2962 iter.remove(); 2963 } 2964 if (matches.size() == 0) { 2965 return null; 2966 } else if (matches.size() == 1) { 2967 return matches.get(0).getComponentInfo().getComponentName(); 2968 } else { 2969 throw new RuntimeException( 2970 "There must be at most one ephemeral installer; found " + matches); 2971 } 2972 } 2973 2974 private void primeDomainVerificationsLPw(int userId) { 2975 if (DEBUG_DOMAIN_VERIFICATION) { 2976 Slog.d(TAG, "Priming domain verifications in user " + userId); 2977 } 2978 2979 SystemConfig systemConfig = SystemConfig.getInstance(); 2980 ArraySet<String> packages = systemConfig.getLinkedApps(); 2981 2982 for (String packageName : packages) { 2983 PackageParser.Package pkg = mPackages.get(packageName); 2984 if (pkg != null) { 2985 if (!pkg.isSystemApp()) { 2986 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2987 continue; 2988 } 2989 2990 ArraySet<String> domains = null; 2991 for (PackageParser.Activity a : pkg.activities) { 2992 for (ActivityIntentInfo filter : a.intents) { 2993 if (hasValidDomains(filter)) { 2994 if (domains == null) { 2995 domains = new ArraySet<String>(); 2996 } 2997 domains.addAll(filter.getHostsList()); 2998 } 2999 } 3000 } 3001 3002 if (domains != null && domains.size() > 0) { 3003 if (DEBUG_DOMAIN_VERIFICATION) { 3004 Slog.v(TAG, " + " + packageName); 3005 } 3006 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3007 // state w.r.t. the formal app-linkage "no verification attempted" state; 3008 // and then 'always' in the per-user state actually used for intent resolution. 3009 final IntentFilterVerificationInfo ivi; 3010 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3011 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3012 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3013 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3014 } else { 3015 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3016 + "' does not handle web links"); 3017 } 3018 } else { 3019 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3020 } 3021 } 3022 3023 scheduleWritePackageRestrictionsLocked(userId); 3024 scheduleWriteSettingsLocked(); 3025 } 3026 3027 private void applyFactoryDefaultBrowserLPw(int userId) { 3028 // The default browser app's package name is stored in a string resource, 3029 // with a product-specific overlay used for vendor customization. 3030 String browserPkg = mContext.getResources().getString( 3031 com.android.internal.R.string.default_browser); 3032 if (!TextUtils.isEmpty(browserPkg)) { 3033 // non-empty string => required to be a known package 3034 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3035 if (ps == null) { 3036 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3037 browserPkg = null; 3038 } else { 3039 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3040 } 3041 } 3042 3043 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3044 // default. If there's more than one, just leave everything alone. 3045 if (browserPkg == null) { 3046 calculateDefaultBrowserLPw(userId); 3047 } 3048 } 3049 3050 private void calculateDefaultBrowserLPw(int userId) { 3051 List<String> allBrowsers = resolveAllBrowserApps(userId); 3052 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3053 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3054 } 3055 3056 private List<String> resolveAllBrowserApps(int userId) { 3057 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3058 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3059 PackageManager.MATCH_ALL, userId); 3060 3061 final int count = list.size(); 3062 List<String> result = new ArrayList<String>(count); 3063 for (int i=0; i<count; i++) { 3064 ResolveInfo info = list.get(i); 3065 if (info.activityInfo == null 3066 || !info.handleAllWebDataURI 3067 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3068 || result.contains(info.activityInfo.packageName)) { 3069 continue; 3070 } 3071 result.add(info.activityInfo.packageName); 3072 } 3073 3074 return result; 3075 } 3076 3077 private boolean packageIsBrowser(String packageName, int userId) { 3078 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3079 PackageManager.MATCH_ALL, userId); 3080 final int N = list.size(); 3081 for (int i = 0; i < N; i++) { 3082 ResolveInfo info = list.get(i); 3083 if (packageName.equals(info.activityInfo.packageName)) { 3084 return true; 3085 } 3086 } 3087 return false; 3088 } 3089 3090 private void checkDefaultBrowser() { 3091 final int myUserId = UserHandle.myUserId(); 3092 final String packageName = getDefaultBrowserPackageName(myUserId); 3093 if (packageName != null) { 3094 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3095 if (info == null) { 3096 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3097 synchronized (mPackages) { 3098 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3099 } 3100 } 3101 } 3102 } 3103 3104 @Override 3105 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3106 throws RemoteException { 3107 try { 3108 return super.onTransact(code, data, reply, flags); 3109 } catch (RuntimeException e) { 3110 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3111 Slog.wtf(TAG, "Package Manager Crash", e); 3112 } 3113 throw e; 3114 } 3115 } 3116 3117 static int[] appendInts(int[] cur, int[] add) { 3118 if (add == null) return cur; 3119 if (cur == null) return add; 3120 final int N = add.length; 3121 for (int i=0; i<N; i++) { 3122 cur = appendInt(cur, add[i]); 3123 } 3124 return cur; 3125 } 3126 3127 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3128 if (!sUserManager.exists(userId)) return null; 3129 if (ps == null) { 3130 return null; 3131 } 3132 final PackageParser.Package p = ps.pkg; 3133 if (p == null) { 3134 return null; 3135 } 3136 3137 final PermissionsState permissionsState = ps.getPermissionsState(); 3138 3139 // Compute GIDs only if requested 3140 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3141 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3142 // Compute granted permissions only if package has requested permissions 3143 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3144 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3145 final PackageUserState state = ps.readUserState(userId); 3146 3147 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3148 && ps.isSystem()) { 3149 flags |= MATCH_ANY_USER; 3150 } 3151 3152 return PackageParser.generatePackageInfo(p, gids, flags, 3153 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3154 } 3155 3156 @Override 3157 public void checkPackageStartable(String packageName, int userId) { 3158 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3159 3160 synchronized (mPackages) { 3161 final PackageSetting ps = mSettings.mPackages.get(packageName); 3162 if (ps == null) { 3163 throw new SecurityException("Package " + packageName + " was not found!"); 3164 } 3165 3166 if (!ps.getInstalled(userId)) { 3167 throw new SecurityException( 3168 "Package " + packageName + " was not installed for user " + userId + "!"); 3169 } 3170 3171 if (mSafeMode && !ps.isSystem()) { 3172 throw new SecurityException("Package " + packageName + " not a system app!"); 3173 } 3174 3175 if (mFrozenPackages.contains(packageName)) { 3176 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3177 } 3178 3179 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3180 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3181 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3182 } 3183 } 3184 } 3185 3186 @Override 3187 public boolean isPackageAvailable(String packageName, int userId) { 3188 if (!sUserManager.exists(userId)) return false; 3189 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3190 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3191 synchronized (mPackages) { 3192 PackageParser.Package p = mPackages.get(packageName); 3193 if (p != null) { 3194 final PackageSetting ps = (PackageSetting) p.mExtras; 3195 if (ps != null) { 3196 final PackageUserState state = ps.readUserState(userId); 3197 if (state != null) { 3198 return PackageParser.isAvailable(state); 3199 } 3200 } 3201 } 3202 } 3203 return false; 3204 } 3205 3206 @Override 3207 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3208 if (!sUserManager.exists(userId)) return null; 3209 flags = updateFlagsForPackage(flags, userId, packageName); 3210 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3211 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3212 // reader 3213 synchronized (mPackages) { 3214 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3215 PackageParser.Package p = null; 3216 if (matchFactoryOnly) { 3217 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3218 if (ps != null) { 3219 return generatePackageInfo(ps, flags, userId); 3220 } 3221 } 3222 if (p == null) { 3223 p = mPackages.get(packageName); 3224 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3225 return null; 3226 } 3227 } 3228 if (DEBUG_PACKAGE_INFO) 3229 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3230 if (p != null) { 3231 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3232 } 3233 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3234 final PackageSetting ps = mSettings.mPackages.get(packageName); 3235 return generatePackageInfo(ps, flags, userId); 3236 } 3237 } 3238 return null; 3239 } 3240 3241 @Override 3242 public String[] currentToCanonicalPackageNames(String[] names) { 3243 String[] out = new String[names.length]; 3244 // reader 3245 synchronized (mPackages) { 3246 for (int i=names.length-1; i>=0; i--) { 3247 PackageSetting ps = mSettings.mPackages.get(names[i]); 3248 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3249 } 3250 } 3251 return out; 3252 } 3253 3254 @Override 3255 public String[] canonicalToCurrentPackageNames(String[] names) { 3256 String[] out = new String[names.length]; 3257 // reader 3258 synchronized (mPackages) { 3259 for (int i=names.length-1; i>=0; i--) { 3260 String cur = mSettings.getRenamedPackageLPr(names[i]); 3261 out[i] = cur != null ? cur : names[i]; 3262 } 3263 } 3264 return out; 3265 } 3266 3267 @Override 3268 public int getPackageUid(String packageName, int flags, int userId) { 3269 if (!sUserManager.exists(userId)) return -1; 3270 flags = updateFlagsForPackage(flags, userId, packageName); 3271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3272 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3273 3274 // reader 3275 synchronized (mPackages) { 3276 final PackageParser.Package p = mPackages.get(packageName); 3277 if (p != null && p.isMatch(flags)) { 3278 return UserHandle.getUid(userId, p.applicationInfo.uid); 3279 } 3280 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3281 final PackageSetting ps = mSettings.mPackages.get(packageName); 3282 if (ps != null && ps.isMatch(flags)) { 3283 return UserHandle.getUid(userId, ps.appId); 3284 } 3285 } 3286 } 3287 3288 return -1; 3289 } 3290 3291 @Override 3292 public int[] getPackageGids(String packageName, int flags, int userId) { 3293 if (!sUserManager.exists(userId)) return null; 3294 flags = updateFlagsForPackage(flags, userId, packageName); 3295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3296 false /* requireFullPermission */, false /* checkShell */, 3297 "getPackageGids"); 3298 3299 // reader 3300 synchronized (mPackages) { 3301 final PackageParser.Package p = mPackages.get(packageName); 3302 if (p != null && p.isMatch(flags)) { 3303 PackageSetting ps = (PackageSetting) p.mExtras; 3304 // TODO: Shouldn't this be checking for package installed state for userId and 3305 // return null? 3306 return ps.getPermissionsState().computeGids(userId); 3307 } 3308 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3309 final PackageSetting ps = mSettings.mPackages.get(packageName); 3310 if (ps != null && ps.isMatch(flags)) { 3311 return ps.getPermissionsState().computeGids(userId); 3312 } 3313 } 3314 } 3315 3316 return null; 3317 } 3318 3319 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3320 if (bp.perm != null) { 3321 return PackageParser.generatePermissionInfo(bp.perm, flags); 3322 } 3323 PermissionInfo pi = new PermissionInfo(); 3324 pi.name = bp.name; 3325 pi.packageName = bp.sourcePackage; 3326 pi.nonLocalizedLabel = bp.name; 3327 pi.protectionLevel = bp.protectionLevel; 3328 return pi; 3329 } 3330 3331 @Override 3332 public PermissionInfo getPermissionInfo(String name, int flags) { 3333 // reader 3334 synchronized (mPackages) { 3335 final BasePermission p = mSettings.mPermissions.get(name); 3336 if (p != null) { 3337 return generatePermissionInfo(p, flags); 3338 } 3339 return null; 3340 } 3341 } 3342 3343 @Override 3344 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3345 int flags) { 3346 // reader 3347 synchronized (mPackages) { 3348 if (group != null && !mPermissionGroups.containsKey(group)) { 3349 // This is thrown as NameNotFoundException 3350 return null; 3351 } 3352 3353 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3354 for (BasePermission p : mSettings.mPermissions.values()) { 3355 if (group == null) { 3356 if (p.perm == null || p.perm.info.group == null) { 3357 out.add(generatePermissionInfo(p, flags)); 3358 } 3359 } else { 3360 if (p.perm != null && group.equals(p.perm.info.group)) { 3361 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3362 } 3363 } 3364 } 3365 return new ParceledListSlice<>(out); 3366 } 3367 } 3368 3369 @Override 3370 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3371 // reader 3372 synchronized (mPackages) { 3373 return PackageParser.generatePermissionGroupInfo( 3374 mPermissionGroups.get(name), flags); 3375 } 3376 } 3377 3378 @Override 3379 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3380 // reader 3381 synchronized (mPackages) { 3382 final int N = mPermissionGroups.size(); 3383 ArrayList<PermissionGroupInfo> out 3384 = new ArrayList<PermissionGroupInfo>(N); 3385 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3386 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3387 } 3388 return new ParceledListSlice<>(out); 3389 } 3390 } 3391 3392 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3393 int userId) { 3394 if (!sUserManager.exists(userId)) return null; 3395 PackageSetting ps = mSettings.mPackages.get(packageName); 3396 if (ps != null) { 3397 if (ps.pkg == null) { 3398 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3399 if (pInfo != null) { 3400 return pInfo.applicationInfo; 3401 } 3402 return null; 3403 } 3404 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3405 ps.readUserState(userId), userId); 3406 } 3407 return null; 3408 } 3409 3410 @Override 3411 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3412 if (!sUserManager.exists(userId)) return null; 3413 flags = updateFlagsForApplication(flags, userId, packageName); 3414 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3415 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3416 // writer 3417 synchronized (mPackages) { 3418 PackageParser.Package p = mPackages.get(packageName); 3419 if (DEBUG_PACKAGE_INFO) Log.v( 3420 TAG, "getApplicationInfo " + packageName 3421 + ": " + p); 3422 if (p != null) { 3423 PackageSetting ps = mSettings.mPackages.get(packageName); 3424 if (ps == null) return null; 3425 // Note: isEnabledLP() does not apply here - always return info 3426 return PackageParser.generateApplicationInfo( 3427 p, flags, ps.readUserState(userId), userId); 3428 } 3429 if ("android".equals(packageName)||"system".equals(packageName)) { 3430 return mAndroidApplication; 3431 } 3432 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 3433 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3434 } 3435 } 3436 return null; 3437 } 3438 3439 @Override 3440 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3441 final IPackageDataObserver observer) { 3442 mContext.enforceCallingOrSelfPermission( 3443 android.Manifest.permission.CLEAR_APP_CACHE, null); 3444 // Queue up an async operation since clearing cache may take a little while. 3445 mHandler.post(new Runnable() { 3446 public void run() { 3447 mHandler.removeCallbacks(this); 3448 boolean success = true; 3449 synchronized (mInstallLock) { 3450 try { 3451 mInstaller.freeCache(volumeUuid, freeStorageSize); 3452 } catch (InstallerException e) { 3453 Slog.w(TAG, "Couldn't clear application caches: " + e); 3454 success = false; 3455 } 3456 } 3457 if (observer != null) { 3458 try { 3459 observer.onRemoveCompleted(null, success); 3460 } catch (RemoteException e) { 3461 Slog.w(TAG, "RemoveException when invoking call back"); 3462 } 3463 } 3464 } 3465 }); 3466 } 3467 3468 @Override 3469 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3470 final IntentSender pi) { 3471 mContext.enforceCallingOrSelfPermission( 3472 android.Manifest.permission.CLEAR_APP_CACHE, null); 3473 // Queue up an async operation since clearing cache may take a little while. 3474 mHandler.post(new Runnable() { 3475 public void run() { 3476 mHandler.removeCallbacks(this); 3477 boolean success = true; 3478 synchronized (mInstallLock) { 3479 try { 3480 mInstaller.freeCache(volumeUuid, freeStorageSize); 3481 } catch (InstallerException e) { 3482 Slog.w(TAG, "Couldn't clear application caches: " + e); 3483 success = false; 3484 } 3485 } 3486 if(pi != null) { 3487 try { 3488 // Callback via pending intent 3489 int code = success ? 1 : 0; 3490 pi.sendIntent(null, code, null, 3491 null, null); 3492 } catch (SendIntentException e1) { 3493 Slog.i(TAG, "Failed to send pending intent"); 3494 } 3495 } 3496 } 3497 }); 3498 } 3499 3500 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3501 synchronized (mInstallLock) { 3502 try { 3503 mInstaller.freeCache(volumeUuid, freeStorageSize); 3504 } catch (InstallerException e) { 3505 throw new IOException("Failed to free enough space", e); 3506 } 3507 } 3508 } 3509 3510 /** 3511 * Update given flags based on encryption status of current user. 3512 */ 3513 private int updateFlags(int flags, int userId) { 3514 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3515 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3516 // Caller expressed an explicit opinion about what encryption 3517 // aware/unaware components they want to see, so fall through and 3518 // give them what they want 3519 } else { 3520 // Caller expressed no opinion, so match based on user state 3521 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3522 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3523 } else { 3524 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3525 } 3526 } 3527 return flags; 3528 } 3529 3530 private UserManagerInternal getUserManagerInternal() { 3531 if (mUserManagerInternal == null) { 3532 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3533 } 3534 return mUserManagerInternal; 3535 } 3536 3537 /** 3538 * Update given flags when being used to request {@link PackageInfo}. 3539 */ 3540 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3541 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 3542 boolean triaged = true; 3543 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3544 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3545 // Caller is asking for component details, so they'd better be 3546 // asking for specific encryption matching behavior, or be triaged 3547 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3548 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3549 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3550 triaged = false; 3551 } 3552 } 3553 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3554 | PackageManager.MATCH_SYSTEM_ONLY 3555 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3556 triaged = false; 3557 } 3558 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 3559 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 3560 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 3561 + Debug.getCallers(5)); 3562 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 3563 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 3564 // If the caller wants all packages and has a restricted profile associated with it, 3565 // then match all users. This is to make sure that launchers that need to access work 3566 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 3567 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 3568 flags |= PackageManager.MATCH_ANY_USER; 3569 } 3570 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3571 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3572 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3573 } 3574 return updateFlags(flags, userId); 3575 } 3576 3577 /** 3578 * Update given flags when being used to request {@link ApplicationInfo}. 3579 */ 3580 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3581 return updateFlagsForPackage(flags, userId, cookie); 3582 } 3583 3584 /** 3585 * Update given flags when being used to request {@link ComponentInfo}. 3586 */ 3587 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3588 if (cookie instanceof Intent) { 3589 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3590 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3591 } 3592 } 3593 3594 boolean triaged = true; 3595 // Caller is asking for component details, so they'd better be 3596 // asking for specific encryption matching behavior, or be triaged 3597 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3598 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3599 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3600 triaged = false; 3601 } 3602 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3603 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3604 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3605 } 3606 3607 return updateFlags(flags, userId); 3608 } 3609 3610 /** 3611 * Update given flags when being used to request {@link ResolveInfo}. 3612 */ 3613 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3614 // Safe mode means we shouldn't match any third-party components 3615 if (mSafeMode) { 3616 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3617 } 3618 3619 return updateFlagsForComponent(flags, userId, cookie); 3620 } 3621 3622 @Override 3623 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3624 if (!sUserManager.exists(userId)) return null; 3625 flags = updateFlagsForComponent(flags, userId, component); 3626 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3627 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3628 synchronized (mPackages) { 3629 PackageParser.Activity a = mActivities.mActivities.get(component); 3630 3631 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3632 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3633 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3634 if (ps == null) return null; 3635 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3636 userId); 3637 } 3638 if (mResolveComponentName.equals(component)) { 3639 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3640 new PackageUserState(), userId); 3641 } 3642 } 3643 return null; 3644 } 3645 3646 @Override 3647 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3648 String resolvedType) { 3649 synchronized (mPackages) { 3650 if (component.equals(mResolveComponentName)) { 3651 // The resolver supports EVERYTHING! 3652 return true; 3653 } 3654 PackageParser.Activity a = mActivities.mActivities.get(component); 3655 if (a == null) { 3656 return false; 3657 } 3658 for (int i=0; i<a.intents.size(); i++) { 3659 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3660 intent.getData(), intent.getCategories(), TAG) >= 0) { 3661 return true; 3662 } 3663 } 3664 return false; 3665 } 3666 } 3667 3668 @Override 3669 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3670 if (!sUserManager.exists(userId)) return null; 3671 flags = updateFlagsForComponent(flags, userId, component); 3672 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3673 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3674 synchronized (mPackages) { 3675 PackageParser.Activity a = mReceivers.mActivities.get(component); 3676 if (DEBUG_PACKAGE_INFO) Log.v( 3677 TAG, "getReceiverInfo " + component + ": " + a); 3678 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3679 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3680 if (ps == null) return null; 3681 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3682 userId); 3683 } 3684 } 3685 return null; 3686 } 3687 3688 @Override 3689 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3690 if (!sUserManager.exists(userId)) return null; 3691 flags = updateFlagsForComponent(flags, userId, component); 3692 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3693 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3694 synchronized (mPackages) { 3695 PackageParser.Service s = mServices.mServices.get(component); 3696 if (DEBUG_PACKAGE_INFO) Log.v( 3697 TAG, "getServiceInfo " + component + ": " + s); 3698 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3699 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3700 if (ps == null) return null; 3701 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3702 userId); 3703 } 3704 } 3705 return null; 3706 } 3707 3708 @Override 3709 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3710 if (!sUserManager.exists(userId)) return null; 3711 flags = updateFlagsForComponent(flags, userId, component); 3712 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3713 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3714 synchronized (mPackages) { 3715 PackageParser.Provider p = mProviders.mProviders.get(component); 3716 if (DEBUG_PACKAGE_INFO) Log.v( 3717 TAG, "getProviderInfo " + component + ": " + p); 3718 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3719 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3720 if (ps == null) return null; 3721 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3722 userId); 3723 } 3724 } 3725 return null; 3726 } 3727 3728 @Override 3729 public String[] getSystemSharedLibraryNames() { 3730 Set<String> libSet; 3731 synchronized (mPackages) { 3732 libSet = mSharedLibraries.keySet(); 3733 int size = libSet.size(); 3734 if (size > 0) { 3735 String[] libs = new String[size]; 3736 libSet.toArray(libs); 3737 return libs; 3738 } 3739 } 3740 return null; 3741 } 3742 3743 @Override 3744 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3745 synchronized (mPackages) { 3746 return mServicesSystemSharedLibraryPackageName; 3747 } 3748 } 3749 3750 @Override 3751 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3752 synchronized (mPackages) { 3753 return mSharedSystemSharedLibraryPackageName; 3754 } 3755 } 3756 3757 @Override 3758 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3759 synchronized (mPackages) { 3760 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3761 3762 final FeatureInfo fi = new FeatureInfo(); 3763 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3764 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3765 res.add(fi); 3766 3767 return new ParceledListSlice<>(res); 3768 } 3769 } 3770 3771 @Override 3772 public boolean hasSystemFeature(String name, int version) { 3773 synchronized (mPackages) { 3774 final FeatureInfo feat = mAvailableFeatures.get(name); 3775 if (feat == null) { 3776 return false; 3777 } else { 3778 return feat.version >= version; 3779 } 3780 } 3781 } 3782 3783 @Override 3784 public int checkPermission(String permName, String pkgName, int userId) { 3785 if (!sUserManager.exists(userId)) { 3786 return PackageManager.PERMISSION_DENIED; 3787 } 3788 3789 synchronized (mPackages) { 3790 final PackageParser.Package p = mPackages.get(pkgName); 3791 if (p != null && p.mExtras != null) { 3792 final PackageSetting ps = (PackageSetting) p.mExtras; 3793 final PermissionsState permissionsState = ps.getPermissionsState(); 3794 if (permissionsState.hasPermission(permName, userId)) { 3795 return PackageManager.PERMISSION_GRANTED; 3796 } 3797 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3798 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3799 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3800 return PackageManager.PERMISSION_GRANTED; 3801 } 3802 } 3803 } 3804 3805 return PackageManager.PERMISSION_DENIED; 3806 } 3807 3808 @Override 3809 public int checkUidPermission(String permName, int uid) { 3810 final int userId = UserHandle.getUserId(uid); 3811 3812 if (!sUserManager.exists(userId)) { 3813 return PackageManager.PERMISSION_DENIED; 3814 } 3815 3816 synchronized (mPackages) { 3817 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3818 if (obj != null) { 3819 final SettingBase ps = (SettingBase) obj; 3820 final PermissionsState permissionsState = ps.getPermissionsState(); 3821 if (permissionsState.hasPermission(permName, userId)) { 3822 return PackageManager.PERMISSION_GRANTED; 3823 } 3824 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3825 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3826 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3827 return PackageManager.PERMISSION_GRANTED; 3828 } 3829 } else { 3830 ArraySet<String> perms = mSystemPermissions.get(uid); 3831 if (perms != null) { 3832 if (perms.contains(permName)) { 3833 return PackageManager.PERMISSION_GRANTED; 3834 } 3835 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3836 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3837 return PackageManager.PERMISSION_GRANTED; 3838 } 3839 } 3840 } 3841 } 3842 3843 return PackageManager.PERMISSION_DENIED; 3844 } 3845 3846 @Override 3847 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3848 if (UserHandle.getCallingUserId() != userId) { 3849 mContext.enforceCallingPermission( 3850 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3851 "isPermissionRevokedByPolicy for user " + userId); 3852 } 3853 3854 if (checkPermission(permission, packageName, userId) 3855 == PackageManager.PERMISSION_GRANTED) { 3856 return false; 3857 } 3858 3859 final long identity = Binder.clearCallingIdentity(); 3860 try { 3861 final int flags = getPermissionFlags(permission, packageName, userId); 3862 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3863 } finally { 3864 Binder.restoreCallingIdentity(identity); 3865 } 3866 } 3867 3868 @Override 3869 public String getPermissionControllerPackageName() { 3870 synchronized (mPackages) { 3871 return mRequiredInstallerPackage; 3872 } 3873 } 3874 3875 /** 3876 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3877 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3878 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3879 * @param message the message to log on security exception 3880 */ 3881 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3882 boolean checkShell, String message) { 3883 if (userId < 0) { 3884 throw new IllegalArgumentException("Invalid userId " + userId); 3885 } 3886 if (checkShell) { 3887 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3888 } 3889 if (userId == UserHandle.getUserId(callingUid)) return; 3890 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3891 if (requireFullPermission) { 3892 mContext.enforceCallingOrSelfPermission( 3893 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3894 } else { 3895 try { 3896 mContext.enforceCallingOrSelfPermission( 3897 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3898 } catch (SecurityException se) { 3899 mContext.enforceCallingOrSelfPermission( 3900 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3901 } 3902 } 3903 } 3904 } 3905 3906 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3907 if (callingUid == Process.SHELL_UID) { 3908 if (userHandle >= 0 3909 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3910 throw new SecurityException("Shell does not have permission to access user " 3911 + userHandle); 3912 } else if (userHandle < 0) { 3913 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3914 + Debug.getCallers(3)); 3915 } 3916 } 3917 } 3918 3919 private BasePermission findPermissionTreeLP(String permName) { 3920 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3921 if (permName.startsWith(bp.name) && 3922 permName.length() > bp.name.length() && 3923 permName.charAt(bp.name.length()) == '.') { 3924 return bp; 3925 } 3926 } 3927 return null; 3928 } 3929 3930 private BasePermission checkPermissionTreeLP(String permName) { 3931 if (permName != null) { 3932 BasePermission bp = findPermissionTreeLP(permName); 3933 if (bp != null) { 3934 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3935 return bp; 3936 } 3937 throw new SecurityException("Calling uid " 3938 + Binder.getCallingUid() 3939 + " is not allowed to add to permission tree " 3940 + bp.name + " owned by uid " + bp.uid); 3941 } 3942 } 3943 throw new SecurityException("No permission tree found for " + permName); 3944 } 3945 3946 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3947 if (s1 == null) { 3948 return s2 == null; 3949 } 3950 if (s2 == null) { 3951 return false; 3952 } 3953 if (s1.getClass() != s2.getClass()) { 3954 return false; 3955 } 3956 return s1.equals(s2); 3957 } 3958 3959 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3960 if (pi1.icon != pi2.icon) return false; 3961 if (pi1.logo != pi2.logo) return false; 3962 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3963 if (!compareStrings(pi1.name, pi2.name)) return false; 3964 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3965 // We'll take care of setting this one. 3966 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3967 // These are not currently stored in settings. 3968 //if (!compareStrings(pi1.group, pi2.group)) return false; 3969 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3970 //if (pi1.labelRes != pi2.labelRes) return false; 3971 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3972 return true; 3973 } 3974 3975 int permissionInfoFootprint(PermissionInfo info) { 3976 int size = info.name.length(); 3977 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3978 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3979 return size; 3980 } 3981 3982 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3983 int size = 0; 3984 for (BasePermission perm : mSettings.mPermissions.values()) { 3985 if (perm.uid == tree.uid) { 3986 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3987 } 3988 } 3989 return size; 3990 } 3991 3992 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3993 // We calculate the max size of permissions defined by this uid and throw 3994 // if that plus the size of 'info' would exceed our stated maximum. 3995 if (tree.uid != Process.SYSTEM_UID) { 3996 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3997 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3998 throw new SecurityException("Permission tree size cap exceeded"); 3999 } 4000 } 4001 } 4002 4003 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4004 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4005 throw new SecurityException("Label must be specified in permission"); 4006 } 4007 BasePermission tree = checkPermissionTreeLP(info.name); 4008 BasePermission bp = mSettings.mPermissions.get(info.name); 4009 boolean added = bp == null; 4010 boolean changed = true; 4011 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4012 if (added) { 4013 enforcePermissionCapLocked(info, tree); 4014 bp = new BasePermission(info.name, tree.sourcePackage, 4015 BasePermission.TYPE_DYNAMIC); 4016 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4017 throw new SecurityException( 4018 "Not allowed to modify non-dynamic permission " 4019 + info.name); 4020 } else { 4021 if (bp.protectionLevel == fixedLevel 4022 && bp.perm.owner.equals(tree.perm.owner) 4023 && bp.uid == tree.uid 4024 && comparePermissionInfos(bp.perm.info, info)) { 4025 changed = false; 4026 } 4027 } 4028 bp.protectionLevel = fixedLevel; 4029 info = new PermissionInfo(info); 4030 info.protectionLevel = fixedLevel; 4031 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4032 bp.perm.info.packageName = tree.perm.info.packageName; 4033 bp.uid = tree.uid; 4034 if (added) { 4035 mSettings.mPermissions.put(info.name, bp); 4036 } 4037 if (changed) { 4038 if (!async) { 4039 mSettings.writeLPr(); 4040 } else { 4041 scheduleWriteSettingsLocked(); 4042 } 4043 } 4044 return added; 4045 } 4046 4047 @Override 4048 public boolean addPermission(PermissionInfo info) { 4049 synchronized (mPackages) { 4050 return addPermissionLocked(info, false); 4051 } 4052 } 4053 4054 @Override 4055 public boolean addPermissionAsync(PermissionInfo info) { 4056 synchronized (mPackages) { 4057 return addPermissionLocked(info, true); 4058 } 4059 } 4060 4061 @Override 4062 public void removePermission(String name) { 4063 synchronized (mPackages) { 4064 checkPermissionTreeLP(name); 4065 BasePermission bp = mSettings.mPermissions.get(name); 4066 if (bp != null) { 4067 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4068 throw new SecurityException( 4069 "Not allowed to modify non-dynamic permission " 4070 + name); 4071 } 4072 mSettings.mPermissions.remove(name); 4073 mSettings.writeLPr(); 4074 } 4075 } 4076 } 4077 4078 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4079 BasePermission bp) { 4080 int index = pkg.requestedPermissions.indexOf(bp.name); 4081 if (index == -1) { 4082 throw new SecurityException("Package " + pkg.packageName 4083 + " has not requested permission " + bp.name); 4084 } 4085 if (!bp.isRuntime() && !bp.isDevelopment()) { 4086 throw new SecurityException("Permission " + bp.name 4087 + " is not a changeable permission type"); 4088 } 4089 } 4090 4091 @Override 4092 public void grantRuntimePermission(String packageName, String name, final int userId) { 4093 grantRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4094 } 4095 4096 private void grantRuntimePermission(String packageName, String name, final int userId, 4097 boolean overridePolicy) { 4098 if (!sUserManager.exists(userId)) { 4099 Log.e(TAG, "No such user:" + userId); 4100 return; 4101 } 4102 4103 mContext.enforceCallingOrSelfPermission( 4104 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4105 "grantRuntimePermission"); 4106 4107 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4108 true /* requireFullPermission */, true /* checkShell */, 4109 "grantRuntimePermission"); 4110 4111 final int uid; 4112 final SettingBase sb; 4113 4114 synchronized (mPackages) { 4115 final PackageParser.Package pkg = mPackages.get(packageName); 4116 if (pkg == null) { 4117 throw new IllegalArgumentException("Unknown package: " + packageName); 4118 } 4119 4120 final BasePermission bp = mSettings.mPermissions.get(name); 4121 if (bp == null) { 4122 throw new IllegalArgumentException("Unknown permission: " + name); 4123 } 4124 4125 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4126 4127 // If a permission review is required for legacy apps we represent 4128 // their permissions as always granted runtime ones since we need 4129 // to keep the review required permission flag per user while an 4130 // install permission's state is shared across all users. 4131 if (mPermissionReviewRequired 4132 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4133 && bp.isRuntime()) { 4134 return; 4135 } 4136 4137 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4138 sb = (SettingBase) pkg.mExtras; 4139 if (sb == null) { 4140 throw new IllegalArgumentException("Unknown package: " + packageName); 4141 } 4142 4143 final PermissionsState permissionsState = sb.getPermissionsState(); 4144 4145 final int flags = permissionsState.getPermissionFlags(name, userId); 4146 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4147 throw new SecurityException("Cannot grant system fixed permission " 4148 + name + " for package " + packageName); 4149 } 4150 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4151 throw new SecurityException("Cannot grant policy fixed permission " 4152 + name + " for package " + packageName); 4153 } 4154 4155 if (bp.isDevelopment()) { 4156 // Development permissions must be handled specially, since they are not 4157 // normal runtime permissions. For now they apply to all users. 4158 if (permissionsState.grantInstallPermission(bp) != 4159 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4160 scheduleWriteSettingsLocked(); 4161 } 4162 return; 4163 } 4164 4165 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 4166 throw new SecurityException("Cannot grant non-ephemeral permission" 4167 + name + " for package " + packageName); 4168 } 4169 4170 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4171 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4172 return; 4173 } 4174 4175 final int result = permissionsState.grantRuntimePermission(bp, userId); 4176 switch (result) { 4177 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4178 return; 4179 } 4180 4181 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4182 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4183 mHandler.post(new Runnable() { 4184 @Override 4185 public void run() { 4186 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4187 } 4188 }); 4189 } 4190 break; 4191 } 4192 4193 if (bp.isRuntime()) { 4194 logPermissionGranted(mContext, name, packageName); 4195 } 4196 4197 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4198 4199 // Not critical if that is lost - app has to request again. 4200 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4201 } 4202 4203 // Only need to do this if user is initialized. Otherwise it's a new user 4204 // and there are no processes running as the user yet and there's no need 4205 // to make an expensive call to remount processes for the changed permissions. 4206 if (READ_EXTERNAL_STORAGE.equals(name) 4207 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4208 final long token = Binder.clearCallingIdentity(); 4209 try { 4210 if (sUserManager.isInitialized(userId)) { 4211 StorageManagerInternal storageManagerInternal = LocalServices.getService( 4212 StorageManagerInternal.class); 4213 storageManagerInternal.onExternalStoragePolicyChanged(uid, packageName); 4214 } 4215 } finally { 4216 Binder.restoreCallingIdentity(token); 4217 } 4218 } 4219 } 4220 4221 @Override 4222 public void revokeRuntimePermission(String packageName, String name, int userId) { 4223 revokeRuntimePermission(packageName, name, userId, false /* Only if not fixed by policy */); 4224 } 4225 4226 private void revokeRuntimePermission(String packageName, String name, int userId, 4227 boolean overridePolicy) { 4228 if (!sUserManager.exists(userId)) { 4229 Log.e(TAG, "No such user:" + userId); 4230 return; 4231 } 4232 4233 mContext.enforceCallingOrSelfPermission( 4234 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4235 "revokeRuntimePermission"); 4236 4237 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4238 true /* requireFullPermission */, true /* checkShell */, 4239 "revokeRuntimePermission"); 4240 4241 final int appId; 4242 4243 synchronized (mPackages) { 4244 final PackageParser.Package pkg = mPackages.get(packageName); 4245 if (pkg == null) { 4246 throw new IllegalArgumentException("Unknown package: " + packageName); 4247 } 4248 4249 final BasePermission bp = mSettings.mPermissions.get(name); 4250 if (bp == null) { 4251 throw new IllegalArgumentException("Unknown permission: " + name); 4252 } 4253 4254 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4255 4256 // If a permission review is required for legacy apps we represent 4257 // their permissions as always granted runtime ones since we need 4258 // to keep the review required permission flag per user while an 4259 // install permission's state is shared across all users. 4260 if (mPermissionReviewRequired 4261 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4262 && bp.isRuntime()) { 4263 return; 4264 } 4265 4266 SettingBase sb = (SettingBase) pkg.mExtras; 4267 if (sb == null) { 4268 throw new IllegalArgumentException("Unknown package: " + packageName); 4269 } 4270 4271 final PermissionsState permissionsState = sb.getPermissionsState(); 4272 4273 final int flags = permissionsState.getPermissionFlags(name, userId); 4274 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4275 throw new SecurityException("Cannot revoke system fixed permission " 4276 + name + " for package " + packageName); 4277 } 4278 if (!overridePolicy && (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0) { 4279 throw new SecurityException("Cannot revoke policy fixed permission " 4280 + name + " for package " + packageName); 4281 } 4282 4283 if (bp.isDevelopment()) { 4284 // Development permissions must be handled specially, since they are not 4285 // normal runtime permissions. For now they apply to all users. 4286 if (permissionsState.revokeInstallPermission(bp) != 4287 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4288 scheduleWriteSettingsLocked(); 4289 } 4290 return; 4291 } 4292 4293 if (permissionsState.revokeRuntimePermission(bp, userId) == 4294 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4295 return; 4296 } 4297 4298 if (bp.isRuntime()) { 4299 logPermissionRevoked(mContext, name, packageName); 4300 } 4301 4302 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4303 4304 // Critical, after this call app should never have the permission. 4305 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4306 4307 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4308 } 4309 4310 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4311 } 4312 4313 /** 4314 * Get the first event id for the permission. 4315 * 4316 * <p>There are four events for each permission: <ul> 4317 * <li>Request permission: first id + 0</li> 4318 * <li>Grant permission: first id + 1</li> 4319 * <li>Request for permission denied: first id + 2</li> 4320 * <li>Revoke permission: first id + 3</li> 4321 * </ul></p> 4322 * 4323 * @param name name of the permission 4324 * 4325 * @return The first event id for the permission 4326 */ 4327 private static int getBaseEventId(@NonNull String name) { 4328 int eventIdIndex = ALL_DANGEROUS_PERMISSIONS.indexOf(name); 4329 4330 if (eventIdIndex == -1) { 4331 if (AppOpsManager.permissionToOpCode(name) == AppOpsManager.OP_NONE 4332 || "user".equals(Build.TYPE)) { 4333 Log.i(TAG, "Unknown permission " + name); 4334 4335 return MetricsEvent.ACTION_PERMISSION_REQUEST_UNKNOWN; 4336 } else { 4337 // Most likely #ALL_DANGEROUS_PERMISSIONS needs to be updated. 4338 // 4339 // Also update 4340 // - EventLogger#ALL_DANGEROUS_PERMISSIONS 4341 // - metrics_constants.proto 4342 throw new IllegalStateException("Unknown permission " + name); 4343 } 4344 } 4345 4346 return MetricsEvent.ACTION_PERMISSION_REQUEST_READ_CALENDAR + eventIdIndex * 4; 4347 } 4348 4349 /** 4350 * Log that a permission was revoked. 4351 * 4352 * @param context Context of the caller 4353 * @param name name of the permission 4354 * @param packageName package permission if for 4355 */ 4356 private static void logPermissionRevoked(@NonNull Context context, @NonNull String name, 4357 @NonNull String packageName) { 4358 MetricsLogger.action(context, getBaseEventId(name) + 3, packageName); 4359 } 4360 4361 /** 4362 * Log that a permission request was granted. 4363 * 4364 * @param context Context of the caller 4365 * @param name name of the permission 4366 * @param packageName package permission if for 4367 */ 4368 private static void logPermissionGranted(@NonNull Context context, @NonNull String name, 4369 @NonNull String packageName) { 4370 MetricsLogger.action(context, getBaseEventId(name) + 1, packageName); 4371 } 4372 4373 @Override 4374 public void resetRuntimePermissions() { 4375 mContext.enforceCallingOrSelfPermission( 4376 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4377 "revokeRuntimePermission"); 4378 4379 int callingUid = Binder.getCallingUid(); 4380 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4381 mContext.enforceCallingOrSelfPermission( 4382 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4383 "resetRuntimePermissions"); 4384 } 4385 4386 synchronized (mPackages) { 4387 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4388 for (int userId : UserManagerService.getInstance().getUserIds()) { 4389 final int packageCount = mPackages.size(); 4390 for (int i = 0; i < packageCount; i++) { 4391 PackageParser.Package pkg = mPackages.valueAt(i); 4392 if (!(pkg.mExtras instanceof PackageSetting)) { 4393 continue; 4394 } 4395 PackageSetting ps = (PackageSetting) pkg.mExtras; 4396 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4397 } 4398 } 4399 } 4400 } 4401 4402 @Override 4403 public int getPermissionFlags(String name, String packageName, int userId) { 4404 if (!sUserManager.exists(userId)) { 4405 return 0; 4406 } 4407 4408 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4409 4410 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4411 true /* requireFullPermission */, false /* checkShell */, 4412 "getPermissionFlags"); 4413 4414 synchronized (mPackages) { 4415 final PackageParser.Package pkg = mPackages.get(packageName); 4416 if (pkg == null) { 4417 return 0; 4418 } 4419 4420 final BasePermission bp = mSettings.mPermissions.get(name); 4421 if (bp == null) { 4422 return 0; 4423 } 4424 4425 SettingBase sb = (SettingBase) pkg.mExtras; 4426 if (sb == null) { 4427 return 0; 4428 } 4429 4430 PermissionsState permissionsState = sb.getPermissionsState(); 4431 return permissionsState.getPermissionFlags(name, userId); 4432 } 4433 } 4434 4435 @Override 4436 public void updatePermissionFlags(String name, String packageName, int flagMask, 4437 int flagValues, int userId) { 4438 if (!sUserManager.exists(userId)) { 4439 return; 4440 } 4441 4442 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4443 4444 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4445 true /* requireFullPermission */, true /* checkShell */, 4446 "updatePermissionFlags"); 4447 4448 // Only the system can change these flags and nothing else. 4449 if (getCallingUid() != Process.SYSTEM_UID) { 4450 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4451 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4452 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4453 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4454 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4455 } 4456 4457 synchronized (mPackages) { 4458 final PackageParser.Package pkg = mPackages.get(packageName); 4459 if (pkg == null) { 4460 throw new IllegalArgumentException("Unknown package: " + packageName); 4461 } 4462 4463 final BasePermission bp = mSettings.mPermissions.get(name); 4464 if (bp == null) { 4465 throw new IllegalArgumentException("Unknown permission: " + name); 4466 } 4467 4468 SettingBase sb = (SettingBase) pkg.mExtras; 4469 if (sb == null) { 4470 throw new IllegalArgumentException("Unknown package: " + packageName); 4471 } 4472 4473 PermissionsState permissionsState = sb.getPermissionsState(); 4474 4475 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4476 4477 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4478 // Install and runtime permissions are stored in different places, 4479 // so figure out what permission changed and persist the change. 4480 if (permissionsState.getInstallPermissionState(name) != null) { 4481 scheduleWriteSettingsLocked(); 4482 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4483 || hadState) { 4484 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4485 } 4486 } 4487 } 4488 } 4489 4490 /** 4491 * Update the permission flags for all packages and runtime permissions of a user in order 4492 * to allow device or profile owner to remove POLICY_FIXED. 4493 */ 4494 @Override 4495 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4496 if (!sUserManager.exists(userId)) { 4497 return; 4498 } 4499 4500 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4501 4502 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4503 true /* requireFullPermission */, true /* checkShell */, 4504 "updatePermissionFlagsForAllApps"); 4505 4506 // Only the system can change system fixed flags. 4507 if (getCallingUid() != Process.SYSTEM_UID) { 4508 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4509 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4510 } 4511 4512 synchronized (mPackages) { 4513 boolean changed = false; 4514 final int packageCount = mPackages.size(); 4515 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4516 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4517 SettingBase sb = (SettingBase) pkg.mExtras; 4518 if (sb == null) { 4519 continue; 4520 } 4521 PermissionsState permissionsState = sb.getPermissionsState(); 4522 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4523 userId, flagMask, flagValues); 4524 } 4525 if (changed) { 4526 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4527 } 4528 } 4529 } 4530 4531 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4532 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4533 != PackageManager.PERMISSION_GRANTED 4534 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4535 != PackageManager.PERMISSION_GRANTED) { 4536 throw new SecurityException(message + " requires " 4537 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4538 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4539 } 4540 } 4541 4542 @Override 4543 public boolean shouldShowRequestPermissionRationale(String permissionName, 4544 String packageName, int userId) { 4545 if (UserHandle.getCallingUserId() != userId) { 4546 mContext.enforceCallingPermission( 4547 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4548 "canShowRequestPermissionRationale for user " + userId); 4549 } 4550 4551 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4552 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4553 return false; 4554 } 4555 4556 if (checkPermission(permissionName, packageName, userId) 4557 == PackageManager.PERMISSION_GRANTED) { 4558 return false; 4559 } 4560 4561 final int flags; 4562 4563 final long identity = Binder.clearCallingIdentity(); 4564 try { 4565 flags = getPermissionFlags(permissionName, 4566 packageName, userId); 4567 } finally { 4568 Binder.restoreCallingIdentity(identity); 4569 } 4570 4571 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4572 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4573 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4574 4575 if ((flags & fixedFlags) != 0) { 4576 return false; 4577 } 4578 4579 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4580 } 4581 4582 @Override 4583 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4584 mContext.enforceCallingOrSelfPermission( 4585 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4586 "addOnPermissionsChangeListener"); 4587 4588 synchronized (mPackages) { 4589 mOnPermissionChangeListeners.addListenerLocked(listener); 4590 } 4591 } 4592 4593 @Override 4594 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4595 synchronized (mPackages) { 4596 mOnPermissionChangeListeners.removeListenerLocked(listener); 4597 } 4598 } 4599 4600 @Override 4601 public boolean isProtectedBroadcast(String actionName) { 4602 synchronized (mPackages) { 4603 if (mProtectedBroadcasts.contains(actionName)) { 4604 return true; 4605 } else if (actionName != null) { 4606 // TODO: remove these terrible hacks 4607 if (actionName.startsWith("android.net.netmon.lingerExpired") 4608 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4609 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4610 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4611 return true; 4612 } 4613 } 4614 } 4615 return false; 4616 } 4617 4618 @Override 4619 public int checkSignatures(String pkg1, String pkg2) { 4620 synchronized (mPackages) { 4621 final PackageParser.Package p1 = mPackages.get(pkg1); 4622 final PackageParser.Package p2 = mPackages.get(pkg2); 4623 if (p1 == null || p1.mExtras == null 4624 || p2 == null || p2.mExtras == null) { 4625 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4626 } 4627 return compareSignatures(p1.mSignatures, p2.mSignatures); 4628 } 4629 } 4630 4631 @Override 4632 public int checkUidSignatures(int uid1, int uid2) { 4633 // Map to base uids. 4634 uid1 = UserHandle.getAppId(uid1); 4635 uid2 = UserHandle.getAppId(uid2); 4636 // reader 4637 synchronized (mPackages) { 4638 Signature[] s1; 4639 Signature[] s2; 4640 Object obj = mSettings.getUserIdLPr(uid1); 4641 if (obj != null) { 4642 if (obj instanceof SharedUserSetting) { 4643 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4644 } else if (obj instanceof PackageSetting) { 4645 s1 = ((PackageSetting)obj).signatures.mSignatures; 4646 } else { 4647 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4648 } 4649 } else { 4650 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4651 } 4652 obj = mSettings.getUserIdLPr(uid2); 4653 if (obj != null) { 4654 if (obj instanceof SharedUserSetting) { 4655 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4656 } else if (obj instanceof PackageSetting) { 4657 s2 = ((PackageSetting)obj).signatures.mSignatures; 4658 } else { 4659 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4660 } 4661 } else { 4662 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4663 } 4664 return compareSignatures(s1, s2); 4665 } 4666 } 4667 4668 /** 4669 * This method should typically only be used when granting or revoking 4670 * permissions, since the app may immediately restart after this call. 4671 * <p> 4672 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4673 * guard your work against the app being relaunched. 4674 */ 4675 private void killUid(int appId, int userId, String reason) { 4676 final long identity = Binder.clearCallingIdentity(); 4677 try { 4678 IActivityManager am = ActivityManager.getService(); 4679 if (am != null) { 4680 try { 4681 am.killUid(appId, userId, reason); 4682 } catch (RemoteException e) { 4683 /* ignore - same process */ 4684 } 4685 } 4686 } finally { 4687 Binder.restoreCallingIdentity(identity); 4688 } 4689 } 4690 4691 /** 4692 * Compares two sets of signatures. Returns: 4693 * <br /> 4694 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4695 * <br /> 4696 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4697 * <br /> 4698 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4699 * <br /> 4700 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4701 * <br /> 4702 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4703 */ 4704 static int compareSignatures(Signature[] s1, Signature[] s2) { 4705 if (s1 == null) { 4706 return s2 == null 4707 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4708 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4709 } 4710 4711 if (s2 == null) { 4712 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4713 } 4714 4715 if (s1.length != s2.length) { 4716 return PackageManager.SIGNATURE_NO_MATCH; 4717 } 4718 4719 // Since both signature sets are of size 1, we can compare without HashSets. 4720 if (s1.length == 1) { 4721 return s1[0].equals(s2[0]) ? 4722 PackageManager.SIGNATURE_MATCH : 4723 PackageManager.SIGNATURE_NO_MATCH; 4724 } 4725 4726 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4727 for (Signature sig : s1) { 4728 set1.add(sig); 4729 } 4730 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4731 for (Signature sig : s2) { 4732 set2.add(sig); 4733 } 4734 // Make sure s2 contains all signatures in s1. 4735 if (set1.equals(set2)) { 4736 return PackageManager.SIGNATURE_MATCH; 4737 } 4738 return PackageManager.SIGNATURE_NO_MATCH; 4739 } 4740 4741 /** 4742 * If the database version for this type of package (internal storage or 4743 * external storage) is less than the version where package signatures 4744 * were updated, return true. 4745 */ 4746 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4747 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4748 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4749 } 4750 4751 /** 4752 * Used for backward compatibility to make sure any packages with 4753 * certificate chains get upgraded to the new style. {@code existingSigs} 4754 * will be in the old format (since they were stored on disk from before the 4755 * system upgrade) and {@code scannedSigs} will be in the newer format. 4756 */ 4757 private int compareSignaturesCompat(PackageSignatures existingSigs, 4758 PackageParser.Package scannedPkg) { 4759 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4760 return PackageManager.SIGNATURE_NO_MATCH; 4761 } 4762 4763 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4764 for (Signature sig : existingSigs.mSignatures) { 4765 existingSet.add(sig); 4766 } 4767 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4768 for (Signature sig : scannedPkg.mSignatures) { 4769 try { 4770 Signature[] chainSignatures = sig.getChainSignatures(); 4771 for (Signature chainSig : chainSignatures) { 4772 scannedCompatSet.add(chainSig); 4773 } 4774 } catch (CertificateEncodingException e) { 4775 scannedCompatSet.add(sig); 4776 } 4777 } 4778 /* 4779 * Make sure the expanded scanned set contains all signatures in the 4780 * existing one. 4781 */ 4782 if (scannedCompatSet.equals(existingSet)) { 4783 // Migrate the old signatures to the new scheme. 4784 existingSigs.assignSignatures(scannedPkg.mSignatures); 4785 // The new KeySets will be re-added later in the scanning process. 4786 synchronized (mPackages) { 4787 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4788 } 4789 return PackageManager.SIGNATURE_MATCH; 4790 } 4791 return PackageManager.SIGNATURE_NO_MATCH; 4792 } 4793 4794 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4795 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4796 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4797 } 4798 4799 private int compareSignaturesRecover(PackageSignatures existingSigs, 4800 PackageParser.Package scannedPkg) { 4801 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4802 return PackageManager.SIGNATURE_NO_MATCH; 4803 } 4804 4805 String msg = null; 4806 try { 4807 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4808 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4809 + scannedPkg.packageName); 4810 return PackageManager.SIGNATURE_MATCH; 4811 } 4812 } catch (CertificateException e) { 4813 msg = e.getMessage(); 4814 } 4815 4816 logCriticalInfo(Log.INFO, 4817 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4818 return PackageManager.SIGNATURE_NO_MATCH; 4819 } 4820 4821 @Override 4822 public List<String> getAllPackages() { 4823 synchronized (mPackages) { 4824 return new ArrayList<String>(mPackages.keySet()); 4825 } 4826 } 4827 4828 @Override 4829 public String[] getPackagesForUid(int uid) { 4830 final int userId = UserHandle.getUserId(uid); 4831 uid = UserHandle.getAppId(uid); 4832 // reader 4833 synchronized (mPackages) { 4834 Object obj = mSettings.getUserIdLPr(uid); 4835 if (obj instanceof SharedUserSetting) { 4836 final SharedUserSetting sus = (SharedUserSetting) obj; 4837 final int N = sus.packages.size(); 4838 String[] res = new String[N]; 4839 final Iterator<PackageSetting> it = sus.packages.iterator(); 4840 int i = 0; 4841 while (it.hasNext()) { 4842 PackageSetting ps = it.next(); 4843 if (ps.getInstalled(userId)) { 4844 res[i++] = ps.name; 4845 } else { 4846 res = ArrayUtils.removeElement(String.class, res, res[i]); 4847 } 4848 } 4849 return res; 4850 } else if (obj instanceof PackageSetting) { 4851 final PackageSetting ps = (PackageSetting) obj; 4852 return new String[] { ps.name }; 4853 } 4854 } 4855 return null; 4856 } 4857 4858 @Override 4859 public String getNameForUid(int uid) { 4860 // reader 4861 synchronized (mPackages) { 4862 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4863 if (obj instanceof SharedUserSetting) { 4864 final SharedUserSetting sus = (SharedUserSetting) obj; 4865 return sus.name + ":" + sus.userId; 4866 } else if (obj instanceof PackageSetting) { 4867 final PackageSetting ps = (PackageSetting) obj; 4868 return ps.name; 4869 } 4870 } 4871 return null; 4872 } 4873 4874 @Override 4875 public int getUidForSharedUser(String sharedUserName) { 4876 if(sharedUserName == null) { 4877 return -1; 4878 } 4879 // reader 4880 synchronized (mPackages) { 4881 SharedUserSetting suid; 4882 try { 4883 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4884 if (suid != null) { 4885 return suid.userId; 4886 } 4887 } catch (PackageManagerException ignore) { 4888 // can't happen, but, still need to catch it 4889 } 4890 return -1; 4891 } 4892 } 4893 4894 @Override 4895 public int getFlagsForUid(int uid) { 4896 synchronized (mPackages) { 4897 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4898 if (obj instanceof SharedUserSetting) { 4899 final SharedUserSetting sus = (SharedUserSetting) obj; 4900 return sus.pkgFlags; 4901 } else if (obj instanceof PackageSetting) { 4902 final PackageSetting ps = (PackageSetting) obj; 4903 return ps.pkgFlags; 4904 } 4905 } 4906 return 0; 4907 } 4908 4909 @Override 4910 public int getPrivateFlagsForUid(int uid) { 4911 synchronized (mPackages) { 4912 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4913 if (obj instanceof SharedUserSetting) { 4914 final SharedUserSetting sus = (SharedUserSetting) obj; 4915 return sus.pkgPrivateFlags; 4916 } else if (obj instanceof PackageSetting) { 4917 final PackageSetting ps = (PackageSetting) obj; 4918 return ps.pkgPrivateFlags; 4919 } 4920 } 4921 return 0; 4922 } 4923 4924 @Override 4925 public boolean isUidPrivileged(int uid) { 4926 uid = UserHandle.getAppId(uid); 4927 // reader 4928 synchronized (mPackages) { 4929 Object obj = mSettings.getUserIdLPr(uid); 4930 if (obj instanceof SharedUserSetting) { 4931 final SharedUserSetting sus = (SharedUserSetting) obj; 4932 final Iterator<PackageSetting> it = sus.packages.iterator(); 4933 while (it.hasNext()) { 4934 if (it.next().isPrivileged()) { 4935 return true; 4936 } 4937 } 4938 } else if (obj instanceof PackageSetting) { 4939 final PackageSetting ps = (PackageSetting) obj; 4940 return ps.isPrivileged(); 4941 } 4942 } 4943 return false; 4944 } 4945 4946 @Override 4947 public String[] getAppOpPermissionPackages(String permissionName) { 4948 synchronized (mPackages) { 4949 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4950 if (pkgs == null) { 4951 return null; 4952 } 4953 return pkgs.toArray(new String[pkgs.size()]); 4954 } 4955 } 4956 4957 @Override 4958 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4959 int flags, int userId) { 4960 try { 4961 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4962 4963 if (!sUserManager.exists(userId)) return null; 4964 flags = updateFlagsForResolve(flags, userId, intent); 4965 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4966 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4967 4968 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4969 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4970 flags, userId); 4971 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4972 4973 final ResolveInfo bestChoice = 4974 chooseBestActivity(intent, resolvedType, flags, query, userId); 4975 return bestChoice; 4976 } finally { 4977 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4978 } 4979 } 4980 4981 @Override 4982 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4983 IntentFilter filter, int match, ComponentName activity) { 4984 final int userId = UserHandle.getCallingUserId(); 4985 if (DEBUG_PREFERRED) { 4986 Log.v(TAG, "setLastChosenActivity intent=" + intent 4987 + " resolvedType=" + resolvedType 4988 + " flags=" + flags 4989 + " filter=" + filter 4990 + " match=" + match 4991 + " activity=" + activity); 4992 filter.dump(new PrintStreamPrinter(System.out), " "); 4993 } 4994 intent.setComponent(null); 4995 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4996 userId); 4997 // Find any earlier preferred or last chosen entries and nuke them 4998 findPreferredActivity(intent, resolvedType, 4999 flags, query, 0, false, true, false, userId); 5000 // Add the new activity as the last chosen for this filter 5001 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5002 "Setting last chosen"); 5003 } 5004 5005 @Override 5006 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5007 final int userId = UserHandle.getCallingUserId(); 5008 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5009 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5010 userId); 5011 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5012 false, false, false, userId); 5013 } 5014 5015 private boolean isEphemeralDisabled() { 5016 // ephemeral apps have been disabled across the board 5017 if (DISABLE_EPHEMERAL_APPS) { 5018 return true; 5019 } 5020 // system isn't up yet; can't read settings, so, assume no ephemeral apps 5021 if (!mSystemReady) { 5022 return true; 5023 } 5024 // we can't get a content resolver until the system is ready; these checks must happen last 5025 final ContentResolver resolver = mContext.getContentResolver(); 5026 if (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) { 5027 return true; 5028 } 5029 return Secure.getInt(resolver, Secure.WEB_ACTION_ENABLED, 1) == 0; 5030 } 5031 5032 private boolean isEphemeralAllowed( 5033 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5034 boolean skipPackageCheck) { 5035 // Short circuit and return early if possible. 5036 if (isEphemeralDisabled()) { 5037 return false; 5038 } 5039 final int callingUser = UserHandle.getCallingUserId(); 5040 if (callingUser != UserHandle.USER_SYSTEM) { 5041 return false; 5042 } 5043 if (mEphemeralResolverConnection == null) { 5044 return false; 5045 } 5046 if (mEphemeralInstallerComponent == null) { 5047 return false; 5048 } 5049 if (intent.getComponent() != null) { 5050 return false; 5051 } 5052 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5053 return false; 5054 } 5055 if (!skipPackageCheck && intent.getPackage() != null) { 5056 return false; 5057 } 5058 final boolean isWebUri = hasWebURI(intent); 5059 if (!isWebUri || intent.getData().getHost() == null) { 5060 return false; 5061 } 5062 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5063 synchronized (mPackages) { 5064 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5065 for (int n = 0; n < count; n++) { 5066 ResolveInfo info = resolvedActivities.get(n); 5067 String packageName = info.activityInfo.packageName; 5068 PackageSetting ps = mSettings.mPackages.get(packageName); 5069 if (ps != null) { 5070 // Try to get the status from User settings first 5071 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5072 int status = (int) (packedStatus >> 32); 5073 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5074 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5075 if (DEBUG_EPHEMERAL) { 5076 Slog.v(TAG, "DENY ephemeral apps;" 5077 + " pkg: " + packageName + ", status: " + status); 5078 } 5079 return false; 5080 } 5081 } 5082 } 5083 } 5084 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5085 return true; 5086 } 5087 5088 private void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 5089 Intent origIntent, String resolvedType, Intent launchIntent, String callingPackage, 5090 int userId) { 5091 final Message msg = mHandler.obtainMessage(EPHEMERAL_RESOLUTION_PHASE_TWO, 5092 new EphemeralRequest(responseObj, origIntent, resolvedType, launchIntent, 5093 callingPackage, userId)); 5094 mHandler.sendMessage(msg); 5095 } 5096 5097 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5098 int flags, List<ResolveInfo> query, int userId) { 5099 if (query != null) { 5100 final int N = query.size(); 5101 if (N == 1) { 5102 return query.get(0); 5103 } else if (N > 1) { 5104 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5105 // If there is more than one activity with the same priority, 5106 // then let the user decide between them. 5107 ResolveInfo r0 = query.get(0); 5108 ResolveInfo r1 = query.get(1); 5109 if (DEBUG_INTENT_MATCHING || debug) { 5110 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5111 + r1.activityInfo.name + "=" + r1.priority); 5112 } 5113 // If the first activity has a higher priority, or a different 5114 // default, then it is always desirable to pick it. 5115 if (r0.priority != r1.priority 5116 || r0.preferredOrder != r1.preferredOrder 5117 || r0.isDefault != r1.isDefault) { 5118 return query.get(0); 5119 } 5120 // If we have saved a preference for a preferred activity for 5121 // this Intent, use that. 5122 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5123 flags, query, r0.priority, true, false, debug, userId); 5124 if (ri != null) { 5125 return ri; 5126 } 5127 ri = new ResolveInfo(mResolveInfo); 5128 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5129 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5130 // If all of the options come from the same package, show the application's 5131 // label and icon instead of the generic resolver's. 5132 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5133 // and then throw away the ResolveInfo itself, meaning that the caller loses 5134 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5135 // a fallback for this case; we only set the target package's resources on 5136 // the ResolveInfo, not the ActivityInfo. 5137 final String intentPackage = intent.getPackage(); 5138 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5139 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5140 ri.resolvePackageName = intentPackage; 5141 if (userNeedsBadging(userId)) { 5142 ri.noResourceId = true; 5143 } else { 5144 ri.icon = appi.icon; 5145 } 5146 ri.iconResourceId = appi.icon; 5147 ri.labelRes = appi.labelRes; 5148 } 5149 ri.activityInfo.applicationInfo = new ApplicationInfo( 5150 ri.activityInfo.applicationInfo); 5151 if (userId != 0) { 5152 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5153 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5154 } 5155 // Make sure that the resolver is displayable in car mode 5156 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5157 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5158 return ri; 5159 } 5160 } 5161 return null; 5162 } 5163 5164 /** 5165 * Return true if the given list is not empty and all of its contents have 5166 * an activityInfo with the given package name. 5167 */ 5168 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5169 if (ArrayUtils.isEmpty(list)) { 5170 return false; 5171 } 5172 for (int i = 0, N = list.size(); i < N; i++) { 5173 final ResolveInfo ri = list.get(i); 5174 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5175 if (ai == null || !packageName.equals(ai.packageName)) { 5176 return false; 5177 } 5178 } 5179 return true; 5180 } 5181 5182 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5183 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5184 final int N = query.size(); 5185 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5186 .get(userId); 5187 // Get the list of persistent preferred activities that handle the intent 5188 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5189 List<PersistentPreferredActivity> pprefs = ppir != null 5190 ? ppir.queryIntent(intent, resolvedType, 5191 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5192 : null; 5193 if (pprefs != null && pprefs.size() > 0) { 5194 final int M = pprefs.size(); 5195 for (int i=0; i<M; i++) { 5196 final PersistentPreferredActivity ppa = pprefs.get(i); 5197 if (DEBUG_PREFERRED || debug) { 5198 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5199 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5200 + "\n component=" + ppa.mComponent); 5201 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5202 } 5203 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5204 flags | MATCH_DISABLED_COMPONENTS, userId); 5205 if (DEBUG_PREFERRED || debug) { 5206 Slog.v(TAG, "Found persistent preferred activity:"); 5207 if (ai != null) { 5208 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5209 } else { 5210 Slog.v(TAG, " null"); 5211 } 5212 } 5213 if (ai == null) { 5214 // This previously registered persistent preferred activity 5215 // component is no longer known. Ignore it and do NOT remove it. 5216 continue; 5217 } 5218 for (int j=0; j<N; j++) { 5219 final ResolveInfo ri = query.get(j); 5220 if (!ri.activityInfo.applicationInfo.packageName 5221 .equals(ai.applicationInfo.packageName)) { 5222 continue; 5223 } 5224 if (!ri.activityInfo.name.equals(ai.name)) { 5225 continue; 5226 } 5227 // Found a persistent preference that can handle the intent. 5228 if (DEBUG_PREFERRED || debug) { 5229 Slog.v(TAG, "Returning persistent preferred activity: " + 5230 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5231 } 5232 return ri; 5233 } 5234 } 5235 } 5236 return null; 5237 } 5238 5239 // TODO: handle preferred activities missing while user has amnesia 5240 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5241 List<ResolveInfo> query, int priority, boolean always, 5242 boolean removeMatches, boolean debug, int userId) { 5243 if (!sUserManager.exists(userId)) return null; 5244 flags = updateFlagsForResolve(flags, userId, intent); 5245 // writer 5246 synchronized (mPackages) { 5247 if (intent.getSelector() != null) { 5248 intent = intent.getSelector(); 5249 } 5250 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5251 5252 // Try to find a matching persistent preferred activity. 5253 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5254 debug, userId); 5255 5256 // If a persistent preferred activity matched, use it. 5257 if (pri != null) { 5258 return pri; 5259 } 5260 5261 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5262 // Get the list of preferred activities that handle the intent 5263 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5264 List<PreferredActivity> prefs = pir != null 5265 ? pir.queryIntent(intent, resolvedType, 5266 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5267 : null; 5268 if (prefs != null && prefs.size() > 0) { 5269 boolean changed = false; 5270 try { 5271 // First figure out how good the original match set is. 5272 // We will only allow preferred activities that came 5273 // from the same match quality. 5274 int match = 0; 5275 5276 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5277 5278 final int N = query.size(); 5279 for (int j=0; j<N; j++) { 5280 final ResolveInfo ri = query.get(j); 5281 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5282 + ": 0x" + Integer.toHexString(match)); 5283 if (ri.match > match) { 5284 match = ri.match; 5285 } 5286 } 5287 5288 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5289 + Integer.toHexString(match)); 5290 5291 match &= IntentFilter.MATCH_CATEGORY_MASK; 5292 final int M = prefs.size(); 5293 for (int i=0; i<M; i++) { 5294 final PreferredActivity pa = prefs.get(i); 5295 if (DEBUG_PREFERRED || debug) { 5296 Slog.v(TAG, "Checking PreferredActivity ds=" 5297 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5298 + "\n component=" + pa.mPref.mComponent); 5299 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5300 } 5301 if (pa.mPref.mMatch != match) { 5302 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5303 + Integer.toHexString(pa.mPref.mMatch)); 5304 continue; 5305 } 5306 // If it's not an "always" type preferred activity and that's what we're 5307 // looking for, skip it. 5308 if (always && !pa.mPref.mAlways) { 5309 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5310 continue; 5311 } 5312 final ActivityInfo ai = getActivityInfo( 5313 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5314 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5315 userId); 5316 if (DEBUG_PREFERRED || debug) { 5317 Slog.v(TAG, "Found preferred activity:"); 5318 if (ai != null) { 5319 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5320 } else { 5321 Slog.v(TAG, " null"); 5322 } 5323 } 5324 if (ai == null) { 5325 // This previously registered preferred activity 5326 // component is no longer known. Most likely an update 5327 // to the app was installed and in the new version this 5328 // component no longer exists. Clean it up by removing 5329 // it from the preferred activities list, and skip it. 5330 Slog.w(TAG, "Removing dangling preferred activity: " 5331 + pa.mPref.mComponent); 5332 pir.removeFilter(pa); 5333 changed = true; 5334 continue; 5335 } 5336 for (int j=0; j<N; j++) { 5337 final ResolveInfo ri = query.get(j); 5338 if (!ri.activityInfo.applicationInfo.packageName 5339 .equals(ai.applicationInfo.packageName)) { 5340 continue; 5341 } 5342 if (!ri.activityInfo.name.equals(ai.name)) { 5343 continue; 5344 } 5345 5346 if (removeMatches) { 5347 pir.removeFilter(pa); 5348 changed = true; 5349 if (DEBUG_PREFERRED) { 5350 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5351 } 5352 break; 5353 } 5354 5355 // Okay we found a previously set preferred or last chosen app. 5356 // If the result set is different from when this 5357 // was created, we need to clear it and re-ask the 5358 // user their preference, if we're looking for an "always" type entry. 5359 if (always && !pa.mPref.sameSet(query)) { 5360 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5361 + intent + " type " + resolvedType); 5362 if (DEBUG_PREFERRED) { 5363 Slog.v(TAG, "Removing preferred activity since set changed " 5364 + pa.mPref.mComponent); 5365 } 5366 pir.removeFilter(pa); 5367 // Re-add the filter as a "last chosen" entry (!always) 5368 PreferredActivity lastChosen = new PreferredActivity( 5369 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5370 pir.addFilter(lastChosen); 5371 changed = true; 5372 return null; 5373 } 5374 5375 // Yay! Either the set matched or we're looking for the last chosen 5376 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5377 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5378 return ri; 5379 } 5380 } 5381 } finally { 5382 if (changed) { 5383 if (DEBUG_PREFERRED) { 5384 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5385 } 5386 scheduleWritePackageRestrictionsLocked(userId); 5387 } 5388 } 5389 } 5390 } 5391 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5392 return null; 5393 } 5394 5395 /* 5396 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5397 */ 5398 @Override 5399 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5400 int targetUserId) { 5401 mContext.enforceCallingOrSelfPermission( 5402 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5403 List<CrossProfileIntentFilter> matches = 5404 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5405 if (matches != null) { 5406 int size = matches.size(); 5407 for (int i = 0; i < size; i++) { 5408 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5409 } 5410 } 5411 if (hasWebURI(intent)) { 5412 // cross-profile app linking works only towards the parent. 5413 final UserInfo parent = getProfileParent(sourceUserId); 5414 synchronized(mPackages) { 5415 int flags = updateFlagsForResolve(0, parent.id, intent); 5416 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5417 intent, resolvedType, flags, sourceUserId, parent.id); 5418 return xpDomainInfo != null; 5419 } 5420 } 5421 return false; 5422 } 5423 5424 private UserInfo getProfileParent(int userId) { 5425 final long identity = Binder.clearCallingIdentity(); 5426 try { 5427 return sUserManager.getProfileParent(userId); 5428 } finally { 5429 Binder.restoreCallingIdentity(identity); 5430 } 5431 } 5432 5433 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5434 String resolvedType, int userId) { 5435 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5436 if (resolver != null) { 5437 return resolver.queryIntent(intent, resolvedType, false, userId); 5438 } 5439 return null; 5440 } 5441 5442 @Override 5443 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5444 String resolvedType, int flags, int userId) { 5445 try { 5446 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5447 5448 return new ParceledListSlice<>( 5449 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5450 } finally { 5451 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5452 } 5453 } 5454 5455 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5456 String resolvedType, int flags, int userId) { 5457 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5458 flags = updateFlagsForResolve(flags, userId, intent); 5459 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5460 false /* requireFullPermission */, false /* checkShell */, 5461 "query intent activities"); 5462 ComponentName comp = intent.getComponent(); 5463 if (comp == null) { 5464 if (intent.getSelector() != null) { 5465 intent = intent.getSelector(); 5466 comp = intent.getComponent(); 5467 } 5468 } 5469 5470 if (comp != null) { 5471 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5472 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5473 if (ai != null) { 5474 final ResolveInfo ri = new ResolveInfo(); 5475 ri.activityInfo = ai; 5476 list.add(ri); 5477 } 5478 return list; 5479 } 5480 5481 // reader 5482 boolean sortResult = false; 5483 boolean addEphemeral = false; 5484 boolean matchEphemeralPackage = false; 5485 List<ResolveInfo> result; 5486 final String pkgName = intent.getPackage(); 5487 synchronized (mPackages) { 5488 if (pkgName == null) { 5489 List<CrossProfileIntentFilter> matchingFilters = 5490 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5491 // Check for results that need to skip the current profile. 5492 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5493 resolvedType, flags, userId); 5494 if (xpResolveInfo != null) { 5495 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 5496 xpResult.add(xpResolveInfo); 5497 return filterIfNotSystemUser(xpResult, userId); 5498 } 5499 5500 // Check for results in the current profile. 5501 result = filterIfNotSystemUser(mActivities.queryIntent( 5502 intent, resolvedType, flags, userId), userId); 5503 addEphemeral = 5504 isEphemeralAllowed(intent, result, userId, false /*skipPackageCheck*/); 5505 5506 // Check for cross profile results. 5507 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5508 xpResolveInfo = queryCrossProfileIntents( 5509 matchingFilters, intent, resolvedType, flags, userId, 5510 hasNonNegativePriorityResult); 5511 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5512 boolean isVisibleToUser = filterIfNotSystemUser( 5513 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5514 if (isVisibleToUser) { 5515 result.add(xpResolveInfo); 5516 sortResult = true; 5517 } 5518 } 5519 if (hasWebURI(intent)) { 5520 CrossProfileDomainInfo xpDomainInfo = null; 5521 final UserInfo parent = getProfileParent(userId); 5522 if (parent != null) { 5523 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5524 flags, userId, parent.id); 5525 } 5526 if (xpDomainInfo != null) { 5527 if (xpResolveInfo != null) { 5528 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5529 // in the result. 5530 result.remove(xpResolveInfo); 5531 } 5532 if (result.size() == 0 && !addEphemeral) { 5533 // No result in current profile, but found candidate in parent user. 5534 // And we are not going to add emphemeral app, so we can return the 5535 // result straight away. 5536 result.add(xpDomainInfo.resolveInfo); 5537 return result; 5538 } 5539 } else if (result.size() <= 1 && !addEphemeral) { 5540 // No result in parent user and <= 1 result in current profile, and we 5541 // are not going to add emphemeral app, so we can return the result without 5542 // further processing. 5543 return result; 5544 } 5545 // We have more than one candidate (combining results from current and parent 5546 // profile), so we need filtering and sorting. 5547 result = filterCandidatesWithDomainPreferredActivitiesLPr( 5548 intent, flags, result, xpDomainInfo, userId); 5549 sortResult = true; 5550 } 5551 } else { 5552 final PackageParser.Package pkg = mPackages.get(pkgName); 5553 if (pkg != null) { 5554 result = filterIfNotSystemUser( 5555 mActivities.queryIntentForPackage( 5556 intent, resolvedType, flags, pkg.activities, userId), 5557 userId); 5558 } else { 5559 // the caller wants to resolve for a particular package; however, there 5560 // were no installed results, so, try to find an ephemeral result 5561 addEphemeral = isEphemeralAllowed( 5562 intent, null /*result*/, userId, true /*skipPackageCheck*/); 5563 matchEphemeralPackage = true; 5564 result = new ArrayList<ResolveInfo>(); 5565 } 5566 } 5567 } 5568 if (addEphemeral) { 5569 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 5570 final EphemeralRequest requestObject = new EphemeralRequest( 5571 null /*responseObj*/, intent /*origIntent*/, resolvedType, 5572 null /*launchIntent*/, null /*callingPackage*/, userId); 5573 final EphemeralResponse intentInfo = EphemeralResolver.doEphemeralResolutionPhaseOne( 5574 mContext, mEphemeralResolverConnection, requestObject); 5575 if (intentInfo != null) { 5576 if (DEBUG_EPHEMERAL) { 5577 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 5578 } 5579 final ResolveInfo ephemeralInstaller = new ResolveInfo(mEphemeralInstallerInfo); 5580 ephemeralInstaller.ephemeralResponse = intentInfo; 5581 // make sure this resolver is the default 5582 ephemeralInstaller.isDefault = true; 5583 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 5584 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 5585 // add a non-generic filter 5586 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 5587 ephemeralInstaller.filter.addDataPath( 5588 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 5589 result.add(ephemeralInstaller); 5590 } 5591 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5592 } 5593 if (sortResult) { 5594 Collections.sort(result, mResolvePrioritySorter); 5595 } 5596 return result; 5597 } 5598 5599 private static class CrossProfileDomainInfo { 5600 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5601 ResolveInfo resolveInfo; 5602 /* Best domain verification status of the activities found in the other profile */ 5603 int bestDomainVerificationStatus; 5604 } 5605 5606 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5607 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5608 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5609 sourceUserId)) { 5610 return null; 5611 } 5612 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5613 resolvedType, flags, parentUserId); 5614 5615 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5616 return null; 5617 } 5618 CrossProfileDomainInfo result = null; 5619 int size = resultTargetUser.size(); 5620 for (int i = 0; i < size; i++) { 5621 ResolveInfo riTargetUser = resultTargetUser.get(i); 5622 // Intent filter verification is only for filters that specify a host. So don't return 5623 // those that handle all web uris. 5624 if (riTargetUser.handleAllWebDataURI) { 5625 continue; 5626 } 5627 String packageName = riTargetUser.activityInfo.packageName; 5628 PackageSetting ps = mSettings.mPackages.get(packageName); 5629 if (ps == null) { 5630 continue; 5631 } 5632 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5633 int status = (int)(verificationState >> 32); 5634 if (result == null) { 5635 result = new CrossProfileDomainInfo(); 5636 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5637 sourceUserId, parentUserId); 5638 result.bestDomainVerificationStatus = status; 5639 } else { 5640 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5641 result.bestDomainVerificationStatus); 5642 } 5643 } 5644 // Don't consider matches with status NEVER across profiles. 5645 if (result != null && result.bestDomainVerificationStatus 5646 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5647 return null; 5648 } 5649 return result; 5650 } 5651 5652 /** 5653 * Verification statuses are ordered from the worse to the best, except for 5654 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5655 */ 5656 private int bestDomainVerificationStatus(int status1, int status2) { 5657 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5658 return status2; 5659 } 5660 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5661 return status1; 5662 } 5663 return (int) MathUtils.max(status1, status2); 5664 } 5665 5666 private boolean isUserEnabled(int userId) { 5667 long callingId = Binder.clearCallingIdentity(); 5668 try { 5669 UserInfo userInfo = sUserManager.getUserInfo(userId); 5670 return userInfo != null && userInfo.isEnabled(); 5671 } finally { 5672 Binder.restoreCallingIdentity(callingId); 5673 } 5674 } 5675 5676 /** 5677 * Filter out activities with systemUserOnly flag set, when current user is not System. 5678 * 5679 * @return filtered list 5680 */ 5681 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5682 if (userId == UserHandle.USER_SYSTEM) { 5683 return resolveInfos; 5684 } 5685 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5686 ResolveInfo info = resolveInfos.get(i); 5687 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5688 resolveInfos.remove(i); 5689 } 5690 } 5691 return resolveInfos; 5692 } 5693 5694 /** 5695 * @param resolveInfos list of resolve infos in descending priority order 5696 * @return if the list contains a resolve info with non-negative priority 5697 */ 5698 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5699 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5700 } 5701 5702 private static boolean hasWebURI(Intent intent) { 5703 if (intent.getData() == null) { 5704 return false; 5705 } 5706 final String scheme = intent.getScheme(); 5707 if (TextUtils.isEmpty(scheme)) { 5708 return false; 5709 } 5710 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5711 } 5712 5713 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5714 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5715 int userId) { 5716 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5717 5718 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5719 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5720 candidates.size()); 5721 } 5722 5723 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5724 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5725 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5726 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5727 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5728 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5729 5730 synchronized (mPackages) { 5731 final int count = candidates.size(); 5732 // First, try to use linked apps. Partition the candidates into four lists: 5733 // one for the final results, one for the "do not use ever", one for "undefined status" 5734 // and finally one for "browser app type". 5735 for (int n=0; n<count; n++) { 5736 ResolveInfo info = candidates.get(n); 5737 String packageName = info.activityInfo.packageName; 5738 PackageSetting ps = mSettings.mPackages.get(packageName); 5739 if (ps != null) { 5740 // Add to the special match all list (Browser use case) 5741 if (info.handleAllWebDataURI) { 5742 matchAllList.add(info); 5743 continue; 5744 } 5745 // Try to get the status from User settings first 5746 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5747 int status = (int)(packedStatus >> 32); 5748 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5749 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5750 if (DEBUG_DOMAIN_VERIFICATION) { 5751 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5752 + " : linkgen=" + linkGeneration); 5753 } 5754 // Use link-enabled generation as preferredOrder, i.e. 5755 // prefer newly-enabled over earlier-enabled. 5756 info.preferredOrder = linkGeneration; 5757 alwaysList.add(info); 5758 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5759 if (DEBUG_DOMAIN_VERIFICATION) { 5760 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5761 } 5762 neverList.add(info); 5763 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5764 if (DEBUG_DOMAIN_VERIFICATION) { 5765 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5766 } 5767 alwaysAskList.add(info); 5768 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5769 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5770 if (DEBUG_DOMAIN_VERIFICATION) { 5771 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5772 } 5773 undefinedList.add(info); 5774 } 5775 } 5776 } 5777 5778 // We'll want to include browser possibilities in a few cases 5779 boolean includeBrowser = false; 5780 5781 // First try to add the "always" resolution(s) for the current user, if any 5782 if (alwaysList.size() > 0) { 5783 result.addAll(alwaysList); 5784 } else { 5785 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5786 result.addAll(undefinedList); 5787 // Maybe add one for the other profile. 5788 if (xpDomainInfo != null && ( 5789 xpDomainInfo.bestDomainVerificationStatus 5790 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5791 result.add(xpDomainInfo.resolveInfo); 5792 } 5793 includeBrowser = true; 5794 } 5795 5796 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5797 // If there were 'always' entries their preferred order has been set, so we also 5798 // back that off to make the alternatives equivalent 5799 if (alwaysAskList.size() > 0) { 5800 for (ResolveInfo i : result) { 5801 i.preferredOrder = 0; 5802 } 5803 result.addAll(alwaysAskList); 5804 includeBrowser = true; 5805 } 5806 5807 if (includeBrowser) { 5808 // Also add browsers (all of them or only the default one) 5809 if (DEBUG_DOMAIN_VERIFICATION) { 5810 Slog.v(TAG, " ...including browsers in candidate set"); 5811 } 5812 if ((matchFlags & MATCH_ALL) != 0) { 5813 result.addAll(matchAllList); 5814 } else { 5815 // Browser/generic handling case. If there's a default browser, go straight 5816 // to that (but only if there is no other higher-priority match). 5817 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5818 int maxMatchPrio = 0; 5819 ResolveInfo defaultBrowserMatch = null; 5820 final int numCandidates = matchAllList.size(); 5821 for (int n = 0; n < numCandidates; n++) { 5822 ResolveInfo info = matchAllList.get(n); 5823 // track the highest overall match priority... 5824 if (info.priority > maxMatchPrio) { 5825 maxMatchPrio = info.priority; 5826 } 5827 // ...and the highest-priority default browser match 5828 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5829 if (defaultBrowserMatch == null 5830 || (defaultBrowserMatch.priority < info.priority)) { 5831 if (debug) { 5832 Slog.v(TAG, "Considering default browser match " + info); 5833 } 5834 defaultBrowserMatch = info; 5835 } 5836 } 5837 } 5838 if (defaultBrowserMatch != null 5839 && defaultBrowserMatch.priority >= maxMatchPrio 5840 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5841 { 5842 if (debug) { 5843 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5844 } 5845 result.add(defaultBrowserMatch); 5846 } else { 5847 result.addAll(matchAllList); 5848 } 5849 } 5850 5851 // If there is nothing selected, add all candidates and remove the ones that the user 5852 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5853 if (result.size() == 0) { 5854 result.addAll(candidates); 5855 result.removeAll(neverList); 5856 } 5857 } 5858 } 5859 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5860 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5861 result.size()); 5862 for (ResolveInfo info : result) { 5863 Slog.v(TAG, " + " + info.activityInfo); 5864 } 5865 } 5866 return result; 5867 } 5868 5869 // Returns a packed value as a long: 5870 // 5871 // high 'int'-sized word: link status: undefined/ask/never/always. 5872 // low 'int'-sized word: relative priority among 'always' results. 5873 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5874 long result = ps.getDomainVerificationStatusForUser(userId); 5875 // if none available, get the master status 5876 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5877 if (ps.getIntentFilterVerificationInfo() != null) { 5878 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5879 } 5880 } 5881 return result; 5882 } 5883 5884 private ResolveInfo querySkipCurrentProfileIntents( 5885 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5886 int flags, int sourceUserId) { 5887 if (matchingFilters != null) { 5888 int size = matchingFilters.size(); 5889 for (int i = 0; i < size; i ++) { 5890 CrossProfileIntentFilter filter = matchingFilters.get(i); 5891 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5892 // Checking if there are activities in the target user that can handle the 5893 // intent. 5894 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5895 resolvedType, flags, sourceUserId); 5896 if (resolveInfo != null) { 5897 return resolveInfo; 5898 } 5899 } 5900 } 5901 } 5902 return null; 5903 } 5904 5905 // Return matching ResolveInfo in target user if any. 5906 private ResolveInfo queryCrossProfileIntents( 5907 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5908 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5909 if (matchingFilters != null) { 5910 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5911 // match the same intent. For performance reasons, it is better not to 5912 // run queryIntent twice for the same userId 5913 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5914 int size = matchingFilters.size(); 5915 for (int i = 0; i < size; i++) { 5916 CrossProfileIntentFilter filter = matchingFilters.get(i); 5917 int targetUserId = filter.getTargetUserId(); 5918 boolean skipCurrentProfile = 5919 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5920 boolean skipCurrentProfileIfNoMatchFound = 5921 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5922 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5923 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5924 // Checking if there are activities in the target user that can handle the 5925 // intent. 5926 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5927 resolvedType, flags, sourceUserId); 5928 if (resolveInfo != null) return resolveInfo; 5929 alreadyTriedUserIds.put(targetUserId, true); 5930 } 5931 } 5932 } 5933 return null; 5934 } 5935 5936 /** 5937 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5938 * will forward the intent to the filter's target user. 5939 * Otherwise, returns null. 5940 */ 5941 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5942 String resolvedType, int flags, int sourceUserId) { 5943 int targetUserId = filter.getTargetUserId(); 5944 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5945 resolvedType, flags, targetUserId); 5946 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5947 // If all the matches in the target profile are suspended, return null. 5948 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5949 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5950 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5951 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5952 targetUserId); 5953 } 5954 } 5955 } 5956 return null; 5957 } 5958 5959 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5960 int sourceUserId, int targetUserId) { 5961 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5962 long ident = Binder.clearCallingIdentity(); 5963 boolean targetIsProfile; 5964 try { 5965 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5966 } finally { 5967 Binder.restoreCallingIdentity(ident); 5968 } 5969 String className; 5970 if (targetIsProfile) { 5971 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5972 } else { 5973 className = FORWARD_INTENT_TO_PARENT; 5974 } 5975 ComponentName forwardingActivityComponentName = new ComponentName( 5976 mAndroidApplication.packageName, className); 5977 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5978 sourceUserId); 5979 if (!targetIsProfile) { 5980 forwardingActivityInfo.showUserIcon = targetUserId; 5981 forwardingResolveInfo.noResourceId = true; 5982 } 5983 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5984 forwardingResolveInfo.priority = 0; 5985 forwardingResolveInfo.preferredOrder = 0; 5986 forwardingResolveInfo.match = 0; 5987 forwardingResolveInfo.isDefault = true; 5988 forwardingResolveInfo.filter = filter; 5989 forwardingResolveInfo.targetUserId = targetUserId; 5990 return forwardingResolveInfo; 5991 } 5992 5993 @Override 5994 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5995 Intent[] specifics, String[] specificTypes, Intent intent, 5996 String resolvedType, int flags, int userId) { 5997 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5998 specificTypes, intent, resolvedType, flags, userId)); 5999 } 6000 6001 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 6002 Intent[] specifics, String[] specificTypes, Intent intent, 6003 String resolvedType, int flags, int userId) { 6004 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6005 flags = updateFlagsForResolve(flags, userId, intent); 6006 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6007 false /* requireFullPermission */, false /* checkShell */, 6008 "query intent activity options"); 6009 final String resultsAction = intent.getAction(); 6010 6011 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 6012 | PackageManager.GET_RESOLVED_FILTER, userId); 6013 6014 if (DEBUG_INTENT_MATCHING) { 6015 Log.v(TAG, "Query " + intent + ": " + results); 6016 } 6017 6018 int specificsPos = 0; 6019 int N; 6020 6021 // todo: note that the algorithm used here is O(N^2). This 6022 // isn't a problem in our current environment, but if we start running 6023 // into situations where we have more than 5 or 10 matches then this 6024 // should probably be changed to something smarter... 6025 6026 // First we go through and resolve each of the specific items 6027 // that were supplied, taking care of removing any corresponding 6028 // duplicate items in the generic resolve list. 6029 if (specifics != null) { 6030 for (int i=0; i<specifics.length; i++) { 6031 final Intent sintent = specifics[i]; 6032 if (sintent == null) { 6033 continue; 6034 } 6035 6036 if (DEBUG_INTENT_MATCHING) { 6037 Log.v(TAG, "Specific #" + i + ": " + sintent); 6038 } 6039 6040 String action = sintent.getAction(); 6041 if (resultsAction != null && resultsAction.equals(action)) { 6042 // If this action was explicitly requested, then don't 6043 // remove things that have it. 6044 action = null; 6045 } 6046 6047 ResolveInfo ri = null; 6048 ActivityInfo ai = null; 6049 6050 ComponentName comp = sintent.getComponent(); 6051 if (comp == null) { 6052 ri = resolveIntent( 6053 sintent, 6054 specificTypes != null ? specificTypes[i] : null, 6055 flags, userId); 6056 if (ri == null) { 6057 continue; 6058 } 6059 if (ri == mResolveInfo) { 6060 // ACK! Must do something better with this. 6061 } 6062 ai = ri.activityInfo; 6063 comp = new ComponentName(ai.applicationInfo.packageName, 6064 ai.name); 6065 } else { 6066 ai = getActivityInfo(comp, flags, userId); 6067 if (ai == null) { 6068 continue; 6069 } 6070 } 6071 6072 // Look for any generic query activities that are duplicates 6073 // of this specific one, and remove them from the results. 6074 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6075 N = results.size(); 6076 int j; 6077 for (j=specificsPos; j<N; j++) { 6078 ResolveInfo sri = results.get(j); 6079 if ((sri.activityInfo.name.equals(comp.getClassName()) 6080 && sri.activityInfo.applicationInfo.packageName.equals( 6081 comp.getPackageName())) 6082 || (action != null && sri.filter.matchAction(action))) { 6083 results.remove(j); 6084 if (DEBUG_INTENT_MATCHING) Log.v( 6085 TAG, "Removing duplicate item from " + j 6086 + " due to specific " + specificsPos); 6087 if (ri == null) { 6088 ri = sri; 6089 } 6090 j--; 6091 N--; 6092 } 6093 } 6094 6095 // Add this specific item to its proper place. 6096 if (ri == null) { 6097 ri = new ResolveInfo(); 6098 ri.activityInfo = ai; 6099 } 6100 results.add(specificsPos, ri); 6101 ri.specificIndex = i; 6102 specificsPos++; 6103 } 6104 } 6105 6106 // Now we go through the remaining generic results and remove any 6107 // duplicate actions that are found here. 6108 N = results.size(); 6109 for (int i=specificsPos; i<N-1; i++) { 6110 final ResolveInfo rii = results.get(i); 6111 if (rii.filter == null) { 6112 continue; 6113 } 6114 6115 // Iterate over all of the actions of this result's intent 6116 // filter... typically this should be just one. 6117 final Iterator<String> it = rii.filter.actionsIterator(); 6118 if (it == null) { 6119 continue; 6120 } 6121 while (it.hasNext()) { 6122 final String action = it.next(); 6123 if (resultsAction != null && resultsAction.equals(action)) { 6124 // If this action was explicitly requested, then don't 6125 // remove things that have it. 6126 continue; 6127 } 6128 for (int j=i+1; j<N; j++) { 6129 final ResolveInfo rij = results.get(j); 6130 if (rij.filter != null && rij.filter.hasAction(action)) { 6131 results.remove(j); 6132 if (DEBUG_INTENT_MATCHING) Log.v( 6133 TAG, "Removing duplicate item from " + j 6134 + " due to action " + action + " at " + i); 6135 j--; 6136 N--; 6137 } 6138 } 6139 } 6140 6141 // If the caller didn't request filter information, drop it now 6142 // so we don't have to marshall/unmarshall it. 6143 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6144 rii.filter = null; 6145 } 6146 } 6147 6148 // Filter out the caller activity if so requested. 6149 if (caller != null) { 6150 N = results.size(); 6151 for (int i=0; i<N; i++) { 6152 ActivityInfo ainfo = results.get(i).activityInfo; 6153 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6154 && caller.getClassName().equals(ainfo.name)) { 6155 results.remove(i); 6156 break; 6157 } 6158 } 6159 } 6160 6161 // If the caller didn't request filter information, 6162 // drop them now so we don't have to 6163 // marshall/unmarshall it. 6164 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6165 N = results.size(); 6166 for (int i=0; i<N; i++) { 6167 results.get(i).filter = null; 6168 } 6169 } 6170 6171 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6172 return results; 6173 } 6174 6175 @Override 6176 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6177 String resolvedType, int flags, int userId) { 6178 return new ParceledListSlice<>( 6179 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6180 } 6181 6182 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6183 String resolvedType, int flags, int userId) { 6184 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6185 flags = updateFlagsForResolve(flags, userId, intent); 6186 ComponentName comp = intent.getComponent(); 6187 if (comp == null) { 6188 if (intent.getSelector() != null) { 6189 intent = intent.getSelector(); 6190 comp = intent.getComponent(); 6191 } 6192 } 6193 if (comp != null) { 6194 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6195 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6196 if (ai != null) { 6197 ResolveInfo ri = new ResolveInfo(); 6198 ri.activityInfo = ai; 6199 list.add(ri); 6200 } 6201 return list; 6202 } 6203 6204 // reader 6205 synchronized (mPackages) { 6206 String pkgName = intent.getPackage(); 6207 if (pkgName == null) { 6208 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6209 } 6210 final PackageParser.Package pkg = mPackages.get(pkgName); 6211 if (pkg != null) { 6212 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6213 userId); 6214 } 6215 return Collections.emptyList(); 6216 } 6217 } 6218 6219 @Override 6220 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6221 if (!sUserManager.exists(userId)) return null; 6222 flags = updateFlagsForResolve(flags, userId, intent); 6223 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6224 if (query != null) { 6225 if (query.size() >= 1) { 6226 // If there is more than one service with the same priority, 6227 // just arbitrarily pick the first one. 6228 return query.get(0); 6229 } 6230 } 6231 return null; 6232 } 6233 6234 @Override 6235 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6236 String resolvedType, int flags, int userId) { 6237 return new ParceledListSlice<>( 6238 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6239 } 6240 6241 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6242 String resolvedType, int flags, int userId) { 6243 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6244 flags = updateFlagsForResolve(flags, userId, intent); 6245 ComponentName comp = intent.getComponent(); 6246 if (comp == null) { 6247 if (intent.getSelector() != null) { 6248 intent = intent.getSelector(); 6249 comp = intent.getComponent(); 6250 } 6251 } 6252 if (comp != null) { 6253 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6254 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6255 if (si != null) { 6256 final ResolveInfo ri = new ResolveInfo(); 6257 ri.serviceInfo = si; 6258 list.add(ri); 6259 } 6260 return list; 6261 } 6262 6263 // reader 6264 synchronized (mPackages) { 6265 String pkgName = intent.getPackage(); 6266 if (pkgName == null) { 6267 return mServices.queryIntent(intent, resolvedType, flags, userId); 6268 } 6269 final PackageParser.Package pkg = mPackages.get(pkgName); 6270 if (pkg != null) { 6271 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6272 userId); 6273 } 6274 return Collections.emptyList(); 6275 } 6276 } 6277 6278 @Override 6279 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6280 String resolvedType, int flags, int userId) { 6281 return new ParceledListSlice<>( 6282 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6283 } 6284 6285 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6286 Intent intent, String resolvedType, int flags, int userId) { 6287 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6288 flags = updateFlagsForResolve(flags, userId, intent); 6289 ComponentName comp = intent.getComponent(); 6290 if (comp == null) { 6291 if (intent.getSelector() != null) { 6292 intent = intent.getSelector(); 6293 comp = intent.getComponent(); 6294 } 6295 } 6296 if (comp != null) { 6297 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6298 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6299 if (pi != null) { 6300 final ResolveInfo ri = new ResolveInfo(); 6301 ri.providerInfo = pi; 6302 list.add(ri); 6303 } 6304 return list; 6305 } 6306 6307 // reader 6308 synchronized (mPackages) { 6309 String pkgName = intent.getPackage(); 6310 if (pkgName == null) { 6311 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6312 } 6313 final PackageParser.Package pkg = mPackages.get(pkgName); 6314 if (pkg != null) { 6315 return mProviders.queryIntentForPackage( 6316 intent, resolvedType, flags, pkg.providers, userId); 6317 } 6318 return Collections.emptyList(); 6319 } 6320 } 6321 6322 @Override 6323 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6324 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6325 flags = updateFlagsForPackage(flags, userId, null); 6326 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6327 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6328 true /* requireFullPermission */, false /* checkShell */, 6329 "get installed packages"); 6330 6331 // writer 6332 synchronized (mPackages) { 6333 ArrayList<PackageInfo> list; 6334 if (listUninstalled) { 6335 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6336 for (PackageSetting ps : mSettings.mPackages.values()) { 6337 final PackageInfo pi; 6338 if (ps.pkg != null) { 6339 pi = generatePackageInfo(ps, flags, userId); 6340 } else { 6341 pi = generatePackageInfo(ps, flags, userId); 6342 } 6343 if (pi != null) { 6344 list.add(pi); 6345 } 6346 } 6347 } else { 6348 list = new ArrayList<PackageInfo>(mPackages.size()); 6349 for (PackageParser.Package p : mPackages.values()) { 6350 final PackageInfo pi = 6351 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6352 if (pi != null) { 6353 list.add(pi); 6354 } 6355 } 6356 } 6357 6358 return new ParceledListSlice<PackageInfo>(list); 6359 } 6360 } 6361 6362 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6363 String[] permissions, boolean[] tmp, int flags, int userId) { 6364 int numMatch = 0; 6365 final PermissionsState permissionsState = ps.getPermissionsState(); 6366 for (int i=0; i<permissions.length; i++) { 6367 final String permission = permissions[i]; 6368 if (permissionsState.hasPermission(permission, userId)) { 6369 tmp[i] = true; 6370 numMatch++; 6371 } else { 6372 tmp[i] = false; 6373 } 6374 } 6375 if (numMatch == 0) { 6376 return; 6377 } 6378 final PackageInfo pi; 6379 if (ps.pkg != null) { 6380 pi = generatePackageInfo(ps, flags, userId); 6381 } else { 6382 pi = generatePackageInfo(ps, flags, userId); 6383 } 6384 // The above might return null in cases of uninstalled apps or install-state 6385 // skew across users/profiles. 6386 if (pi != null) { 6387 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6388 if (numMatch == permissions.length) { 6389 pi.requestedPermissions = permissions; 6390 } else { 6391 pi.requestedPermissions = new String[numMatch]; 6392 numMatch = 0; 6393 for (int i=0; i<permissions.length; i++) { 6394 if (tmp[i]) { 6395 pi.requestedPermissions[numMatch] = permissions[i]; 6396 numMatch++; 6397 } 6398 } 6399 } 6400 } 6401 list.add(pi); 6402 } 6403 } 6404 6405 @Override 6406 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6407 String[] permissions, int flags, int userId) { 6408 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6409 flags = updateFlagsForPackage(flags, userId, permissions); 6410 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6411 true /* requireFullPermission */, false /* checkShell */, 6412 "get packages holding permissions"); 6413 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6414 6415 // writer 6416 synchronized (mPackages) { 6417 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6418 boolean[] tmpBools = new boolean[permissions.length]; 6419 if (listUninstalled) { 6420 for (PackageSetting ps : mSettings.mPackages.values()) { 6421 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6422 userId); 6423 } 6424 } else { 6425 for (PackageParser.Package pkg : mPackages.values()) { 6426 PackageSetting ps = (PackageSetting)pkg.mExtras; 6427 if (ps != null) { 6428 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6429 userId); 6430 } 6431 } 6432 } 6433 6434 return new ParceledListSlice<PackageInfo>(list); 6435 } 6436 } 6437 6438 @Override 6439 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6440 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6441 flags = updateFlagsForApplication(flags, userId, null); 6442 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 6443 6444 // writer 6445 synchronized (mPackages) { 6446 ArrayList<ApplicationInfo> list; 6447 if (listUninstalled) { 6448 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6449 for (PackageSetting ps : mSettings.mPackages.values()) { 6450 ApplicationInfo ai; 6451 int effectiveFlags = flags; 6452 if (ps.isSystem()) { 6453 effectiveFlags |= PackageManager.MATCH_ANY_USER; 6454 } 6455 if (ps.pkg != null) { 6456 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 6457 ps.readUserState(userId), userId); 6458 } else { 6459 ai = generateApplicationInfoFromSettingsLPw(ps.name, effectiveFlags, 6460 userId); 6461 } 6462 if (ai != null) { 6463 list.add(ai); 6464 } 6465 } 6466 } else { 6467 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6468 for (PackageParser.Package p : mPackages.values()) { 6469 if (p.mExtras != null) { 6470 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6471 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6472 if (ai != null) { 6473 list.add(ai); 6474 } 6475 } 6476 } 6477 } 6478 6479 return new ParceledListSlice<ApplicationInfo>(list); 6480 } 6481 } 6482 6483 @Override 6484 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6485 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6486 return null; 6487 } 6488 6489 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6490 "getEphemeralApplications"); 6491 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6492 true /* requireFullPermission */, false /* checkShell */, 6493 "getEphemeralApplications"); 6494 synchronized (mPackages) { 6495 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6496 .getEphemeralApplicationsLPw(userId); 6497 if (ephemeralApps != null) { 6498 return new ParceledListSlice<>(ephemeralApps); 6499 } 6500 } 6501 return null; 6502 } 6503 6504 @Override 6505 public boolean isEphemeralApplication(String packageName, int userId) { 6506 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6507 true /* requireFullPermission */, false /* checkShell */, 6508 "isEphemeral"); 6509 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6510 return false; 6511 } 6512 6513 if (!isCallerSameApp(packageName)) { 6514 return false; 6515 } 6516 synchronized (mPackages) { 6517 PackageParser.Package pkg = mPackages.get(packageName); 6518 if (pkg != null) { 6519 return pkg.applicationInfo.isEphemeralApp(); 6520 } 6521 } 6522 return false; 6523 } 6524 6525 @Override 6526 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6527 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6528 return null; 6529 } 6530 6531 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6532 true /* requireFullPermission */, false /* checkShell */, 6533 "getCookie"); 6534 if (!isCallerSameApp(packageName)) { 6535 return null; 6536 } 6537 synchronized (mPackages) { 6538 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6539 packageName, userId); 6540 } 6541 } 6542 6543 @Override 6544 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6545 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6546 return true; 6547 } 6548 6549 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6550 true /* requireFullPermission */, true /* checkShell */, 6551 "setCookie"); 6552 if (!isCallerSameApp(packageName)) { 6553 return false; 6554 } 6555 synchronized (mPackages) { 6556 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6557 packageName, cookie, userId); 6558 } 6559 } 6560 6561 @Override 6562 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6563 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 6564 return null; 6565 } 6566 6567 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6568 "getEphemeralApplicationIcon"); 6569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6570 true /* requireFullPermission */, false /* checkShell */, 6571 "getEphemeralApplicationIcon"); 6572 synchronized (mPackages) { 6573 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6574 packageName, userId); 6575 } 6576 } 6577 6578 private boolean isCallerSameApp(String packageName) { 6579 PackageParser.Package pkg = mPackages.get(packageName); 6580 return pkg != null 6581 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6582 } 6583 6584 @Override 6585 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6586 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6587 } 6588 6589 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6590 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6591 6592 // reader 6593 synchronized (mPackages) { 6594 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6595 final int userId = UserHandle.getCallingUserId(); 6596 while (i.hasNext()) { 6597 final PackageParser.Package p = i.next(); 6598 if (p.applicationInfo == null) continue; 6599 6600 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6601 && !p.applicationInfo.isDirectBootAware(); 6602 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6603 && p.applicationInfo.isDirectBootAware(); 6604 6605 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6606 && (!mSafeMode || isSystemApp(p)) 6607 && (matchesUnaware || matchesAware)) { 6608 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6609 if (ps != null) { 6610 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6611 ps.readUserState(userId), userId); 6612 if (ai != null) { 6613 finalList.add(ai); 6614 } 6615 } 6616 } 6617 } 6618 } 6619 6620 return finalList; 6621 } 6622 6623 @Override 6624 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6625 if (!sUserManager.exists(userId)) return null; 6626 flags = updateFlagsForComponent(flags, userId, name); 6627 // reader 6628 synchronized (mPackages) { 6629 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6630 PackageSetting ps = provider != null 6631 ? mSettings.mPackages.get(provider.owner.packageName) 6632 : null; 6633 return ps != null 6634 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6635 ? PackageParser.generateProviderInfo(provider, flags, 6636 ps.readUserState(userId), userId) 6637 : null; 6638 } 6639 } 6640 6641 /** 6642 * @deprecated 6643 */ 6644 @Deprecated 6645 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6646 // reader 6647 synchronized (mPackages) { 6648 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6649 .entrySet().iterator(); 6650 final int userId = UserHandle.getCallingUserId(); 6651 while (i.hasNext()) { 6652 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6653 PackageParser.Provider p = entry.getValue(); 6654 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6655 6656 if (ps != null && p.syncable 6657 && (!mSafeMode || (p.info.applicationInfo.flags 6658 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6659 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6660 ps.readUserState(userId), userId); 6661 if (info != null) { 6662 outNames.add(entry.getKey()); 6663 outInfo.add(info); 6664 } 6665 } 6666 } 6667 } 6668 } 6669 6670 @Override 6671 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6672 int uid, int flags) { 6673 final int userId = processName != null ? UserHandle.getUserId(uid) 6674 : UserHandle.getCallingUserId(); 6675 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6676 flags = updateFlagsForComponent(flags, userId, processName); 6677 6678 ArrayList<ProviderInfo> finalList = null; 6679 // reader 6680 synchronized (mPackages) { 6681 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6682 while (i.hasNext()) { 6683 final PackageParser.Provider p = i.next(); 6684 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6685 if (ps != null && p.info.authority != null 6686 && (processName == null 6687 || (p.info.processName.equals(processName) 6688 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6689 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6690 if (finalList == null) { 6691 finalList = new ArrayList<ProviderInfo>(3); 6692 } 6693 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6694 ps.readUserState(userId), userId); 6695 if (info != null) { 6696 finalList.add(info); 6697 } 6698 } 6699 } 6700 } 6701 6702 if (finalList != null) { 6703 Collections.sort(finalList, mProviderInitOrderSorter); 6704 return new ParceledListSlice<ProviderInfo>(finalList); 6705 } 6706 6707 return ParceledListSlice.emptyList(); 6708 } 6709 6710 @Override 6711 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6712 // reader 6713 synchronized (mPackages) { 6714 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6715 return PackageParser.generateInstrumentationInfo(i, flags); 6716 } 6717 } 6718 6719 @Override 6720 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6721 String targetPackage, int flags) { 6722 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6723 } 6724 6725 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6726 int flags) { 6727 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6728 6729 // reader 6730 synchronized (mPackages) { 6731 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6732 while (i.hasNext()) { 6733 final PackageParser.Instrumentation p = i.next(); 6734 if (targetPackage == null 6735 || targetPackage.equals(p.info.targetPackage)) { 6736 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6737 flags); 6738 if (ii != null) { 6739 finalList.add(ii); 6740 } 6741 } 6742 } 6743 } 6744 6745 return finalList; 6746 } 6747 6748 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6749 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6750 if (overlays == null) { 6751 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6752 return; 6753 } 6754 for (PackageParser.Package opkg : overlays.values()) { 6755 // Not much to do if idmap fails: we already logged the error 6756 // and we certainly don't want to abort installation of pkg simply 6757 // because an overlay didn't fit properly. For these reasons, 6758 // ignore the return value of createIdmapForPackagePairLI. 6759 createIdmapForPackagePairLI(pkg, opkg); 6760 } 6761 } 6762 6763 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6764 PackageParser.Package opkg) { 6765 if (!opkg.mTrustedOverlay) { 6766 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6767 opkg.baseCodePath + ": overlay not trusted"); 6768 return false; 6769 } 6770 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6771 if (overlaySet == null) { 6772 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6773 opkg.baseCodePath + " but target package has no known overlays"); 6774 return false; 6775 } 6776 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6777 // TODO: generate idmap for split APKs 6778 try { 6779 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6780 } catch (InstallerException e) { 6781 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6782 + opkg.baseCodePath); 6783 return false; 6784 } 6785 PackageParser.Package[] overlayArray = 6786 overlaySet.values().toArray(new PackageParser.Package[0]); 6787 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6788 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6789 return p1.mOverlayPriority - p2.mOverlayPriority; 6790 } 6791 }; 6792 Arrays.sort(overlayArray, cmp); 6793 6794 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6795 int i = 0; 6796 for (PackageParser.Package p : overlayArray) { 6797 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6798 } 6799 return true; 6800 } 6801 6802 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6803 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + dir.getAbsolutePath() + "]"); 6804 try { 6805 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6806 } finally { 6807 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6808 } 6809 } 6810 6811 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6812 final File[] files = dir.listFiles(); 6813 if (ArrayUtils.isEmpty(files)) { 6814 Log.d(TAG, "No files in app dir " + dir); 6815 return; 6816 } 6817 6818 if (DEBUG_PACKAGE_SCANNING) { 6819 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6820 + " flags=0x" + Integer.toHexString(parseFlags)); 6821 } 6822 ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 6823 mSeparateProcesses, mOnlyCore, mMetrics); 6824 6825 // Submit files for parsing in parallel 6826 int fileCount = 0; 6827 for (File file : files) { 6828 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6829 && !PackageInstallerService.isStageName(file.getName()); 6830 if (!isPackage) { 6831 // Ignore entries which are not packages 6832 continue; 6833 } 6834 parallelPackageParser.submit(file, parseFlags); 6835 fileCount++; 6836 } 6837 6838 // Process results one by one 6839 for (; fileCount > 0; fileCount--) { 6840 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 6841 Throwable throwable = parseResult.throwable; 6842 int errorCode = PackageManager.INSTALL_SUCCEEDED; 6843 6844 if (throwable == null) { 6845 try { 6846 scanPackageLI(parseResult.pkg, parseResult.scanFile, parseFlags, scanFlags, 6847 currentTime, null); 6848 } catch (PackageManagerException e) { 6849 errorCode = e.error; 6850 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 6851 } 6852 } else if (throwable instanceof PackageParser.PackageParserException) { 6853 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 6854 throwable; 6855 errorCode = e.error; 6856 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 6857 } else { 6858 throw new IllegalStateException("Unexpected exception occurred while parsing " 6859 + parseResult.scanFile, throwable); 6860 } 6861 6862 // Delete invalid userdata apps 6863 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6864 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 6865 logCriticalInfo(Log.WARN, 6866 "Deleting invalid package at " + parseResult.scanFile); 6867 removeCodePathLI(parseResult.scanFile); 6868 } 6869 } 6870 parallelPackageParser.close(); 6871 } 6872 6873 private static File getSettingsProblemFile() { 6874 File dataDir = Environment.getDataDirectory(); 6875 File systemDir = new File(dataDir, "system"); 6876 File fname = new File(systemDir, "uiderrors.txt"); 6877 return fname; 6878 } 6879 6880 static void reportSettingsProblem(int priority, String msg) { 6881 logCriticalInfo(priority, msg); 6882 } 6883 6884 static void logCriticalInfo(int priority, String msg) { 6885 Slog.println(priority, TAG, msg); 6886 EventLogTags.writePmCriticalInfo(msg); 6887 try { 6888 File fname = getSettingsProblemFile(); 6889 FileOutputStream out = new FileOutputStream(fname, true); 6890 PrintWriter pw = new FastPrintWriter(out); 6891 SimpleDateFormat formatter = new SimpleDateFormat(); 6892 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6893 pw.println(dateString + ": " + msg); 6894 pw.close(); 6895 FileUtils.setPermissions( 6896 fname.toString(), 6897 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6898 -1, -1); 6899 } catch (java.io.IOException e) { 6900 } 6901 } 6902 6903 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6904 if (srcFile.isDirectory()) { 6905 final File baseFile = new File(pkg.baseCodePath); 6906 long maxModifiedTime = baseFile.lastModified(); 6907 if (pkg.splitCodePaths != null) { 6908 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6909 final File splitFile = new File(pkg.splitCodePaths[i]); 6910 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6911 } 6912 } 6913 return maxModifiedTime; 6914 } 6915 return srcFile.lastModified(); 6916 } 6917 6918 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6919 final int policyFlags) throws PackageManagerException { 6920 // When upgrading from pre-N MR1, verify the package time stamp using the package 6921 // directory and not the APK file. 6922 final long lastModifiedTime = mIsPreNMR1Upgrade 6923 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg, srcFile); 6924 if (ps != null 6925 && ps.codePath.equals(srcFile) 6926 && ps.timeStamp == lastModifiedTime 6927 && !isCompatSignatureUpdateNeeded(pkg) 6928 && !isRecoverSignatureUpdateNeeded(pkg)) { 6929 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6930 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6931 ArraySet<PublicKey> signingKs; 6932 synchronized (mPackages) { 6933 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6934 } 6935 if (ps.signatures.mSignatures != null 6936 && ps.signatures.mSignatures.length != 0 6937 && signingKs != null) { 6938 // Optimization: reuse the existing cached certificates 6939 // if the package appears to be unchanged. 6940 pkg.mSignatures = ps.signatures.mSignatures; 6941 pkg.mSigningKeys = signingKs; 6942 return; 6943 } 6944 6945 Slog.w(TAG, "PackageSetting for " + ps.name 6946 + " is missing signatures. Collecting certs again to recover them."); 6947 } else { 6948 Slog.i(TAG, srcFile.toString() + " changed; collecting certs"); 6949 } 6950 6951 try { 6952 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 6953 PackageParser.collectCertificates(pkg, policyFlags); 6954 } catch (PackageParserException e) { 6955 throw PackageManagerException.from(e); 6956 } finally { 6957 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6958 } 6959 } 6960 6961 /** 6962 * Traces a package scan. 6963 * @see #scanPackageLI(File, int, int, long, UserHandle) 6964 */ 6965 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6966 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6967 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 6968 try { 6969 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6970 } finally { 6971 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6972 } 6973 } 6974 6975 /** 6976 * Scans a package and returns the newly parsed package. 6977 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6978 */ 6979 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6980 long currentTime, UserHandle user) throws PackageManagerException { 6981 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6982 PackageParser pp = new PackageParser(); 6983 pp.setSeparateProcesses(mSeparateProcesses); 6984 pp.setOnlyCoreApps(mOnlyCore); 6985 pp.setDisplayMetrics(mMetrics); 6986 6987 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6988 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6989 } 6990 6991 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6992 final PackageParser.Package pkg; 6993 try { 6994 pkg = pp.parsePackage(scanFile, parseFlags); 6995 } catch (PackageParserException e) { 6996 throw PackageManagerException.from(e); 6997 } finally { 6998 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6999 } 7000 7001 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 7002 } 7003 7004 /** 7005 * Scans a package and returns the newly parsed package. 7006 * @throws PackageManagerException on a parse error. 7007 */ 7008 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 7009 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7010 throws PackageManagerException { 7011 // If the package has children and this is the first dive in the function 7012 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 7013 // packages (parent and children) would be successfully scanned before the 7014 // actual scan since scanning mutates internal state and we want to atomically 7015 // install the package and its children. 7016 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7017 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7018 scanFlags |= SCAN_CHECK_ONLY; 7019 } 7020 } else { 7021 scanFlags &= ~SCAN_CHECK_ONLY; 7022 } 7023 7024 // Scan the parent 7025 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 7026 scanFlags, currentTime, user); 7027 7028 // Scan the children 7029 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7030 for (int i = 0; i < childCount; i++) { 7031 PackageParser.Package childPackage = pkg.childPackages.get(i); 7032 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 7033 currentTime, user); 7034 } 7035 7036 7037 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7038 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 7039 } 7040 7041 return scannedPkg; 7042 } 7043 7044 /** 7045 * Scans a package and returns the newly parsed package. 7046 * @throws PackageManagerException on a parse error. 7047 */ 7048 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 7049 int policyFlags, int scanFlags, long currentTime, UserHandle user) 7050 throws PackageManagerException { 7051 PackageSetting ps = null; 7052 PackageSetting updatedPkg; 7053 // reader 7054 synchronized (mPackages) { 7055 // Look to see if we already know about this package. 7056 String oldName = mSettings.getRenamedPackageLPr(pkg.packageName); 7057 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 7058 // This package has been renamed to its original name. Let's 7059 // use that. 7060 ps = mSettings.getPackageLPr(oldName); 7061 } 7062 // If there was no original package, see one for the real package name. 7063 if (ps == null) { 7064 ps = mSettings.getPackageLPr(pkg.packageName); 7065 } 7066 // Check to see if this package could be hiding/updating a system 7067 // package. Must look for it either under the original or real 7068 // package name depending on our state. 7069 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 7070 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 7071 7072 // If this is a package we don't know about on the system partition, we 7073 // may need to remove disabled child packages on the system partition 7074 // or may need to not add child packages if the parent apk is updated 7075 // on the data partition and no longer defines this child package. 7076 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7077 // If this is a parent package for an updated system app and this system 7078 // app got an OTA update which no longer defines some of the child packages 7079 // we have to prune them from the disabled system packages. 7080 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 7081 if (disabledPs != null) { 7082 final int scannedChildCount = (pkg.childPackages != null) 7083 ? pkg.childPackages.size() : 0; 7084 final int disabledChildCount = disabledPs.childPackageNames != null 7085 ? disabledPs.childPackageNames.size() : 0; 7086 for (int i = 0; i < disabledChildCount; i++) { 7087 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 7088 boolean disabledPackageAvailable = false; 7089 for (int j = 0; j < scannedChildCount; j++) { 7090 PackageParser.Package childPkg = pkg.childPackages.get(j); 7091 if (childPkg.packageName.equals(disabledChildPackageName)) { 7092 disabledPackageAvailable = true; 7093 break; 7094 } 7095 } 7096 if (!disabledPackageAvailable) { 7097 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 7098 } 7099 } 7100 } 7101 } 7102 } 7103 7104 boolean updatedPkgBetter = false; 7105 // First check if this is a system package that may involve an update 7106 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 7107 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 7108 // it needs to drop FLAG_PRIVILEGED. 7109 if (locationIsPrivileged(scanFile)) { 7110 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7111 } else { 7112 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7113 } 7114 7115 if (ps != null && !ps.codePath.equals(scanFile)) { 7116 // The path has changed from what was last scanned... check the 7117 // version of the new path against what we have stored to determine 7118 // what to do. 7119 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7120 if (pkg.mVersionCode <= ps.versionCode) { 7121 // The system package has been updated and the code path does not match 7122 // Ignore entry. Skip it. 7123 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7124 + " ignored: updated version " + ps.versionCode 7125 + " better than this " + pkg.mVersionCode); 7126 if (!updatedPkg.codePath.equals(scanFile)) { 7127 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7128 + ps.name + " changing from " + updatedPkg.codePathString 7129 + " to " + scanFile); 7130 updatedPkg.codePath = scanFile; 7131 updatedPkg.codePathString = scanFile.toString(); 7132 updatedPkg.resourcePath = scanFile; 7133 updatedPkg.resourcePathString = scanFile.toString(); 7134 } 7135 updatedPkg.pkg = pkg; 7136 updatedPkg.versionCode = pkg.mVersionCode; 7137 7138 // Update the disabled system child packages to point to the package too. 7139 final int childCount = updatedPkg.childPackageNames != null 7140 ? updatedPkg.childPackageNames.size() : 0; 7141 for (int i = 0; i < childCount; i++) { 7142 String childPackageName = updatedPkg.childPackageNames.get(i); 7143 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7144 childPackageName); 7145 if (updatedChildPkg != null) { 7146 updatedChildPkg.pkg = pkg; 7147 updatedChildPkg.versionCode = pkg.mVersionCode; 7148 } 7149 } 7150 7151 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7152 + scanFile + " ignored: updated version " + ps.versionCode 7153 + " better than this " + pkg.mVersionCode); 7154 } else { 7155 // The current app on the system partition is better than 7156 // what we have updated to on the data partition; switch 7157 // back to the system partition version. 7158 // At this point, its safely assumed that package installation for 7159 // apps in system partition will go through. If not there won't be a working 7160 // version of the app 7161 // writer 7162 synchronized (mPackages) { 7163 // Just remove the loaded entries from package lists. 7164 mPackages.remove(ps.name); 7165 } 7166 7167 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7168 + " reverting from " + ps.codePathString 7169 + ": new version " + pkg.mVersionCode 7170 + " better than installed " + ps.versionCode); 7171 7172 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7173 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7174 synchronized (mInstallLock) { 7175 args.cleanUpResourcesLI(); 7176 } 7177 synchronized (mPackages) { 7178 mSettings.enableSystemPackageLPw(ps.name); 7179 } 7180 updatedPkgBetter = true; 7181 } 7182 } 7183 } 7184 7185 if (updatedPkg != null) { 7186 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7187 // initially 7188 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7189 7190 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7191 // flag set initially 7192 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7193 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7194 } 7195 } 7196 7197 // Verify certificates against what was last scanned 7198 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7199 7200 /* 7201 * A new system app appeared, but we already had a non-system one of the 7202 * same name installed earlier. 7203 */ 7204 boolean shouldHideSystemApp = false; 7205 if (updatedPkg == null && ps != null 7206 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7207 /* 7208 * Check to make sure the signatures match first. If they don't, 7209 * wipe the installed application and its data. 7210 */ 7211 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7212 != PackageManager.SIGNATURE_MATCH) { 7213 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7214 + " signatures don't match existing userdata copy; removing"); 7215 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7216 "scanPackageInternalLI")) { 7217 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7218 } 7219 ps = null; 7220 } else { 7221 /* 7222 * If the newly-added system app is an older version than the 7223 * already installed version, hide it. It will be scanned later 7224 * and re-added like an update. 7225 */ 7226 if (pkg.mVersionCode <= ps.versionCode) { 7227 shouldHideSystemApp = true; 7228 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7229 + " but new version " + pkg.mVersionCode + " better than installed " 7230 + ps.versionCode + "; hiding system"); 7231 } else { 7232 /* 7233 * The newly found system app is a newer version that the 7234 * one previously installed. Simply remove the 7235 * already-installed application and replace it with our own 7236 * while keeping the application data. 7237 */ 7238 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7239 + " reverting from " + ps.codePathString + ": new version " 7240 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7241 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7242 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7243 synchronized (mInstallLock) { 7244 args.cleanUpResourcesLI(); 7245 } 7246 } 7247 } 7248 } 7249 7250 // The apk is forward locked (not public) if its code and resources 7251 // are kept in different files. (except for app in either system or 7252 // vendor path). 7253 // TODO grab this value from PackageSettings 7254 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7255 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7256 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7257 } 7258 } 7259 7260 // TODO: extend to support forward-locked splits 7261 String resourcePath = null; 7262 String baseResourcePath = null; 7263 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7264 if (ps != null && ps.resourcePathString != null) { 7265 resourcePath = ps.resourcePathString; 7266 baseResourcePath = ps.resourcePathString; 7267 } else { 7268 // Should not happen at all. Just log an error. 7269 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7270 } 7271 } else { 7272 resourcePath = pkg.codePath; 7273 baseResourcePath = pkg.baseCodePath; 7274 } 7275 7276 // Set application objects path explicitly. 7277 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7278 pkg.setApplicationInfoCodePath(pkg.codePath); 7279 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7280 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7281 pkg.setApplicationInfoResourcePath(resourcePath); 7282 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7283 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7284 7285 // Note that we invoke the following method only if we are about to unpack an application 7286 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7287 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7288 7289 /* 7290 * If the system app should be overridden by a previously installed 7291 * data, hide the system app now and let the /data/app scan pick it up 7292 * again. 7293 */ 7294 if (shouldHideSystemApp) { 7295 synchronized (mPackages) { 7296 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7297 } 7298 } 7299 7300 return scannedPkg; 7301 } 7302 7303 private static String fixProcessName(String defProcessName, 7304 String processName) { 7305 if (processName == null) { 7306 return defProcessName; 7307 } 7308 return processName; 7309 } 7310 7311 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7312 throws PackageManagerException { 7313 if (pkgSetting.signatures.mSignatures != null) { 7314 // Already existing package. Make sure signatures match 7315 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7316 == PackageManager.SIGNATURE_MATCH; 7317 if (!match) { 7318 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7319 == PackageManager.SIGNATURE_MATCH; 7320 } 7321 if (!match) { 7322 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7323 == PackageManager.SIGNATURE_MATCH; 7324 } 7325 if (!match) { 7326 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7327 + pkg.packageName + " signatures do not match the " 7328 + "previously installed version; ignoring!"); 7329 } 7330 } 7331 7332 // Check for shared user signatures 7333 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7334 // Already existing package. Make sure signatures match 7335 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7336 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7337 if (!match) { 7338 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7339 == PackageManager.SIGNATURE_MATCH; 7340 } 7341 if (!match) { 7342 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7343 == PackageManager.SIGNATURE_MATCH; 7344 } 7345 if (!match) { 7346 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7347 "Package " + pkg.packageName 7348 + " has no signatures that match those in shared user " 7349 + pkgSetting.sharedUser.name + "; ignoring!"); 7350 } 7351 } 7352 } 7353 7354 /** 7355 * Enforces that only the system UID or root's UID can call a method exposed 7356 * via Binder. 7357 * 7358 * @param message used as message if SecurityException is thrown 7359 * @throws SecurityException if the caller is not system or root 7360 */ 7361 private static final void enforceSystemOrRoot(String message) { 7362 final int uid = Binder.getCallingUid(); 7363 if (uid != Process.SYSTEM_UID && uid != 0) { 7364 throw new SecurityException(message); 7365 } 7366 } 7367 7368 @Override 7369 public void performFstrimIfNeeded() { 7370 enforceSystemOrRoot("Only the system can request fstrim"); 7371 7372 // Before everything else, see whether we need to fstrim. 7373 try { 7374 IStorageManager sm = PackageHelper.getStorageManager(); 7375 if (sm != null) { 7376 boolean doTrim = false; 7377 final long interval = android.provider.Settings.Global.getLong( 7378 mContext.getContentResolver(), 7379 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7380 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7381 if (interval > 0) { 7382 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 7383 if (timeSinceLast > interval) { 7384 doTrim = true; 7385 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7386 + "; running immediately"); 7387 } 7388 } 7389 if (doTrim) { 7390 final boolean dexOptDialogShown; 7391 synchronized (mPackages) { 7392 dexOptDialogShown = mDexOptDialogShown; 7393 } 7394 if (!isFirstBoot() && dexOptDialogShown) { 7395 try { 7396 ActivityManager.getService().showBootMessage( 7397 mContext.getResources().getString( 7398 R.string.android_upgrading_fstrim), true); 7399 } catch (RemoteException e) { 7400 } 7401 } 7402 sm.runMaintenance(); 7403 } 7404 } else { 7405 Slog.e(TAG, "storageManager service unavailable!"); 7406 } 7407 } catch (RemoteException e) { 7408 // Can't happen; StorageManagerService is local 7409 } 7410 } 7411 7412 @Override 7413 public void updatePackagesIfNeeded() { 7414 enforceSystemOrRoot("Only the system can request package update"); 7415 7416 // We need to re-extract after an OTA. 7417 boolean causeUpgrade = isUpgrade(); 7418 7419 // First boot or factory reset. 7420 // Note: we also handle devices that are upgrading to N right now as if it is their 7421 // first boot, as they do not have profile data. 7422 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7423 7424 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7425 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7426 7427 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7428 return; 7429 } 7430 7431 List<PackageParser.Package> pkgs; 7432 synchronized (mPackages) { 7433 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7434 } 7435 7436 final long startTime = System.nanoTime(); 7437 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7438 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7439 7440 final int elapsedTimeSeconds = 7441 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7442 7443 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7444 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7445 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7446 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7447 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7448 } 7449 7450 /** 7451 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7452 * containing statistics about the invocation. The array consists of three elements, 7453 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7454 * and {@code numberOfPackagesFailed}. 7455 */ 7456 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7457 String compilerFilter) { 7458 7459 int numberOfPackagesVisited = 0; 7460 int numberOfPackagesOptimized = 0; 7461 int numberOfPackagesSkipped = 0; 7462 int numberOfPackagesFailed = 0; 7463 final int numberOfPackagesToDexopt = pkgs.size(); 7464 7465 for (PackageParser.Package pkg : pkgs) { 7466 numberOfPackagesVisited++; 7467 7468 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7469 if (DEBUG_DEXOPT) { 7470 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7471 } 7472 numberOfPackagesSkipped++; 7473 continue; 7474 } 7475 7476 if (DEBUG_DEXOPT) { 7477 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7478 numberOfPackagesToDexopt + ": " + pkg.packageName); 7479 } 7480 7481 if (showDialog) { 7482 try { 7483 ActivityManager.getService().showBootMessage( 7484 mContext.getResources().getString(R.string.android_upgrading_apk, 7485 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7486 } catch (RemoteException e) { 7487 } 7488 synchronized (mPackages) { 7489 mDexOptDialogShown = true; 7490 } 7491 } 7492 7493 // If the OTA updates a system app which was previously preopted to a non-preopted state 7494 // the app might end up being verified at runtime. That's because by default the apps 7495 // are verify-profile but for preopted apps there's no profile. 7496 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7497 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7498 // filter (by default interpret-only). 7499 // Note that at this stage unused apps are already filtered. 7500 if (isSystemApp(pkg) && 7501 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7502 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7503 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7504 } 7505 7506 // If the OTA updates a system app which was previously preopted to a non-preopted state 7507 // the app might end up being verified at runtime. That's because by default the apps 7508 // are verify-profile but for preopted apps there's no profile. 7509 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7510 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7511 // filter (by default interpret-only). 7512 // Note that at this stage unused apps are already filtered. 7513 if (isSystemApp(pkg) && 7514 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7515 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7516 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7517 } 7518 7519 // checkProfiles is false to avoid merging profiles during boot which 7520 // might interfere with background compilation (b/28612421). 7521 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7522 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7523 // trade-off worth doing to save boot time work. 7524 int dexOptStatus = performDexOptTraced(pkg.packageName, 7525 false /* checkProfiles */, 7526 compilerFilter, 7527 false /* force */); 7528 switch (dexOptStatus) { 7529 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7530 numberOfPackagesOptimized++; 7531 break; 7532 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7533 numberOfPackagesSkipped++; 7534 break; 7535 case PackageDexOptimizer.DEX_OPT_FAILED: 7536 numberOfPackagesFailed++; 7537 break; 7538 default: 7539 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7540 break; 7541 } 7542 } 7543 7544 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7545 numberOfPackagesFailed }; 7546 } 7547 7548 @Override 7549 public void notifyPackageUse(String packageName, int reason) { 7550 synchronized (mPackages) { 7551 PackageParser.Package p = mPackages.get(packageName); 7552 if (p == null) { 7553 return; 7554 } 7555 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7556 } 7557 } 7558 7559 // TODO: this is not used nor needed. Delete it. 7560 @Override 7561 public boolean performDexOptIfNeeded(String packageName) { 7562 int dexOptStatus = performDexOptTraced(packageName, 7563 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7564 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7565 } 7566 7567 @Override 7568 public boolean performDexOpt(String packageName, 7569 boolean checkProfiles, int compileReason, boolean force) { 7570 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7571 getCompilerFilterForReason(compileReason), force); 7572 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7573 } 7574 7575 @Override 7576 public boolean performDexOptMode(String packageName, 7577 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7578 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7579 targetCompilerFilter, force); 7580 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7581 } 7582 7583 private int performDexOptTraced(String packageName, 7584 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7585 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7586 try { 7587 return performDexOptInternal(packageName, checkProfiles, 7588 targetCompilerFilter, force); 7589 } finally { 7590 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7591 } 7592 } 7593 7594 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7595 // if the package can now be considered up to date for the given filter. 7596 private int performDexOptInternal(String packageName, 7597 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7598 PackageParser.Package p; 7599 synchronized (mPackages) { 7600 p = mPackages.get(packageName); 7601 if (p == null) { 7602 // Package could not be found. Report failure. 7603 return PackageDexOptimizer.DEX_OPT_FAILED; 7604 } 7605 mPackageUsage.maybeWriteAsync(mPackages); 7606 mCompilerStats.maybeWriteAsync(); 7607 } 7608 long callingId = Binder.clearCallingIdentity(); 7609 try { 7610 synchronized (mInstallLock) { 7611 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7612 targetCompilerFilter, force); 7613 } 7614 } finally { 7615 Binder.restoreCallingIdentity(callingId); 7616 } 7617 } 7618 7619 public ArraySet<String> getOptimizablePackages() { 7620 ArraySet<String> pkgs = new ArraySet<String>(); 7621 synchronized (mPackages) { 7622 for (PackageParser.Package p : mPackages.values()) { 7623 if (PackageDexOptimizer.canOptimizePackage(p)) { 7624 pkgs.add(p.packageName); 7625 } 7626 } 7627 } 7628 return pkgs; 7629 } 7630 7631 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7632 boolean checkProfiles, String targetCompilerFilter, 7633 boolean force) { 7634 // Select the dex optimizer based on the force parameter. 7635 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7636 // allocate an object here. 7637 PackageDexOptimizer pdo = force 7638 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7639 : mPackageDexOptimizer; 7640 7641 // Optimize all dependencies first. Note: we ignore the return value and march on 7642 // on errors. 7643 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7644 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7645 if (!deps.isEmpty()) { 7646 for (PackageParser.Package depPackage : deps) { 7647 // TODO: Analyze and investigate if we (should) profile libraries. 7648 // Currently this will do a full compilation of the library by default. 7649 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7650 false /* checkProfiles */, 7651 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7652 getOrCreateCompilerPackageStats(depPackage)); 7653 } 7654 } 7655 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7656 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7657 } 7658 7659 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7660 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7661 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7662 Set<String> collectedNames = new HashSet<>(); 7663 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7664 7665 retValue.remove(p); 7666 7667 return retValue; 7668 } else { 7669 return Collections.emptyList(); 7670 } 7671 } 7672 7673 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7674 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7675 if (!collectedNames.contains(p.packageName)) { 7676 collectedNames.add(p.packageName); 7677 collected.add(p); 7678 7679 if (p.usesLibraries != null) { 7680 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7681 } 7682 if (p.usesOptionalLibraries != null) { 7683 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7684 collectedNames); 7685 } 7686 } 7687 } 7688 7689 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7690 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7691 for (String libName : libs) { 7692 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7693 if (libPkg != null) { 7694 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7695 } 7696 } 7697 } 7698 7699 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7700 synchronized (mPackages) { 7701 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7702 if (lib != null && lib.apk != null) { 7703 return mPackages.get(lib.apk); 7704 } 7705 } 7706 return null; 7707 } 7708 7709 public void shutdown() { 7710 mPackageUsage.writeNow(mPackages); 7711 mCompilerStats.writeNow(); 7712 } 7713 7714 @Override 7715 public void dumpProfiles(String packageName) { 7716 PackageParser.Package pkg; 7717 synchronized (mPackages) { 7718 pkg = mPackages.get(packageName); 7719 if (pkg == null) { 7720 throw new IllegalArgumentException("Unknown package: " + packageName); 7721 } 7722 } 7723 /* Only the shell, root, or the app user should be able to dump profiles. */ 7724 int callingUid = Binder.getCallingUid(); 7725 if (callingUid != Process.SHELL_UID && 7726 callingUid != Process.ROOT_UID && 7727 callingUid != pkg.applicationInfo.uid) { 7728 throw new SecurityException("dumpProfiles"); 7729 } 7730 7731 synchronized (mInstallLock) { 7732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7733 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7734 try { 7735 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7736 String gid = Integer.toString(sharedGid); 7737 String codePaths = TextUtils.join(";", allCodePaths); 7738 mInstaller.dumpProfiles(gid, packageName, codePaths); 7739 } catch (InstallerException e) { 7740 Slog.w(TAG, "Failed to dump profiles", e); 7741 } 7742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7743 } 7744 } 7745 7746 @Override 7747 public void forceDexOpt(String packageName) { 7748 enforceSystemOrRoot("forceDexOpt"); 7749 7750 PackageParser.Package pkg; 7751 synchronized (mPackages) { 7752 pkg = mPackages.get(packageName); 7753 if (pkg == null) { 7754 throw new IllegalArgumentException("Unknown package: " + packageName); 7755 } 7756 } 7757 7758 synchronized (mInstallLock) { 7759 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7760 7761 // Whoever is calling forceDexOpt wants a fully compiled package. 7762 // Don't use profiles since that may cause compilation to be skipped. 7763 final int res = performDexOptInternalWithDependenciesLI(pkg, 7764 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7765 true /* force */); 7766 7767 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7768 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7769 throw new IllegalStateException("Failed to dexopt: " + res); 7770 } 7771 } 7772 } 7773 7774 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7775 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7776 Slog.w(TAG, "Unable to update from " + oldPkg.name 7777 + " to " + newPkg.packageName 7778 + ": old package not in system partition"); 7779 return false; 7780 } else if (mPackages.get(oldPkg.name) != null) { 7781 Slog.w(TAG, "Unable to update from " + oldPkg.name 7782 + " to " + newPkg.packageName 7783 + ": old package still exists"); 7784 return false; 7785 } 7786 return true; 7787 } 7788 7789 void removeCodePathLI(File codePath) { 7790 if (codePath.isDirectory()) { 7791 try { 7792 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7793 } catch (InstallerException e) { 7794 Slog.w(TAG, "Failed to remove code path", e); 7795 } 7796 } else { 7797 codePath.delete(); 7798 } 7799 } 7800 7801 private int[] resolveUserIds(int userId) { 7802 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7803 } 7804 7805 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7806 if (pkg == null) { 7807 Slog.wtf(TAG, "Package was null!", new Throwable()); 7808 return; 7809 } 7810 clearAppDataLeafLIF(pkg, userId, flags); 7811 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7812 for (int i = 0; i < childCount; i++) { 7813 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7814 } 7815 } 7816 7817 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7818 final PackageSetting ps; 7819 synchronized (mPackages) { 7820 ps = mSettings.mPackages.get(pkg.packageName); 7821 } 7822 for (int realUserId : resolveUserIds(userId)) { 7823 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7824 try { 7825 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7826 ceDataInode); 7827 } catch (InstallerException e) { 7828 Slog.w(TAG, String.valueOf(e)); 7829 } 7830 } 7831 } 7832 7833 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7834 if (pkg == null) { 7835 Slog.wtf(TAG, "Package was null!", new Throwable()); 7836 return; 7837 } 7838 destroyAppDataLeafLIF(pkg, userId, flags); 7839 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7840 for (int i = 0; i < childCount; i++) { 7841 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7842 } 7843 } 7844 7845 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7846 final PackageSetting ps; 7847 synchronized (mPackages) { 7848 ps = mSettings.mPackages.get(pkg.packageName); 7849 } 7850 for (int realUserId : resolveUserIds(userId)) { 7851 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7852 try { 7853 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7854 ceDataInode); 7855 } catch (InstallerException e) { 7856 Slog.w(TAG, String.valueOf(e)); 7857 } 7858 } 7859 } 7860 7861 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7862 if (pkg == null) { 7863 Slog.wtf(TAG, "Package was null!", new Throwable()); 7864 return; 7865 } 7866 destroyAppProfilesLeafLIF(pkg); 7867 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7868 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7869 for (int i = 0; i < childCount; i++) { 7870 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7871 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7872 true /* removeBaseMarker */); 7873 } 7874 } 7875 7876 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7877 boolean removeBaseMarker) { 7878 if (pkg.isForwardLocked()) { 7879 return; 7880 } 7881 7882 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7883 try { 7884 path = PackageManagerServiceUtils.realpath(new File(path)); 7885 } catch (IOException e) { 7886 // TODO: Should we return early here ? 7887 Slog.w(TAG, "Failed to get canonical path", e); 7888 continue; 7889 } 7890 7891 final String useMarker = path.replace('/', '@'); 7892 for (int realUserId : resolveUserIds(userId)) { 7893 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7894 if (removeBaseMarker) { 7895 File foreignUseMark = new File(profileDir, useMarker); 7896 if (foreignUseMark.exists()) { 7897 if (!foreignUseMark.delete()) { 7898 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7899 + pkg.packageName); 7900 } 7901 } 7902 } 7903 7904 File[] markers = profileDir.listFiles(); 7905 if (markers != null) { 7906 final String searchString = "@" + pkg.packageName + "@"; 7907 // We also delete all markers that contain the package name we're 7908 // uninstalling. These are associated with secondary dex-files belonging 7909 // to the package. Reconstructing the path of these dex files is messy 7910 // in general. 7911 for (File marker : markers) { 7912 if (marker.getName().indexOf(searchString) > 0) { 7913 if (!marker.delete()) { 7914 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7915 + pkg.packageName); 7916 } 7917 } 7918 } 7919 } 7920 } 7921 } 7922 } 7923 7924 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7925 try { 7926 mInstaller.destroyAppProfiles(pkg.packageName); 7927 } catch (InstallerException e) { 7928 Slog.w(TAG, String.valueOf(e)); 7929 } 7930 } 7931 7932 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7933 if (pkg == null) { 7934 Slog.wtf(TAG, "Package was null!", new Throwable()); 7935 return; 7936 } 7937 clearAppProfilesLeafLIF(pkg); 7938 // We don't remove the base foreign use marker when clearing profiles because 7939 // we will rename it when the app is updated. Unlike the actual profile contents, 7940 // the foreign use marker is good across installs. 7941 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7942 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7943 for (int i = 0; i < childCount; i++) { 7944 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7945 } 7946 } 7947 7948 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7949 try { 7950 mInstaller.clearAppProfiles(pkg.packageName); 7951 } catch (InstallerException e) { 7952 Slog.w(TAG, String.valueOf(e)); 7953 } 7954 } 7955 7956 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7957 long lastUpdateTime) { 7958 // Set parent install/update time 7959 PackageSetting ps = (PackageSetting) pkg.mExtras; 7960 if (ps != null) { 7961 ps.firstInstallTime = firstInstallTime; 7962 ps.lastUpdateTime = lastUpdateTime; 7963 } 7964 // Set children install/update time 7965 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7966 for (int i = 0; i < childCount; i++) { 7967 PackageParser.Package childPkg = pkg.childPackages.get(i); 7968 ps = (PackageSetting) childPkg.mExtras; 7969 if (ps != null) { 7970 ps.firstInstallTime = firstInstallTime; 7971 ps.lastUpdateTime = lastUpdateTime; 7972 } 7973 } 7974 } 7975 7976 private void addSharedLibraryLPr(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7977 PackageParser.Package changingLib) { 7978 if (file.path != null) { 7979 usesLibraryFiles.add(file.path); 7980 return; 7981 } 7982 PackageParser.Package p = mPackages.get(file.apk); 7983 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7984 // If we are doing this while in the middle of updating a library apk, 7985 // then we need to make sure to use that new apk for determining the 7986 // dependencies here. (We haven't yet finished committing the new apk 7987 // to the package manager state.) 7988 if (p == null || p.packageName.equals(changingLib.packageName)) { 7989 p = changingLib; 7990 } 7991 } 7992 if (p != null) { 7993 usesLibraryFiles.addAll(p.getAllCodePaths()); 7994 } 7995 } 7996 7997 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 7998 PackageParser.Package changingLib) throws PackageManagerException { 7999 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 8000 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 8001 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 8002 for (int i=0; i<N; i++) { 8003 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 8004 if (file == null) { 8005 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 8006 "Package " + pkg.packageName + " requires unavailable shared library " 8007 + pkg.usesLibraries.get(i) + "; failing!"); 8008 } 8009 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8010 } 8011 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 8012 for (int i=0; i<N; i++) { 8013 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 8014 if (file == null) { 8015 Slog.w(TAG, "Package " + pkg.packageName 8016 + " desires unavailable shared library " 8017 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 8018 } else { 8019 addSharedLibraryLPr(usesLibraryFiles, file, changingLib); 8020 } 8021 } 8022 N = usesLibraryFiles.size(); 8023 if (N > 0) { 8024 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 8025 } else { 8026 pkg.usesLibraryFiles = null; 8027 } 8028 } 8029 } 8030 8031 private static boolean hasString(List<String> list, List<String> which) { 8032 if (list == null) { 8033 return false; 8034 } 8035 for (int i=list.size()-1; i>=0; i--) { 8036 for (int j=which.size()-1; j>=0; j--) { 8037 if (which.get(j).equals(list.get(i))) { 8038 return true; 8039 } 8040 } 8041 } 8042 return false; 8043 } 8044 8045 private void updateAllSharedLibrariesLPw() { 8046 for (PackageParser.Package pkg : mPackages.values()) { 8047 try { 8048 updateSharedLibrariesLPr(pkg, null); 8049 } catch (PackageManagerException e) { 8050 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8051 } 8052 } 8053 } 8054 8055 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 8056 PackageParser.Package changingPkg) { 8057 ArrayList<PackageParser.Package> res = null; 8058 for (PackageParser.Package pkg : mPackages.values()) { 8059 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 8060 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 8061 if (res == null) { 8062 res = new ArrayList<PackageParser.Package>(); 8063 } 8064 res.add(pkg); 8065 try { 8066 updateSharedLibrariesLPr(pkg, changingPkg); 8067 } catch (PackageManagerException e) { 8068 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 8069 } 8070 } 8071 } 8072 return res; 8073 } 8074 8075 /** 8076 * Derive the value of the {@code cpuAbiOverride} based on the provided 8077 * value and an optional stored value from the package settings. 8078 */ 8079 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 8080 String cpuAbiOverride = null; 8081 8082 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 8083 cpuAbiOverride = null; 8084 } else if (abiOverride != null) { 8085 cpuAbiOverride = abiOverride; 8086 } else if (settings != null) { 8087 cpuAbiOverride = settings.cpuAbiOverrideString; 8088 } 8089 8090 return cpuAbiOverride; 8091 } 8092 8093 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 8094 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 8095 throws PackageManagerException { 8096 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 8097 // If the package has children and this is the first dive in the function 8098 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 8099 // whether all packages (parent and children) would be successfully scanned 8100 // before the actual scan since scanning mutates internal state and we want 8101 // to atomically install the package and its children. 8102 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8103 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8104 scanFlags |= SCAN_CHECK_ONLY; 8105 } 8106 } else { 8107 scanFlags &= ~SCAN_CHECK_ONLY; 8108 } 8109 8110 final PackageParser.Package scannedPkg; 8111 try { 8112 // Scan the parent 8113 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 8114 // Scan the children 8115 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8116 for (int i = 0; i < childCount; i++) { 8117 PackageParser.Package childPkg = pkg.childPackages.get(i); 8118 scanPackageLI(childPkg, policyFlags, 8119 scanFlags, currentTime, user); 8120 } 8121 } finally { 8122 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8123 } 8124 8125 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8126 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 8127 } 8128 8129 return scannedPkg; 8130 } 8131 8132 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 8133 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8134 boolean success = false; 8135 try { 8136 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 8137 currentTime, user); 8138 success = true; 8139 return res; 8140 } finally { 8141 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8142 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8143 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8144 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8145 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8146 } 8147 } 8148 } 8149 8150 /** 8151 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8152 */ 8153 private static boolean apkHasCode(String fileName) { 8154 StrictJarFile jarFile = null; 8155 try { 8156 jarFile = new StrictJarFile(fileName, 8157 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8158 return jarFile.findEntry("classes.dex") != null; 8159 } catch (IOException ignore) { 8160 } finally { 8161 try { 8162 if (jarFile != null) { 8163 jarFile.close(); 8164 } 8165 } catch (IOException ignore) {} 8166 } 8167 return false; 8168 } 8169 8170 /** 8171 * Enforces code policy for the package. This ensures that if an APK has 8172 * declared hasCode="true" in its manifest that the APK actually contains 8173 * code. 8174 * 8175 * @throws PackageManagerException If bytecode could not be found when it should exist 8176 */ 8177 private static void assertCodePolicy(PackageParser.Package pkg) 8178 throws PackageManagerException { 8179 final boolean shouldHaveCode = 8180 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8181 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8182 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8183 "Package " + pkg.baseCodePath + " code is missing"); 8184 } 8185 8186 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8187 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8188 final boolean splitShouldHaveCode = 8189 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8190 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8191 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8192 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8193 } 8194 } 8195 } 8196 } 8197 8198 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8199 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8200 throws PackageManagerException { 8201 if (DEBUG_PACKAGE_SCANNING) { 8202 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8203 Log.d(TAG, "Scanning package " + pkg.packageName); 8204 } 8205 8206 applyPolicy(pkg, policyFlags); 8207 8208 assertPackageIsValid(pkg, policyFlags, scanFlags); 8209 8210 // Initialize package source and resource directories 8211 final File scanFile = new File(pkg.codePath); 8212 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8213 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8214 8215 SharedUserSetting suid = null; 8216 PackageSetting pkgSetting = null; 8217 8218 // Getting the package setting may have a side-effect, so if we 8219 // are only checking if scan would succeed, stash a copy of the 8220 // old setting to restore at the end. 8221 PackageSetting nonMutatedPs = null; 8222 8223 // We keep references to the derived CPU Abis from settings in oder to reuse 8224 // them in the case where we're not upgrading or booting for the first time. 8225 String primaryCpuAbiFromSettings = null; 8226 String secondaryCpuAbiFromSettings = null; 8227 8228 // writer 8229 synchronized (mPackages) { 8230 if (pkg.mSharedUserId != null) { 8231 // SIDE EFFECTS; may potentially allocate a new shared user 8232 suid = mSettings.getSharedUserLPw( 8233 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 8234 if (DEBUG_PACKAGE_SCANNING) { 8235 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8236 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8237 + "): packages=" + suid.packages); 8238 } 8239 } 8240 8241 // Check if we are renaming from an original package name. 8242 PackageSetting origPackage = null; 8243 String realName = null; 8244 if (pkg.mOriginalPackages != null) { 8245 // This package may need to be renamed to a previously 8246 // installed name. Let's check on that... 8247 final String renamed = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8248 if (pkg.mOriginalPackages.contains(renamed)) { 8249 // This package had originally been installed as the 8250 // original name, and we have already taken care of 8251 // transitioning to the new one. Just update the new 8252 // one to continue using the old name. 8253 realName = pkg.mRealPackage; 8254 if (!pkg.packageName.equals(renamed)) { 8255 // Callers into this function may have already taken 8256 // care of renaming the package; only do it here if 8257 // it is not already done. 8258 pkg.setPackageName(renamed); 8259 } 8260 } else { 8261 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8262 if ((origPackage = mSettings.getPackageLPr( 8263 pkg.mOriginalPackages.get(i))) != null) { 8264 // We do have the package already installed under its 8265 // original name... should we use it? 8266 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8267 // New package is not compatible with original. 8268 origPackage = null; 8269 continue; 8270 } else if (origPackage.sharedUser != null) { 8271 // Make sure uid is compatible between packages. 8272 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8273 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8274 + " to " + pkg.packageName + ": old uid " 8275 + origPackage.sharedUser.name 8276 + " differs from " + pkg.mSharedUserId); 8277 origPackage = null; 8278 continue; 8279 } 8280 // TODO: Add case when shared user id is added [b/28144775] 8281 } else { 8282 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8283 + pkg.packageName + " to old name " + origPackage.name); 8284 } 8285 break; 8286 } 8287 } 8288 } 8289 } 8290 8291 if (mTransferedPackages.contains(pkg.packageName)) { 8292 Slog.w(TAG, "Package " + pkg.packageName 8293 + " was transferred to another, but its .apk remains"); 8294 } 8295 8296 // See comments in nonMutatedPs declaration 8297 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8298 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8299 if (foundPs != null) { 8300 nonMutatedPs = new PackageSetting(foundPs); 8301 } 8302 } 8303 8304 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) == 0) { 8305 PackageSetting foundPs = mSettings.getPackageLPr(pkg.packageName); 8306 if (foundPs != null) { 8307 primaryCpuAbiFromSettings = foundPs.primaryCpuAbiString; 8308 secondaryCpuAbiFromSettings = foundPs.secondaryCpuAbiString; 8309 } 8310 } 8311 8312 pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8313 if (pkgSetting != null && pkgSetting.sharedUser != suid) { 8314 PackageManagerService.reportSettingsProblem(Log.WARN, 8315 "Package " + pkg.packageName + " shared user changed from " 8316 + (pkgSetting.sharedUser != null 8317 ? pkgSetting.sharedUser.name : "<nothing>") 8318 + " to " 8319 + (suid != null ? suid.name : "<nothing>") 8320 + "; replacing with new"); 8321 pkgSetting = null; 8322 } 8323 final PackageSetting oldPkgSetting = 8324 pkgSetting == null ? null : new PackageSetting(pkgSetting); 8325 final PackageSetting disabledPkgSetting = 8326 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8327 if (pkgSetting == null) { 8328 final String parentPackageName = (pkg.parentPackage != null) 8329 ? pkg.parentPackage.packageName : null; 8330 // REMOVE SharedUserSetting from method; update in a separate call 8331 pkgSetting = Settings.createNewSetting(pkg.packageName, origPackage, 8332 disabledPkgSetting, realName, suid, destCodeFile, destResourceFile, 8333 pkg.applicationInfo.nativeLibraryRootDir, pkg.applicationInfo.primaryCpuAbi, 8334 pkg.applicationInfo.secondaryCpuAbi, pkg.mVersionCode, 8335 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, user, 8336 true /*allowInstall*/, parentPackageName, pkg.getChildPackageNames(), 8337 UserManagerService.getInstance()); 8338 // SIDE EFFECTS; updates system state; move elsewhere 8339 if (origPackage != null) { 8340 mSettings.addRenamedPackageLPw(pkg.packageName, origPackage.name); 8341 } 8342 mSettings.addUserToSettingLPw(pkgSetting); 8343 } else { 8344 // REMOVE SharedUserSetting from method; update in a separate call. 8345 // 8346 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 8347 // secondaryCpuAbi are not known at this point so we always update them 8348 // to null here, only to reset them at a later point. 8349 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, suid, destCodeFile, 8350 pkg.applicationInfo.nativeLibraryDir, pkg.applicationInfo.primaryCpuAbi, 8351 pkg.applicationInfo.secondaryCpuAbi, pkg.applicationInfo.flags, 8352 pkg.applicationInfo.privateFlags, pkg.getChildPackageNames(), 8353 UserManagerService.getInstance()); 8354 } 8355 // SIDE EFFECTS; persists system state to files on disk; move elsewhere 8356 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 8357 8358 // SIDE EFFECTS; modifies system state; move elsewhere 8359 if (pkgSetting.origPackage != null) { 8360 // If we are first transitioning from an original package, 8361 // fix up the new package's name now. We need to do this after 8362 // looking up the package under its new name, so getPackageLP 8363 // can take care of fiddling things correctly. 8364 pkg.setPackageName(origPackage.name); 8365 8366 // File a report about this. 8367 String msg = "New package " + pkgSetting.realName 8368 + " renamed to replace old package " + pkgSetting.name; 8369 reportSettingsProblem(Log.WARN, msg); 8370 8371 // Make a note of it. 8372 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8373 mTransferedPackages.add(origPackage.name); 8374 } 8375 8376 // No longer need to retain this. 8377 pkgSetting.origPackage = null; 8378 } 8379 8380 // SIDE EFFECTS; modifies system state; move elsewhere 8381 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8382 // Make a note of it. 8383 mTransferedPackages.add(pkg.packageName); 8384 } 8385 8386 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8387 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8388 } 8389 8390 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8391 // Check all shared libraries and map to their actual file path. 8392 // We only do this here for apps not on a system dir, because those 8393 // are the only ones that can fail an install due to this. We 8394 // will take care of the system apps by updating all of their 8395 // library paths after the scan is done. 8396 updateSharedLibrariesLPr(pkg, null); 8397 } 8398 8399 if (mFoundPolicyFile) { 8400 SELinuxMMAC.assignSeinfoValue(pkg); 8401 } 8402 8403 pkg.applicationInfo.uid = pkgSetting.appId; 8404 pkg.mExtras = pkgSetting; 8405 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8406 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8407 // We just determined the app is signed correctly, so bring 8408 // over the latest parsed certs. 8409 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8410 } else { 8411 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8412 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8413 "Package " + pkg.packageName + " upgrade keys do not match the " 8414 + "previously installed version"); 8415 } else { 8416 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8417 String msg = "System package " + pkg.packageName 8418 + " signature changed; retaining data."; 8419 reportSettingsProblem(Log.WARN, msg); 8420 } 8421 } 8422 } else { 8423 try { 8424 // SIDE EFFECTS; compareSignaturesCompat() changes KeysetManagerService 8425 verifySignaturesLP(pkgSetting, pkg); 8426 // We just determined the app is signed correctly, so bring 8427 // over the latest parsed certs. 8428 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8429 } catch (PackageManagerException e) { 8430 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8431 throw e; 8432 } 8433 // The signature has changed, but this package is in the system 8434 // image... let's recover! 8435 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8436 // However... if this package is part of a shared user, but it 8437 // doesn't match the signature of the shared user, let's fail. 8438 // What this means is that you can't change the signatures 8439 // associated with an overall shared user, which doesn't seem all 8440 // that unreasonable. 8441 if (pkgSetting.sharedUser != null) { 8442 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8443 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8444 throw new PackageManagerException( 8445 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8446 "Signature mismatch for shared user: " 8447 + pkgSetting.sharedUser); 8448 } 8449 } 8450 // File a report about this. 8451 String msg = "System package " + pkg.packageName 8452 + " signature changed; retaining data."; 8453 reportSettingsProblem(Log.WARN, msg); 8454 } 8455 } 8456 8457 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8458 // This package wants to adopt ownership of permissions from 8459 // another package. 8460 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8461 final String origName = pkg.mAdoptPermissions.get(i); 8462 final PackageSetting orig = mSettings.getPackageLPr(origName); 8463 if (orig != null) { 8464 if (verifyPackageUpdateLPr(orig, pkg)) { 8465 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8466 + pkg.packageName); 8467 // SIDE EFFECTS; updates permissions system state; move elsewhere 8468 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8469 } 8470 } 8471 } 8472 } 8473 } 8474 8475 pkg.applicationInfo.processName = fixProcessName( 8476 pkg.applicationInfo.packageName, 8477 pkg.applicationInfo.processName); 8478 8479 if (pkg != mPlatformPackage) { 8480 // Get all of our default paths setup 8481 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8482 } 8483 8484 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8485 8486 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8487 if ((scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0) { 8488 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 8489 derivePackageAbi( 8490 pkg, scanFile, cpuAbiOverride, true /*extractLibs*/, mAppLib32InstallDir); 8491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8492 8493 // Some system apps still use directory structure for native libraries 8494 // in which case we might end up not detecting abi solely based on apk 8495 // structure. Try to detect abi based on directory structure. 8496 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8497 pkg.applicationInfo.primaryCpuAbi == null) { 8498 setBundledAppAbisAndRoots(pkg, pkgSetting); 8499 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8500 } 8501 } else { 8502 // This is not a first boot or an upgrade, don't bother deriving the 8503 // ABI during the scan. Instead, trust the value that was stored in the 8504 // package setting. 8505 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 8506 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 8507 8508 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8509 8510 if (DEBUG_ABI_SELECTION) { 8511 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 8512 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 8513 pkg.applicationInfo.secondaryCpuAbi); 8514 } 8515 } 8516 } else { 8517 if ((scanFlags & SCAN_MOVE) != 0) { 8518 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8519 // but we already have this packages package info in the PackageSetting. We just 8520 // use that and derive the native library path based on the new codepath. 8521 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8522 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8523 } 8524 8525 // Set native library paths again. For moves, the path will be updated based on the 8526 // ABIs we've determined above. For non-moves, the path will be updated based on the 8527 // ABIs we determined during compilation, but the path will depend on the final 8528 // package path (after the rename away from the stage path). 8529 setNativeLibraryPaths(pkg, mAppLib32InstallDir); 8530 } 8531 8532 // This is a special case for the "system" package, where the ABI is 8533 // dictated by the zygote configuration (and init.rc). We should keep track 8534 // of this ABI so that we can deal with "normal" applications that run under 8535 // the same UID correctly. 8536 if (mPlatformPackage == pkg) { 8537 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8538 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8539 } 8540 8541 // If there's a mismatch between the abi-override in the package setting 8542 // and the abiOverride specified for the install. Warn about this because we 8543 // would've already compiled the app without taking the package setting into 8544 // account. 8545 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8546 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8547 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8548 " for package " + pkg.packageName); 8549 } 8550 } 8551 8552 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8553 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8554 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8555 8556 // Copy the derived override back to the parsed package, so that we can 8557 // update the package settings accordingly. 8558 pkg.cpuAbiOverride = cpuAbiOverride; 8559 8560 if (DEBUG_ABI_SELECTION) { 8561 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8562 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8563 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8564 } 8565 8566 // Push the derived path down into PackageSettings so we know what to 8567 // clean up at uninstall time. 8568 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8569 8570 if (DEBUG_ABI_SELECTION) { 8571 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8572 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8573 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8574 } 8575 8576 // SIDE EFFECTS; removes DEX files from disk; move elsewhere 8577 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8578 // We don't do this here during boot because we can do it all 8579 // at once after scanning all existing packages. 8580 // 8581 // We also do this *before* we perform dexopt on this package, so that 8582 // we can avoid redundant dexopts, and also to make sure we've got the 8583 // code and package path correct. 8584 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 8585 } 8586 8587 if (mFactoryTest && pkg.requestedPermissions.contains( 8588 android.Manifest.permission.FACTORY_TEST)) { 8589 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8590 } 8591 8592 if (isSystemApp(pkg)) { 8593 pkgSetting.isOrphaned = true; 8594 } 8595 8596 // Take care of first install / last update times. 8597 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8598 if (currentTime != 0) { 8599 if (pkgSetting.firstInstallTime == 0) { 8600 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8601 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 8602 pkgSetting.lastUpdateTime = currentTime; 8603 } 8604 } else if (pkgSetting.firstInstallTime == 0) { 8605 // We need *something*. Take time time stamp of the file. 8606 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8607 } else if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8608 if (scanFileTime != pkgSetting.timeStamp) { 8609 // A package on the system image has changed; consider this 8610 // to be an update. 8611 pkgSetting.lastUpdateTime = scanFileTime; 8612 } 8613 } 8614 pkgSetting.setTimeStamp(scanFileTime); 8615 8616 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8617 if (nonMutatedPs != null) { 8618 synchronized (mPackages) { 8619 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8620 } 8621 } 8622 } else { 8623 // Modify state for the given package setting 8624 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 8625 (policyFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 8626 } 8627 return pkg; 8628 } 8629 8630 /** 8631 * Applies policy to the parsed package based upon the given policy flags. 8632 * Ensures the package is in a good state. 8633 * <p> 8634 * Implementation detail: This method must NOT have any side effect. It would 8635 * ideally be static, but, it requires locks to read system state. 8636 */ 8637 private void applyPolicy(PackageParser.Package pkg, int policyFlags) { 8638 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8639 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8640 if (pkg.applicationInfo.isDirectBootAware()) { 8641 // we're direct boot aware; set for all components 8642 for (PackageParser.Service s : pkg.services) { 8643 s.info.encryptionAware = s.info.directBootAware = true; 8644 } 8645 for (PackageParser.Provider p : pkg.providers) { 8646 p.info.encryptionAware = p.info.directBootAware = true; 8647 } 8648 for (PackageParser.Activity a : pkg.activities) { 8649 a.info.encryptionAware = a.info.directBootAware = true; 8650 } 8651 for (PackageParser.Activity r : pkg.receivers) { 8652 r.info.encryptionAware = r.info.directBootAware = true; 8653 } 8654 } 8655 } else { 8656 // Only allow system apps to be flagged as core apps. 8657 pkg.coreApp = false; 8658 // clear flags not applicable to regular apps 8659 pkg.applicationInfo.privateFlags &= 8660 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8661 pkg.applicationInfo.privateFlags &= 8662 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8663 } 8664 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8665 8666 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8667 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8668 } 8669 8670 if (!isSystemApp(pkg)) { 8671 // Only system apps can use these features. 8672 pkg.mOriginalPackages = null; 8673 pkg.mRealPackage = null; 8674 pkg.mAdoptPermissions = null; 8675 } 8676 } 8677 8678 /** 8679 * Asserts the parsed package is valid according to teh given policy. If the 8680 * package is invalid, for whatever reason, throws {@link PackgeManagerException}. 8681 * <p> 8682 * Implementation detail: This method must NOT have any side effects. It would 8683 * ideally be static, but, it requires locks to read system state. 8684 * 8685 * @throws PackageManagerException If the package fails any of the validation checks 8686 */ 8687 private void assertPackageIsValid(PackageParser.Package pkg, int policyFlags, int scanFlags) 8688 throws PackageManagerException { 8689 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8690 assertCodePolicy(pkg); 8691 } 8692 8693 if (pkg.applicationInfo.getCodePath() == null || 8694 pkg.applicationInfo.getResourcePath() == null) { 8695 // Bail out. The resource and code paths haven't been set. 8696 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8697 "Code and resource paths haven't been set correctly"); 8698 } 8699 8700 // Make sure we're not adding any bogus keyset info 8701 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8702 ksms.assertScannedPackageValid(pkg); 8703 8704 synchronized (mPackages) { 8705 // The special "android" package can only be defined once 8706 if (pkg.packageName.equals("android")) { 8707 if (mAndroidApplication != null) { 8708 Slog.w(TAG, "*************************************************"); 8709 Slog.w(TAG, "Core android package being redefined. Skipping."); 8710 Slog.w(TAG, " codePath=" + pkg.codePath); 8711 Slog.w(TAG, "*************************************************"); 8712 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8713 "Core android package being redefined. Skipping."); 8714 } 8715 } 8716 8717 // A package name must be unique; don't allow duplicates 8718 if (mPackages.containsKey(pkg.packageName) 8719 || mSharedLibraries.containsKey(pkg.packageName)) { 8720 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8721 "Application package " + pkg.packageName 8722 + " already installed. Skipping duplicate."); 8723 } 8724 8725 // Only privileged apps and updated privileged apps can add child packages. 8726 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8727 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8728 throw new PackageManagerException("Only privileged apps can add child " 8729 + "packages. Ignoring package " + pkg.packageName); 8730 } 8731 final int childCount = pkg.childPackages.size(); 8732 for (int i = 0; i < childCount; i++) { 8733 PackageParser.Package childPkg = pkg.childPackages.get(i); 8734 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8735 childPkg.packageName)) { 8736 throw new PackageManagerException("Can't override child of " 8737 + "another disabled app. Ignoring package " + pkg.packageName); 8738 } 8739 } 8740 } 8741 8742 // If we're only installing presumed-existing packages, require that the 8743 // scanned APK is both already known and at the path previously established 8744 // for it. Previously unknown packages we pick up normally, but if we have an 8745 // a priori expectation about this package's install presence, enforce it. 8746 // With a singular exception for new system packages. When an OTA contains 8747 // a new system package, we allow the codepath to change from a system location 8748 // to the user-installed location. If we don't allow this change, any newer, 8749 // user-installed version of the application will be ignored. 8750 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8751 if (mExpectingBetter.containsKey(pkg.packageName)) { 8752 logCriticalInfo(Log.WARN, 8753 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8754 } else { 8755 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 8756 if (known != null) { 8757 if (DEBUG_PACKAGE_SCANNING) { 8758 Log.d(TAG, "Examining " + pkg.codePath 8759 + " and requiring known paths " + known.codePathString 8760 + " & " + known.resourcePathString); 8761 } 8762 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8763 || !pkg.applicationInfo.getResourcePath().equals( 8764 known.resourcePathString)) { 8765 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8766 "Application package " + pkg.packageName 8767 + " found at " + pkg.applicationInfo.getCodePath() 8768 + " but expected at " + known.codePathString 8769 + "; ignoring."); 8770 } 8771 } 8772 } 8773 } 8774 8775 // Verify that this new package doesn't have any content providers 8776 // that conflict with existing packages. Only do this if the 8777 // package isn't already installed, since we don't want to break 8778 // things that are installed. 8779 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8780 final int N = pkg.providers.size(); 8781 int i; 8782 for (i=0; i<N; i++) { 8783 PackageParser.Provider p = pkg.providers.get(i); 8784 if (p.info.authority != null) { 8785 String names[] = p.info.authority.split(";"); 8786 for (int j = 0; j < names.length; j++) { 8787 if (mProvidersByAuthority.containsKey(names[j])) { 8788 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8789 final String otherPackageName = 8790 ((other != null && other.getComponentName() != null) ? 8791 other.getComponentName().getPackageName() : "?"); 8792 throw new PackageManagerException( 8793 INSTALL_FAILED_CONFLICTING_PROVIDER, 8794 "Can't install because provider name " + names[j] 8795 + " (in package " + pkg.applicationInfo.packageName 8796 + ") is already used by " + otherPackageName); 8797 } 8798 } 8799 } 8800 } 8801 } 8802 } 8803 } 8804 8805 /** 8806 * Adds a scanned package to the system. When this method is finished, the package will 8807 * be available for query, resolution, etc... 8808 */ 8809 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 8810 UserHandle user, int scanFlags, boolean chatty) throws PackageManagerException { 8811 final String pkgName = pkg.packageName; 8812 if (mCustomResolverComponentName != null && 8813 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8814 setUpCustomResolverActivity(pkg); 8815 } 8816 8817 if (pkg.packageName.equals("android")) { 8818 synchronized (mPackages) { 8819 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8820 // Set up information for our fall-back user intent resolution activity. 8821 mPlatformPackage = pkg; 8822 pkg.mVersionCode = mSdkVersion; 8823 mAndroidApplication = pkg.applicationInfo; 8824 8825 if (!mResolverReplaced) { 8826 mResolveActivity.applicationInfo = mAndroidApplication; 8827 mResolveActivity.name = ResolverActivity.class.getName(); 8828 mResolveActivity.packageName = mAndroidApplication.packageName; 8829 mResolveActivity.processName = "system:ui"; 8830 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8831 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8832 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8833 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8834 mResolveActivity.exported = true; 8835 mResolveActivity.enabled = true; 8836 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8837 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8838 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8839 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8840 | ActivityInfo.CONFIG_ORIENTATION 8841 | ActivityInfo.CONFIG_KEYBOARD 8842 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8843 mResolveInfo.activityInfo = mResolveActivity; 8844 mResolveInfo.priority = 0; 8845 mResolveInfo.preferredOrder = 0; 8846 mResolveInfo.match = 0; 8847 mResolveComponentName = new ComponentName( 8848 mAndroidApplication.packageName, mResolveActivity.name); 8849 } 8850 } 8851 } 8852 } 8853 8854 ArrayList<PackageParser.Package> clientLibPkgs = null; 8855 // writer 8856 synchronized (mPackages) { 8857 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8858 // Only system apps can add new shared libraries. 8859 if (pkg.libraryNames != null) { 8860 for (int i=0; i<pkg.libraryNames.size(); i++) { 8861 String name = pkg.libraryNames.get(i); 8862 boolean allowed = false; 8863 if (pkg.isUpdatedSystemApp()) { 8864 // New library entries can only be added through the 8865 // system image. This is important to get rid of a lot 8866 // of nasty edge cases: for example if we allowed a non- 8867 // system update of the app to add a library, then uninstalling 8868 // the update would make the library go away, and assumptions 8869 // we made such as through app install filtering would now 8870 // have allowed apps on the device which aren't compatible 8871 // with it. Better to just have the restriction here, be 8872 // conservative, and create many fewer cases that can negatively 8873 // impact the user experience. 8874 final PackageSetting sysPs = mSettings 8875 .getDisabledSystemPkgLPr(pkg.packageName); 8876 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8877 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8878 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8879 allowed = true; 8880 break; 8881 } 8882 } 8883 } 8884 } else { 8885 allowed = true; 8886 } 8887 if (allowed) { 8888 if (!mSharedLibraries.containsKey(name)) { 8889 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8890 } else if (!name.equals(pkg.packageName)) { 8891 Slog.w(TAG, "Package " + pkg.packageName + " library " 8892 + name + " already exists; skipping"); 8893 } 8894 } else { 8895 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8896 + name + " that is not declared on system image; skipping"); 8897 } 8898 } 8899 if ((scanFlags & SCAN_BOOTING) == 0) { 8900 // If we are not booting, we need to update any applications 8901 // that are clients of our shared library. If we are booting, 8902 // this will all be done once the scan is complete. 8903 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8904 } 8905 } 8906 } 8907 } 8908 8909 if ((scanFlags & SCAN_BOOTING) != 0) { 8910 // No apps can run during boot scan, so they don't need to be frozen 8911 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8912 // Caller asked to not kill app, so it's probably not frozen 8913 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8914 // Caller asked us to ignore frozen check for some reason; they 8915 // probably didn't know the package name 8916 } else { 8917 // We're doing major surgery on this package, so it better be frozen 8918 // right now to keep it from launching 8919 checkPackageFrozen(pkgName); 8920 } 8921 8922 // Also need to kill any apps that are dependent on the library. 8923 if (clientLibPkgs != null) { 8924 for (int i=0; i<clientLibPkgs.size(); i++) { 8925 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8926 killApplication(clientPkg.applicationInfo.packageName, 8927 clientPkg.applicationInfo.uid, "update lib"); 8928 } 8929 } 8930 8931 // writer 8932 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8933 8934 boolean createIdmapFailed = false; 8935 synchronized (mPackages) { 8936 // We don't expect installation to fail beyond this point 8937 8938 if (pkgSetting.pkg != null) { 8939 // Note that |user| might be null during the initial boot scan. If a codePath 8940 // for an app has changed during a boot scan, it's due to an app update that's 8941 // part of the system partition and marker changes must be applied to all users. 8942 final int userId = ((user != null) ? user : UserHandle.ALL).getIdentifier(); 8943 final int[] userIds = resolveUserIds(userId); 8944 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, userIds); 8945 } 8946 8947 // Add the new setting to mSettings 8948 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8949 // Add the new setting to mPackages 8950 mPackages.put(pkg.applicationInfo.packageName, pkg); 8951 // Make sure we don't accidentally delete its data. 8952 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8953 while (iter.hasNext()) { 8954 PackageCleanItem item = iter.next(); 8955 if (pkgName.equals(item.packageName)) { 8956 iter.remove(); 8957 } 8958 } 8959 8960 // Add the package's KeySets to the global KeySetManagerService 8961 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8962 ksms.addScannedPackageLPw(pkg); 8963 8964 int N = pkg.providers.size(); 8965 StringBuilder r = null; 8966 int i; 8967 for (i=0; i<N; i++) { 8968 PackageParser.Provider p = pkg.providers.get(i); 8969 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8970 p.info.processName); 8971 mProviders.addProvider(p); 8972 p.syncable = p.info.isSyncable; 8973 if (p.info.authority != null) { 8974 String names[] = p.info.authority.split(";"); 8975 p.info.authority = null; 8976 for (int j = 0; j < names.length; j++) { 8977 if (j == 1 && p.syncable) { 8978 // We only want the first authority for a provider to possibly be 8979 // syncable, so if we already added this provider using a different 8980 // authority clear the syncable flag. We copy the provider before 8981 // changing it because the mProviders object contains a reference 8982 // to a provider that we don't want to change. 8983 // Only do this for the second authority since the resulting provider 8984 // object can be the same for all future authorities for this provider. 8985 p = new PackageParser.Provider(p); 8986 p.syncable = false; 8987 } 8988 if (!mProvidersByAuthority.containsKey(names[j])) { 8989 mProvidersByAuthority.put(names[j], p); 8990 if (p.info.authority == null) { 8991 p.info.authority = names[j]; 8992 } else { 8993 p.info.authority = p.info.authority + ";" + names[j]; 8994 } 8995 if (DEBUG_PACKAGE_SCANNING) { 8996 if (chatty) 8997 Log.d(TAG, "Registered content provider: " + names[j] 8998 + ", className = " + p.info.name + ", isSyncable = " 8999 + p.info.isSyncable); 9000 } 9001 } else { 9002 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 9003 Slog.w(TAG, "Skipping provider name " + names[j] + 9004 " (in package " + pkg.applicationInfo.packageName + 9005 "): name already used by " 9006 + ((other != null && other.getComponentName() != null) 9007 ? other.getComponentName().getPackageName() : "?")); 9008 } 9009 } 9010 } 9011 if (chatty) { 9012 if (r == null) { 9013 r = new StringBuilder(256); 9014 } else { 9015 r.append(' '); 9016 } 9017 r.append(p.info.name); 9018 } 9019 } 9020 if (r != null) { 9021 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 9022 } 9023 9024 N = pkg.services.size(); 9025 r = null; 9026 for (i=0; i<N; i++) { 9027 PackageParser.Service s = pkg.services.get(i); 9028 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 9029 s.info.processName); 9030 mServices.addService(s); 9031 if (chatty) { 9032 if (r == null) { 9033 r = new StringBuilder(256); 9034 } else { 9035 r.append(' '); 9036 } 9037 r.append(s.info.name); 9038 } 9039 } 9040 if (r != null) { 9041 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 9042 } 9043 9044 N = pkg.receivers.size(); 9045 r = null; 9046 for (i=0; i<N; i++) { 9047 PackageParser.Activity a = pkg.receivers.get(i); 9048 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9049 a.info.processName); 9050 mReceivers.addActivity(a, "receiver"); 9051 if (chatty) { 9052 if (r == null) { 9053 r = new StringBuilder(256); 9054 } else { 9055 r.append(' '); 9056 } 9057 r.append(a.info.name); 9058 } 9059 } 9060 if (r != null) { 9061 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 9062 } 9063 9064 N = pkg.activities.size(); 9065 r = null; 9066 for (i=0; i<N; i++) { 9067 PackageParser.Activity a = pkg.activities.get(i); 9068 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 9069 a.info.processName); 9070 mActivities.addActivity(a, "activity"); 9071 if (chatty) { 9072 if (r == null) { 9073 r = new StringBuilder(256); 9074 } else { 9075 r.append(' '); 9076 } 9077 r.append(a.info.name); 9078 } 9079 } 9080 if (r != null) { 9081 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 9082 } 9083 9084 N = pkg.permissionGroups.size(); 9085 r = null; 9086 for (i=0; i<N; i++) { 9087 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 9088 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 9089 final String curPackageName = cur == null ? null : cur.info.packageName; 9090 // Dont allow ephemeral apps to define new permission groups. 9091 if (pkg.applicationInfo.isEphemeralApp()) { 9092 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9093 + pg.info.packageName 9094 + " ignored: ephemeral apps cannot define new permission groups."); 9095 continue; 9096 } 9097 final boolean isPackageUpdate = pg.info.packageName.equals(curPackageName); 9098 if (cur == null || isPackageUpdate) { 9099 mPermissionGroups.put(pg.info.name, pg); 9100 if (chatty) { 9101 if (r == null) { 9102 r = new StringBuilder(256); 9103 } else { 9104 r.append(' '); 9105 } 9106 if (isPackageUpdate) { 9107 r.append("UPD:"); 9108 } 9109 r.append(pg.info.name); 9110 } 9111 } else { 9112 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 9113 + pg.info.packageName + " ignored: original from " 9114 + cur.info.packageName); 9115 if (chatty) { 9116 if (r == null) { 9117 r = new StringBuilder(256); 9118 } else { 9119 r.append(' '); 9120 } 9121 r.append("DUP:"); 9122 r.append(pg.info.name); 9123 } 9124 } 9125 } 9126 if (r != null) { 9127 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 9128 } 9129 9130 N = pkg.permissions.size(); 9131 r = null; 9132 for (i=0; i<N; i++) { 9133 PackageParser.Permission p = pkg.permissions.get(i); 9134 9135 // Dont allow ephemeral apps to define new permissions. 9136 if (pkg.applicationInfo.isEphemeralApp()) { 9137 Slog.w(TAG, "Permission " + p.info.name + " from package " 9138 + p.info.packageName 9139 + " ignored: ephemeral apps cannot define new permissions."); 9140 continue; 9141 } 9142 9143 // Assume by default that we did not install this permission into the system. 9144 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 9145 9146 // Now that permission groups have a special meaning, we ignore permission 9147 // groups for legacy apps to prevent unexpected behavior. In particular, 9148 // permissions for one app being granted to someone just becase they happen 9149 // to be in a group defined by another app (before this had no implications). 9150 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 9151 p.group = mPermissionGroups.get(p.info.group); 9152 // Warn for a permission in an unknown group. 9153 if (p.info.group != null && p.group == null) { 9154 Slog.w(TAG, "Permission " + p.info.name + " from package " 9155 + p.info.packageName + " in an unknown group " + p.info.group); 9156 } 9157 } 9158 9159 ArrayMap<String, BasePermission> permissionMap = 9160 p.tree ? mSettings.mPermissionTrees 9161 : mSettings.mPermissions; 9162 BasePermission bp = permissionMap.get(p.info.name); 9163 9164 // Allow system apps to redefine non-system permissions 9165 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 9166 final boolean currentOwnerIsSystem = (bp.perm != null 9167 && isSystemApp(bp.perm.owner)); 9168 if (isSystemApp(p.owner)) { 9169 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 9170 // It's a built-in permission and no owner, take ownership now 9171 bp.packageSetting = pkgSetting; 9172 bp.perm = p; 9173 bp.uid = pkg.applicationInfo.uid; 9174 bp.sourcePackage = p.info.packageName; 9175 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9176 } else if (!currentOwnerIsSystem) { 9177 String msg = "New decl " + p.owner + " of permission " 9178 + p.info.name + " is system; overriding " + bp.sourcePackage; 9179 reportSettingsProblem(Log.WARN, msg); 9180 bp = null; 9181 } 9182 } 9183 } 9184 9185 if (bp == null) { 9186 bp = new BasePermission(p.info.name, p.info.packageName, 9187 BasePermission.TYPE_NORMAL); 9188 permissionMap.put(p.info.name, bp); 9189 } 9190 9191 if (bp.perm == null) { 9192 if (bp.sourcePackage == null 9193 || bp.sourcePackage.equals(p.info.packageName)) { 9194 BasePermission tree = findPermissionTreeLP(p.info.name); 9195 if (tree == null 9196 || tree.sourcePackage.equals(p.info.packageName)) { 9197 bp.packageSetting = pkgSetting; 9198 bp.perm = p; 9199 bp.uid = pkg.applicationInfo.uid; 9200 bp.sourcePackage = p.info.packageName; 9201 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 9202 if (chatty) { 9203 if (r == null) { 9204 r = new StringBuilder(256); 9205 } else { 9206 r.append(' '); 9207 } 9208 r.append(p.info.name); 9209 } 9210 } else { 9211 Slog.w(TAG, "Permission " + p.info.name + " from package " 9212 + p.info.packageName + " ignored: base tree " 9213 + tree.name + " is from package " 9214 + tree.sourcePackage); 9215 } 9216 } else { 9217 Slog.w(TAG, "Permission " + p.info.name + " from package " 9218 + p.info.packageName + " ignored: original from " 9219 + bp.sourcePackage); 9220 } 9221 } else if (chatty) { 9222 if (r == null) { 9223 r = new StringBuilder(256); 9224 } else { 9225 r.append(' '); 9226 } 9227 r.append("DUP:"); 9228 r.append(p.info.name); 9229 } 9230 if (bp.perm == p) { 9231 bp.protectionLevel = p.info.protectionLevel; 9232 } 9233 } 9234 9235 if (r != null) { 9236 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 9237 } 9238 9239 N = pkg.instrumentation.size(); 9240 r = null; 9241 for (i=0; i<N; i++) { 9242 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9243 a.info.packageName = pkg.applicationInfo.packageName; 9244 a.info.sourceDir = pkg.applicationInfo.sourceDir; 9245 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 9246 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 9247 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 9248 a.info.dataDir = pkg.applicationInfo.dataDir; 9249 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 9250 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 9251 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 9252 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 9253 mInstrumentation.put(a.getComponentName(), a); 9254 if (chatty) { 9255 if (r == null) { 9256 r = new StringBuilder(256); 9257 } else { 9258 r.append(' '); 9259 } 9260 r.append(a.info.name); 9261 } 9262 } 9263 if (r != null) { 9264 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 9265 } 9266 9267 if (pkg.protectedBroadcasts != null) { 9268 N = pkg.protectedBroadcasts.size(); 9269 for (i=0; i<N; i++) { 9270 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9271 } 9272 } 9273 9274 // Create idmap files for pairs of (packages, overlay packages). 9275 // Note: "android", ie framework-res.apk, is handled by native layers. 9276 if (pkg.mOverlayTarget != null) { 9277 // This is an overlay package. 9278 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9279 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9280 mOverlays.put(pkg.mOverlayTarget, 9281 new ArrayMap<String, PackageParser.Package>()); 9282 } 9283 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9284 map.put(pkg.packageName, pkg); 9285 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9286 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9287 createIdmapFailed = true; 9288 } 9289 } 9290 } else if (mOverlays.containsKey(pkg.packageName) && 9291 !pkg.packageName.equals("android")) { 9292 // This is a regular package, with one or more known overlay packages. 9293 createIdmapsForPackageLI(pkg); 9294 } 9295 } 9296 9297 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9298 9299 if (createIdmapFailed) { 9300 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9301 "scanPackageLI failed to createIdmap"); 9302 } 9303 } 9304 9305 private static void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9306 PackageParser.Package update, int[] userIds) { 9307 if (existing.applicationInfo == null || update.applicationInfo == null) { 9308 // This isn't due to an app installation. 9309 return; 9310 } 9311 9312 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9313 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9314 9315 // The codePath hasn't changed, so there's nothing for us to do. 9316 if (Objects.equals(oldCodePath, newCodePath)) { 9317 return; 9318 } 9319 9320 File canonicalNewCodePath; 9321 try { 9322 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9323 } catch (IOException e) { 9324 Slog.w(TAG, "Failed to get canonical path.", e); 9325 return; 9326 } 9327 9328 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9329 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9330 // that the last component of the path (i.e, the name) doesn't need canonicalization 9331 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9332 // but may change in the future. Hopefully this function won't exist at that point. 9333 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9334 oldCodePath.getName()); 9335 9336 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9337 // with "@". 9338 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9339 if (!oldMarkerPrefix.endsWith("@")) { 9340 oldMarkerPrefix += "@"; 9341 } 9342 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9343 if (!newMarkerPrefix.endsWith("@")) { 9344 newMarkerPrefix += "@"; 9345 } 9346 9347 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9348 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9349 for (String updatedPath : updatedPaths) { 9350 String updatedPathName = new File(updatedPath).getName(); 9351 markerSuffixes.add(updatedPathName.replace('/', '@')); 9352 } 9353 9354 for (int userId : userIds) { 9355 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9356 9357 for (String markerSuffix : markerSuffixes) { 9358 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9359 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9360 if (oldForeignUseMark.exists()) { 9361 try { 9362 Os.rename(oldForeignUseMark.getAbsolutePath(), 9363 newForeignUseMark.getAbsolutePath()); 9364 } catch (ErrnoException e) { 9365 Slog.w(TAG, "Failed to rename foreign use marker", e); 9366 oldForeignUseMark.delete(); 9367 } 9368 } 9369 } 9370 } 9371 } 9372 9373 /** 9374 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9375 * is derived purely on the basis of the contents of {@code scanFile} and 9376 * {@code cpuAbiOverride}. 9377 * 9378 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9379 */ 9380 private static void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9381 String cpuAbiOverride, boolean extractLibs, 9382 File appLib32InstallDir) 9383 throws PackageManagerException { 9384 // Give ourselves some initial paths; we'll come back for another 9385 // pass once we've determined ABI below. 9386 setNativeLibraryPaths(pkg, appLib32InstallDir); 9387 9388 // We would never need to extract libs for forward-locked and external packages, 9389 // since the container service will do it for us. We shouldn't attempt to 9390 // extract libs from system app when it was not updated. 9391 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9392 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9393 extractLibs = false; 9394 } 9395 9396 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9397 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9398 9399 NativeLibraryHelper.Handle handle = null; 9400 try { 9401 handle = NativeLibraryHelper.Handle.create(pkg); 9402 // TODO(multiArch): This can be null for apps that didn't go through the 9403 // usual installation process. We can calculate it again, like we 9404 // do during install time. 9405 // 9406 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9407 // unnecessary. 9408 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9409 9410 // Null out the abis so that they can be recalculated. 9411 pkg.applicationInfo.primaryCpuAbi = null; 9412 pkg.applicationInfo.secondaryCpuAbi = null; 9413 if (isMultiArch(pkg.applicationInfo)) { 9414 // Warn if we've set an abiOverride for multi-lib packages.. 9415 // By definition, we need to copy both 32 and 64 bit libraries for 9416 // such packages. 9417 if (pkg.cpuAbiOverride != null 9418 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9419 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9420 } 9421 9422 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9423 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9424 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9425 if (extractLibs) { 9426 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9427 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9428 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9429 useIsaSpecificSubdirs); 9430 } else { 9431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9432 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9433 } 9434 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9435 } 9436 9437 maybeThrowExceptionForMultiArchCopy( 9438 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9439 9440 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9441 if (extractLibs) { 9442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9443 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9444 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9445 useIsaSpecificSubdirs); 9446 } else { 9447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9448 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9449 } 9450 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9451 } 9452 9453 maybeThrowExceptionForMultiArchCopy( 9454 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9455 9456 if (abi64 >= 0) { 9457 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9458 } 9459 9460 if (abi32 >= 0) { 9461 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9462 if (abi64 >= 0) { 9463 if (pkg.use32bitAbi) { 9464 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9465 pkg.applicationInfo.primaryCpuAbi = abi; 9466 } else { 9467 pkg.applicationInfo.secondaryCpuAbi = abi; 9468 } 9469 } else { 9470 pkg.applicationInfo.primaryCpuAbi = abi; 9471 } 9472 } 9473 9474 } else { 9475 String[] abiList = (cpuAbiOverride != null) ? 9476 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9477 9478 // Enable gross and lame hacks for apps that are built with old 9479 // SDK tools. We must scan their APKs for renderscript bitcode and 9480 // not launch them if it's present. Don't bother checking on devices 9481 // that don't have 64 bit support. 9482 boolean needsRenderScriptOverride = false; 9483 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9484 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9485 abiList = Build.SUPPORTED_32_BIT_ABIS; 9486 needsRenderScriptOverride = true; 9487 } 9488 9489 final int copyRet; 9490 if (extractLibs) { 9491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 9492 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9493 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9494 } else { 9495 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 9496 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9497 } 9498 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9499 9500 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9501 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9502 "Error unpackaging native libs for app, errorCode=" + copyRet); 9503 } 9504 9505 if (copyRet >= 0) { 9506 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9507 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9508 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9509 } else if (needsRenderScriptOverride) { 9510 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9511 } 9512 } 9513 } catch (IOException ioe) { 9514 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9515 } finally { 9516 IoUtils.closeQuietly(handle); 9517 } 9518 9519 // Now that we've calculated the ABIs and determined if it's an internal app, 9520 // we will go ahead and populate the nativeLibraryPath. 9521 setNativeLibraryPaths(pkg, appLib32InstallDir); 9522 } 9523 9524 /** 9525 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9526 * i.e, so that all packages can be run inside a single process if required. 9527 * 9528 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9529 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9530 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9531 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9532 * updating a package that belongs to a shared user. 9533 * 9534 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9535 * adds unnecessary complexity. 9536 */ 9537 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9538 PackageParser.Package scannedPackage) { 9539 String requiredInstructionSet = null; 9540 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9541 requiredInstructionSet = VMRuntime.getInstructionSet( 9542 scannedPackage.applicationInfo.primaryCpuAbi); 9543 } 9544 9545 PackageSetting requirer = null; 9546 for (PackageSetting ps : packagesForUser) { 9547 // If packagesForUser contains scannedPackage, we skip it. This will happen 9548 // when scannedPackage is an update of an existing package. Without this check, 9549 // we will never be able to change the ABI of any package belonging to a shared 9550 // user, even if it's compatible with other packages. 9551 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9552 if (ps.primaryCpuAbiString == null) { 9553 continue; 9554 } 9555 9556 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9557 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9558 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9559 // this but there's not much we can do. 9560 String errorMessage = "Instruction set mismatch, " 9561 + ((requirer == null) ? "[caller]" : requirer) 9562 + " requires " + requiredInstructionSet + " whereas " + ps 9563 + " requires " + instructionSet; 9564 Slog.w(TAG, errorMessage); 9565 } 9566 9567 if (requiredInstructionSet == null) { 9568 requiredInstructionSet = instructionSet; 9569 requirer = ps; 9570 } 9571 } 9572 } 9573 9574 if (requiredInstructionSet != null) { 9575 String adjustedAbi; 9576 if (requirer != null) { 9577 // requirer != null implies that either scannedPackage was null or that scannedPackage 9578 // did not require an ABI, in which case we have to adjust scannedPackage to match 9579 // the ABI of the set (which is the same as requirer's ABI) 9580 adjustedAbi = requirer.primaryCpuAbiString; 9581 if (scannedPackage != null) { 9582 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9583 } 9584 } else { 9585 // requirer == null implies that we're updating all ABIs in the set to 9586 // match scannedPackage. 9587 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9588 } 9589 9590 for (PackageSetting ps : packagesForUser) { 9591 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9592 if (ps.primaryCpuAbiString != null) { 9593 continue; 9594 } 9595 9596 ps.primaryCpuAbiString = adjustedAbi; 9597 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9598 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9599 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9600 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9601 + " (requirer=" 9602 + (requirer == null ? "null" : requirer.pkg.packageName) 9603 + ", scannedPackage=" 9604 + (scannedPackage != null ? scannedPackage.packageName : "null") 9605 + ")"); 9606 try { 9607 mInstaller.rmdex(ps.codePathString, 9608 getDexCodeInstructionSet(getPreferredInstructionSet())); 9609 } catch (InstallerException ignored) { 9610 } 9611 } 9612 } 9613 } 9614 } 9615 } 9616 9617 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9618 synchronized (mPackages) { 9619 mResolverReplaced = true; 9620 // Set up information for custom user intent resolution activity. 9621 mResolveActivity.applicationInfo = pkg.applicationInfo; 9622 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9623 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9624 mResolveActivity.processName = pkg.applicationInfo.packageName; 9625 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9626 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9627 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9628 mResolveActivity.theme = 0; 9629 mResolveActivity.exported = true; 9630 mResolveActivity.enabled = true; 9631 mResolveInfo.activityInfo = mResolveActivity; 9632 mResolveInfo.priority = 0; 9633 mResolveInfo.preferredOrder = 0; 9634 mResolveInfo.match = 0; 9635 mResolveComponentName = mCustomResolverComponentName; 9636 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9637 mResolveComponentName); 9638 } 9639 } 9640 9641 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9642 if (installerComponent == null) { 9643 if (DEBUG_EPHEMERAL) { 9644 Slog.d(TAG, "Clear ephemeral installer activity"); 9645 } 9646 mEphemeralInstallerActivity.applicationInfo = null; 9647 return; 9648 } 9649 9650 if (DEBUG_EPHEMERAL) { 9651 Slog.d(TAG, "Set ephemeral installer activity: " + installerComponent); 9652 } 9653 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9654 // Set up information for ephemeral installer activity 9655 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9656 mEphemeralInstallerActivity.name = installerComponent.getClassName(); 9657 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9658 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9659 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9660 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 9661 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9662 mEphemeralInstallerActivity.theme = 0; 9663 mEphemeralInstallerActivity.exported = true; 9664 mEphemeralInstallerActivity.enabled = true; 9665 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9666 mEphemeralInstallerInfo.priority = 0; 9667 mEphemeralInstallerInfo.preferredOrder = 1; 9668 mEphemeralInstallerInfo.isDefault = true; 9669 mEphemeralInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 9670 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 9671 } 9672 9673 private static String calculateBundledApkRoot(final String codePathString) { 9674 final File codePath = new File(codePathString); 9675 final File codeRoot; 9676 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9677 codeRoot = Environment.getRootDirectory(); 9678 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9679 codeRoot = Environment.getOemDirectory(); 9680 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9681 codeRoot = Environment.getVendorDirectory(); 9682 } else { 9683 // Unrecognized code path; take its top real segment as the apk root: 9684 // e.g. /something/app/blah.apk => /something 9685 try { 9686 File f = codePath.getCanonicalFile(); 9687 File parent = f.getParentFile(); // non-null because codePath is a file 9688 File tmp; 9689 while ((tmp = parent.getParentFile()) != null) { 9690 f = parent; 9691 parent = tmp; 9692 } 9693 codeRoot = f; 9694 Slog.w(TAG, "Unrecognized code path " 9695 + codePath + " - using " + codeRoot); 9696 } catch (IOException e) { 9697 // Can't canonicalize the code path -- shenanigans? 9698 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9699 return Environment.getRootDirectory().getPath(); 9700 } 9701 } 9702 return codeRoot.getPath(); 9703 } 9704 9705 /** 9706 * Derive and set the location of native libraries for the given package, 9707 * which varies depending on where and how the package was installed. 9708 */ 9709 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 9710 final ApplicationInfo info = pkg.applicationInfo; 9711 final String codePath = pkg.codePath; 9712 final File codeFile = new File(codePath); 9713 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9714 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9715 9716 info.nativeLibraryRootDir = null; 9717 info.nativeLibraryRootRequiresIsa = false; 9718 info.nativeLibraryDir = null; 9719 info.secondaryNativeLibraryDir = null; 9720 9721 if (isApkFile(codeFile)) { 9722 // Monolithic install 9723 if (bundledApp) { 9724 // If "/system/lib64/apkname" exists, assume that is the per-package 9725 // native library directory to use; otherwise use "/system/lib/apkname". 9726 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9727 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9728 getPrimaryInstructionSet(info)); 9729 9730 // This is a bundled system app so choose the path based on the ABI. 9731 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9732 // is just the default path. 9733 final String apkName = deriveCodePathName(codePath); 9734 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9735 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9736 apkName).getAbsolutePath(); 9737 9738 if (info.secondaryCpuAbi != null) { 9739 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9740 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9741 secondaryLibDir, apkName).getAbsolutePath(); 9742 } 9743 } else if (asecApp) { 9744 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9745 .getAbsolutePath(); 9746 } else { 9747 final String apkName = deriveCodePathName(codePath); 9748 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 9749 .getAbsolutePath(); 9750 } 9751 9752 info.nativeLibraryRootRequiresIsa = false; 9753 info.nativeLibraryDir = info.nativeLibraryRootDir; 9754 } else { 9755 // Cluster install 9756 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9757 info.nativeLibraryRootRequiresIsa = true; 9758 9759 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9760 getPrimaryInstructionSet(info)).getAbsolutePath(); 9761 9762 if (info.secondaryCpuAbi != null) { 9763 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9764 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9765 } 9766 } 9767 } 9768 9769 /** 9770 * Calculate the abis and roots for a bundled app. These can uniquely 9771 * be determined from the contents of the system partition, i.e whether 9772 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9773 * of this information, and instead assume that the system was built 9774 * sensibly. 9775 */ 9776 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9777 PackageSetting pkgSetting) { 9778 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9779 9780 // If "/system/lib64/apkname" exists, assume that is the per-package 9781 // native library directory to use; otherwise use "/system/lib/apkname". 9782 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9783 setBundledAppAbi(pkg, apkRoot, apkName); 9784 // pkgSetting might be null during rescan following uninstall of updates 9785 // to a bundled app, so accommodate that possibility. The settings in 9786 // that case will be established later from the parsed package. 9787 // 9788 // If the settings aren't null, sync them up with what we've just derived. 9789 // note that apkRoot isn't stored in the package settings. 9790 if (pkgSetting != null) { 9791 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9792 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9793 } 9794 } 9795 9796 /** 9797 * Deduces the ABI of a bundled app and sets the relevant fields on the 9798 * parsed pkg object. 9799 * 9800 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9801 * under which system libraries are installed. 9802 * @param apkName the name of the installed package. 9803 */ 9804 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9805 final File codeFile = new File(pkg.codePath); 9806 9807 final boolean has64BitLibs; 9808 final boolean has32BitLibs; 9809 if (isApkFile(codeFile)) { 9810 // Monolithic install 9811 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9812 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9813 } else { 9814 // Cluster install 9815 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9816 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9817 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9818 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9819 has64BitLibs = (new File(rootDir, isa)).exists(); 9820 } else { 9821 has64BitLibs = false; 9822 } 9823 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9824 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9825 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9826 has32BitLibs = (new File(rootDir, isa)).exists(); 9827 } else { 9828 has32BitLibs = false; 9829 } 9830 } 9831 9832 if (has64BitLibs && !has32BitLibs) { 9833 // The package has 64 bit libs, but not 32 bit libs. Its primary 9834 // ABI should be 64 bit. We can safely assume here that the bundled 9835 // native libraries correspond to the most preferred ABI in the list. 9836 9837 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9838 pkg.applicationInfo.secondaryCpuAbi = null; 9839 } else if (has32BitLibs && !has64BitLibs) { 9840 // The package has 32 bit libs but not 64 bit libs. Its primary 9841 // ABI should be 32 bit. 9842 9843 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9844 pkg.applicationInfo.secondaryCpuAbi = null; 9845 } else if (has32BitLibs && has64BitLibs) { 9846 // The application has both 64 and 32 bit bundled libraries. We check 9847 // here that the app declares multiArch support, and warn if it doesn't. 9848 // 9849 // We will be lenient here and record both ABIs. The primary will be the 9850 // ABI that's higher on the list, i.e, a device that's configured to prefer 9851 // 64 bit apps will see a 64 bit primary ABI, 9852 9853 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9854 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9855 } 9856 9857 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9858 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9859 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9860 } else { 9861 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9862 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9863 } 9864 } else { 9865 pkg.applicationInfo.primaryCpuAbi = null; 9866 pkg.applicationInfo.secondaryCpuAbi = null; 9867 } 9868 } 9869 9870 private void killApplication(String pkgName, int appId, String reason) { 9871 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9872 } 9873 9874 private void killApplication(String pkgName, int appId, int userId, String reason) { 9875 // Request the ActivityManager to kill the process(only for existing packages) 9876 // so that we do not end up in a confused state while the user is still using the older 9877 // version of the application while the new one gets installed. 9878 final long token = Binder.clearCallingIdentity(); 9879 try { 9880 IActivityManager am = ActivityManager.getService(); 9881 if (am != null) { 9882 try { 9883 am.killApplication(pkgName, appId, userId, reason); 9884 } catch (RemoteException e) { 9885 } 9886 } 9887 } finally { 9888 Binder.restoreCallingIdentity(token); 9889 } 9890 } 9891 9892 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9893 // Remove the parent package setting 9894 PackageSetting ps = (PackageSetting) pkg.mExtras; 9895 if (ps != null) { 9896 removePackageLI(ps, chatty); 9897 } 9898 // Remove the child package setting 9899 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9900 for (int i = 0; i < childCount; i++) { 9901 PackageParser.Package childPkg = pkg.childPackages.get(i); 9902 ps = (PackageSetting) childPkg.mExtras; 9903 if (ps != null) { 9904 removePackageLI(ps, chatty); 9905 } 9906 } 9907 } 9908 9909 void removePackageLI(PackageSetting ps, boolean chatty) { 9910 if (DEBUG_INSTALL) { 9911 if (chatty) 9912 Log.d(TAG, "Removing package " + ps.name); 9913 } 9914 9915 // writer 9916 synchronized (mPackages) { 9917 mPackages.remove(ps.name); 9918 final PackageParser.Package pkg = ps.pkg; 9919 if (pkg != null) { 9920 cleanPackageDataStructuresLILPw(pkg, chatty); 9921 } 9922 } 9923 } 9924 9925 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9926 if (DEBUG_INSTALL) { 9927 if (chatty) 9928 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9929 } 9930 9931 // writer 9932 synchronized (mPackages) { 9933 // Remove the parent package 9934 mPackages.remove(pkg.applicationInfo.packageName); 9935 cleanPackageDataStructuresLILPw(pkg, chatty); 9936 9937 // Remove the child packages 9938 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9939 for (int i = 0; i < childCount; i++) { 9940 PackageParser.Package childPkg = pkg.childPackages.get(i); 9941 mPackages.remove(childPkg.applicationInfo.packageName); 9942 cleanPackageDataStructuresLILPw(childPkg, chatty); 9943 } 9944 } 9945 } 9946 9947 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9948 int N = pkg.providers.size(); 9949 StringBuilder r = null; 9950 int i; 9951 for (i=0; i<N; i++) { 9952 PackageParser.Provider p = pkg.providers.get(i); 9953 mProviders.removeProvider(p); 9954 if (p.info.authority == null) { 9955 9956 /* There was another ContentProvider with this authority when 9957 * this app was installed so this authority is null, 9958 * Ignore it as we don't have to unregister the provider. 9959 */ 9960 continue; 9961 } 9962 String names[] = p.info.authority.split(";"); 9963 for (int j = 0; j < names.length; j++) { 9964 if (mProvidersByAuthority.get(names[j]) == p) { 9965 mProvidersByAuthority.remove(names[j]); 9966 if (DEBUG_REMOVE) { 9967 if (chatty) 9968 Log.d(TAG, "Unregistered content provider: " + names[j] 9969 + ", className = " + p.info.name + ", isSyncable = " 9970 + p.info.isSyncable); 9971 } 9972 } 9973 } 9974 if (DEBUG_REMOVE && chatty) { 9975 if (r == null) { 9976 r = new StringBuilder(256); 9977 } else { 9978 r.append(' '); 9979 } 9980 r.append(p.info.name); 9981 } 9982 } 9983 if (r != null) { 9984 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9985 } 9986 9987 N = pkg.services.size(); 9988 r = null; 9989 for (i=0; i<N; i++) { 9990 PackageParser.Service s = pkg.services.get(i); 9991 mServices.removeService(s); 9992 if (chatty) { 9993 if (r == null) { 9994 r = new StringBuilder(256); 9995 } else { 9996 r.append(' '); 9997 } 9998 r.append(s.info.name); 9999 } 10000 } 10001 if (r != null) { 10002 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 10003 } 10004 10005 N = pkg.receivers.size(); 10006 r = null; 10007 for (i=0; i<N; i++) { 10008 PackageParser.Activity a = pkg.receivers.get(i); 10009 mReceivers.removeActivity(a, "receiver"); 10010 if (DEBUG_REMOVE && chatty) { 10011 if (r == null) { 10012 r = new StringBuilder(256); 10013 } else { 10014 r.append(' '); 10015 } 10016 r.append(a.info.name); 10017 } 10018 } 10019 if (r != null) { 10020 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 10021 } 10022 10023 N = pkg.activities.size(); 10024 r = null; 10025 for (i=0; i<N; i++) { 10026 PackageParser.Activity a = pkg.activities.get(i); 10027 mActivities.removeActivity(a, "activity"); 10028 if (DEBUG_REMOVE && chatty) { 10029 if (r == null) { 10030 r = new StringBuilder(256); 10031 } else { 10032 r.append(' '); 10033 } 10034 r.append(a.info.name); 10035 } 10036 } 10037 if (r != null) { 10038 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 10039 } 10040 10041 N = pkg.permissions.size(); 10042 r = null; 10043 for (i=0; i<N; i++) { 10044 PackageParser.Permission p = pkg.permissions.get(i); 10045 BasePermission bp = mSettings.mPermissions.get(p.info.name); 10046 if (bp == null) { 10047 bp = mSettings.mPermissionTrees.get(p.info.name); 10048 } 10049 if (bp != null && bp.perm == p) { 10050 bp.perm = null; 10051 if (DEBUG_REMOVE && chatty) { 10052 if (r == null) { 10053 r = new StringBuilder(256); 10054 } else { 10055 r.append(' '); 10056 } 10057 r.append(p.info.name); 10058 } 10059 } 10060 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10061 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 10062 if (appOpPkgs != null) { 10063 appOpPkgs.remove(pkg.packageName); 10064 } 10065 } 10066 } 10067 if (r != null) { 10068 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10069 } 10070 10071 N = pkg.requestedPermissions.size(); 10072 r = null; 10073 for (i=0; i<N; i++) { 10074 String perm = pkg.requestedPermissions.get(i); 10075 BasePermission bp = mSettings.mPermissions.get(perm); 10076 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10077 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 10078 if (appOpPkgs != null) { 10079 appOpPkgs.remove(pkg.packageName); 10080 if (appOpPkgs.isEmpty()) { 10081 mAppOpPermissionPackages.remove(perm); 10082 } 10083 } 10084 } 10085 } 10086 if (r != null) { 10087 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 10088 } 10089 10090 N = pkg.instrumentation.size(); 10091 r = null; 10092 for (i=0; i<N; i++) { 10093 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 10094 mInstrumentation.remove(a.getComponentName()); 10095 if (DEBUG_REMOVE && chatty) { 10096 if (r == null) { 10097 r = new StringBuilder(256); 10098 } else { 10099 r.append(' '); 10100 } 10101 r.append(a.info.name); 10102 } 10103 } 10104 if (r != null) { 10105 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 10106 } 10107 10108 r = null; 10109 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 10110 // Only system apps can hold shared libraries. 10111 if (pkg.libraryNames != null) { 10112 for (i=0; i<pkg.libraryNames.size(); i++) { 10113 String name = pkg.libraryNames.get(i); 10114 SharedLibraryEntry cur = mSharedLibraries.get(name); 10115 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 10116 mSharedLibraries.remove(name); 10117 if (DEBUG_REMOVE && chatty) { 10118 if (r == null) { 10119 r = new StringBuilder(256); 10120 } else { 10121 r.append(' '); 10122 } 10123 r.append(name); 10124 } 10125 } 10126 } 10127 } 10128 } 10129 if (r != null) { 10130 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 10131 } 10132 } 10133 10134 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 10135 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 10136 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 10137 return true; 10138 } 10139 } 10140 return false; 10141 } 10142 10143 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 10144 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 10145 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 10146 10147 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 10148 // Update the parent permissions 10149 updatePermissionsLPw(pkg.packageName, pkg, flags); 10150 // Update the child permissions 10151 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10152 for (int i = 0; i < childCount; i++) { 10153 PackageParser.Package childPkg = pkg.childPackages.get(i); 10154 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 10155 } 10156 } 10157 10158 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 10159 int flags) { 10160 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 10161 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 10162 } 10163 10164 private void updatePermissionsLPw(String changingPkg, 10165 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 10166 // Make sure there are no dangling permission trees. 10167 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 10168 while (it.hasNext()) { 10169 final BasePermission bp = it.next(); 10170 if (bp.packageSetting == null) { 10171 // We may not yet have parsed the package, so just see if 10172 // we still know about its settings. 10173 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10174 } 10175 if (bp.packageSetting == null) { 10176 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 10177 + " from package " + bp.sourcePackage); 10178 it.remove(); 10179 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10180 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10181 Slog.i(TAG, "Removing old permission tree: " + bp.name 10182 + " from package " + bp.sourcePackage); 10183 flags |= UPDATE_PERMISSIONS_ALL; 10184 it.remove(); 10185 } 10186 } 10187 } 10188 10189 // Make sure all dynamic permissions have been assigned to a package, 10190 // and make sure there are no dangling permissions. 10191 it = mSettings.mPermissions.values().iterator(); 10192 while (it.hasNext()) { 10193 final BasePermission bp = it.next(); 10194 if (bp.type == BasePermission.TYPE_DYNAMIC) { 10195 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 10196 + bp.name + " pkg=" + bp.sourcePackage 10197 + " info=" + bp.pendingInfo); 10198 if (bp.packageSetting == null && bp.pendingInfo != null) { 10199 final BasePermission tree = findPermissionTreeLP(bp.name); 10200 if (tree != null && tree.perm != null) { 10201 bp.packageSetting = tree.packageSetting; 10202 bp.perm = new PackageParser.Permission(tree.perm.owner, 10203 new PermissionInfo(bp.pendingInfo)); 10204 bp.perm.info.packageName = tree.perm.info.packageName; 10205 bp.perm.info.name = bp.name; 10206 bp.uid = tree.uid; 10207 } 10208 } 10209 } 10210 if (bp.packageSetting == null) { 10211 // We may not yet have parsed the package, so just see if 10212 // we still know about its settings. 10213 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 10214 } 10215 if (bp.packageSetting == null) { 10216 Slog.w(TAG, "Removing dangling permission: " + bp.name 10217 + " from package " + bp.sourcePackage); 10218 it.remove(); 10219 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 10220 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 10221 Slog.i(TAG, "Removing old permission: " + bp.name 10222 + " from package " + bp.sourcePackage); 10223 flags |= UPDATE_PERMISSIONS_ALL; 10224 it.remove(); 10225 } 10226 } 10227 } 10228 10229 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 10230 // Now update the permissions for all packages, in particular 10231 // replace the granted permissions of the system packages. 10232 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 10233 for (PackageParser.Package pkg : mPackages.values()) { 10234 if (pkg != pkgInfo) { 10235 // Only replace for packages on requested volume 10236 final String volumeUuid = getVolumeUuidForPackage(pkg); 10237 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 10238 && Objects.equals(replaceVolumeUuid, volumeUuid); 10239 grantPermissionsLPw(pkg, replace, changingPkg); 10240 } 10241 } 10242 } 10243 10244 if (pkgInfo != null) { 10245 // Only replace for packages on requested volume 10246 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 10247 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 10248 && Objects.equals(replaceVolumeUuid, volumeUuid); 10249 grantPermissionsLPw(pkgInfo, replace, changingPkg); 10250 } 10251 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10252 } 10253 10254 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 10255 String packageOfInterest) { 10256 // IMPORTANT: There are two types of permissions: install and runtime. 10257 // Install time permissions are granted when the app is installed to 10258 // all device users and users added in the future. Runtime permissions 10259 // are granted at runtime explicitly to specific users. Normal and signature 10260 // protected permissions are install time permissions. Dangerous permissions 10261 // are install permissions if the app's target SDK is Lollipop MR1 or older, 10262 // otherwise they are runtime permissions. This function does not manage 10263 // runtime permissions except for the case an app targeting Lollipop MR1 10264 // being upgraded to target a newer SDK, in which case dangerous permissions 10265 // are transformed from install time to runtime ones. 10266 10267 final PackageSetting ps = (PackageSetting) pkg.mExtras; 10268 if (ps == null) { 10269 return; 10270 } 10271 10272 PermissionsState permissionsState = ps.getPermissionsState(); 10273 PermissionsState origPermissions = permissionsState; 10274 10275 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 10276 10277 boolean runtimePermissionsRevoked = false; 10278 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10279 10280 boolean changedInstallPermission = false; 10281 10282 if (replace) { 10283 ps.installPermissionsFixed = false; 10284 if (!ps.isSharedUser()) { 10285 origPermissions = new PermissionsState(permissionsState); 10286 permissionsState.reset(); 10287 } else { 10288 // We need to know only about runtime permission changes since the 10289 // calling code always writes the install permissions state but 10290 // the runtime ones are written only if changed. The only cases of 10291 // changed runtime permissions here are promotion of an install to 10292 // runtime and revocation of a runtime from a shared user. 10293 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10294 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10295 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10296 runtimePermissionsRevoked = true; 10297 } 10298 } 10299 } 10300 10301 permissionsState.setGlobalGids(mGlobalGids); 10302 10303 final int N = pkg.requestedPermissions.size(); 10304 for (int i=0; i<N; i++) { 10305 final String name = pkg.requestedPermissions.get(i); 10306 final BasePermission bp = mSettings.mPermissions.get(name); 10307 10308 if (DEBUG_INSTALL) { 10309 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10310 } 10311 10312 if (bp == null || bp.packageSetting == null) { 10313 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10314 Slog.w(TAG, "Unknown permission " + name 10315 + " in package " + pkg.packageName); 10316 } 10317 continue; 10318 } 10319 10320 10321 // Limit ephemeral apps to ephemeral allowed permissions. 10322 if (pkg.applicationInfo.isEphemeralApp() && !bp.isEphemeral()) { 10323 Log.i(TAG, "Denying non-ephemeral permission " + bp.name + " for package " 10324 + pkg.packageName); 10325 continue; 10326 } 10327 10328 final String perm = bp.name; 10329 boolean allowedSig = false; 10330 int grant = GRANT_DENIED; 10331 10332 // Keep track of app op permissions. 10333 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10334 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10335 if (pkgs == null) { 10336 pkgs = new ArraySet<>(); 10337 mAppOpPermissionPackages.put(bp.name, pkgs); 10338 } 10339 pkgs.add(pkg.packageName); 10340 } 10341 10342 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10343 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10344 >= Build.VERSION_CODES.M; 10345 switch (level) { 10346 case PermissionInfo.PROTECTION_NORMAL: { 10347 // For all apps normal permissions are install time ones. 10348 grant = GRANT_INSTALL; 10349 } break; 10350 10351 case PermissionInfo.PROTECTION_DANGEROUS: { 10352 // If a permission review is required for legacy apps we represent 10353 // their permissions as always granted runtime ones since we need 10354 // to keep the review required permission flag per user while an 10355 // install permission's state is shared across all users. 10356 if (!appSupportsRuntimePermissions && !mPermissionReviewRequired) { 10357 // For legacy apps dangerous permissions are install time ones. 10358 grant = GRANT_INSTALL; 10359 } else if (origPermissions.hasInstallPermission(bp.name)) { 10360 // For legacy apps that became modern, install becomes runtime. 10361 grant = GRANT_UPGRADE; 10362 } else if (mPromoteSystemApps 10363 && isSystemApp(ps) 10364 && mExistingSystemPackages.contains(ps.name)) { 10365 // For legacy system apps, install becomes runtime. 10366 // We cannot check hasInstallPermission() for system apps since those 10367 // permissions were granted implicitly and not persisted pre-M. 10368 grant = GRANT_UPGRADE; 10369 } else { 10370 // For modern apps keep runtime permissions unchanged. 10371 grant = GRANT_RUNTIME; 10372 } 10373 } break; 10374 10375 case PermissionInfo.PROTECTION_SIGNATURE: { 10376 // For all apps signature permissions are install time ones. 10377 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10378 if (allowedSig) { 10379 grant = GRANT_INSTALL; 10380 } 10381 } break; 10382 } 10383 10384 if (DEBUG_INSTALL) { 10385 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10386 } 10387 10388 if (grant != GRANT_DENIED) { 10389 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10390 // If this is an existing, non-system package, then 10391 // we can't add any new permissions to it. 10392 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10393 // Except... if this is a permission that was added 10394 // to the platform (note: need to only do this when 10395 // updating the platform). 10396 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10397 grant = GRANT_DENIED; 10398 } 10399 } 10400 } 10401 10402 switch (grant) { 10403 case GRANT_INSTALL: { 10404 // Revoke this as runtime permission to handle the case of 10405 // a runtime permission being downgraded to an install one. 10406 // Also in permission review mode we keep dangerous permissions 10407 // for legacy apps 10408 for (int userId : UserManagerService.getInstance().getUserIds()) { 10409 if (origPermissions.getRuntimePermissionState( 10410 bp.name, userId) != null) { 10411 // Revoke the runtime permission and clear the flags. 10412 origPermissions.revokeRuntimePermission(bp, userId); 10413 origPermissions.updatePermissionFlags(bp, userId, 10414 PackageManager.MASK_PERMISSION_FLAGS, 0); 10415 // If we revoked a permission permission, we have to write. 10416 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10417 changedRuntimePermissionUserIds, userId); 10418 } 10419 } 10420 // Grant an install permission. 10421 if (permissionsState.grantInstallPermission(bp) != 10422 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10423 changedInstallPermission = true; 10424 } 10425 } break; 10426 10427 case GRANT_RUNTIME: { 10428 // Grant previously granted runtime permissions. 10429 for (int userId : UserManagerService.getInstance().getUserIds()) { 10430 PermissionState permissionState = origPermissions 10431 .getRuntimePermissionState(bp.name, userId); 10432 int flags = permissionState != null 10433 ? permissionState.getFlags() : 0; 10434 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10435 if (permissionsState.grantRuntimePermission(bp, userId) == 10436 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10437 // If we cannot put the permission as it was, we have to write. 10438 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10439 changedRuntimePermissionUserIds, userId); 10440 } 10441 // If the app supports runtime permissions no need for a review. 10442 if (mPermissionReviewRequired 10443 && appSupportsRuntimePermissions 10444 && (flags & PackageManager 10445 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10446 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10447 // Since we changed the flags, we have to write. 10448 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10449 changedRuntimePermissionUserIds, userId); 10450 } 10451 } else if (mPermissionReviewRequired 10452 && !appSupportsRuntimePermissions) { 10453 // For legacy apps that need a permission review, every new 10454 // runtime permission is granted but it is pending a review. 10455 // We also need to review only platform defined runtime 10456 // permissions as these are the only ones the platform knows 10457 // how to disable the API to simulate revocation as legacy 10458 // apps don't expect to run with revoked permissions. 10459 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10460 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10461 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10462 // We changed the flags, hence have to write. 10463 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10464 changedRuntimePermissionUserIds, userId); 10465 } 10466 } 10467 if (permissionsState.grantRuntimePermission(bp, userId) 10468 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10469 // We changed the permission, hence have to write. 10470 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10471 changedRuntimePermissionUserIds, userId); 10472 } 10473 } 10474 // Propagate the permission flags. 10475 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10476 } 10477 } break; 10478 10479 case GRANT_UPGRADE: { 10480 // Grant runtime permissions for a previously held install permission. 10481 PermissionState permissionState = origPermissions 10482 .getInstallPermissionState(bp.name); 10483 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10484 10485 if (origPermissions.revokeInstallPermission(bp) 10486 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10487 // We will be transferring the permission flags, so clear them. 10488 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10489 PackageManager.MASK_PERMISSION_FLAGS, 0); 10490 changedInstallPermission = true; 10491 } 10492 10493 // If the permission is not to be promoted to runtime we ignore it and 10494 // also its other flags as they are not applicable to install permissions. 10495 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10496 for (int userId : currentUserIds) { 10497 if (permissionsState.grantRuntimePermission(bp, userId) != 10498 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10499 // Transfer the permission flags. 10500 permissionsState.updatePermissionFlags(bp, userId, 10501 flags, flags); 10502 // If we granted the permission, we have to write. 10503 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10504 changedRuntimePermissionUserIds, userId); 10505 } 10506 } 10507 } 10508 } break; 10509 10510 default: { 10511 if (packageOfInterest == null 10512 || packageOfInterest.equals(pkg.packageName)) { 10513 Slog.w(TAG, "Not granting permission " + perm 10514 + " to package " + pkg.packageName 10515 + " because it was previously installed without"); 10516 } 10517 } break; 10518 } 10519 } else { 10520 if (permissionsState.revokeInstallPermission(bp) != 10521 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10522 // Also drop the permission flags. 10523 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10524 PackageManager.MASK_PERMISSION_FLAGS, 0); 10525 changedInstallPermission = true; 10526 Slog.i(TAG, "Un-granting permission " + perm 10527 + " from package " + pkg.packageName 10528 + " (protectionLevel=" + bp.protectionLevel 10529 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10530 + ")"); 10531 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10532 // Don't print warning for app op permissions, since it is fine for them 10533 // not to be granted, there is a UI for the user to decide. 10534 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10535 Slog.w(TAG, "Not granting permission " + perm 10536 + " to package " + pkg.packageName 10537 + " (protectionLevel=" + bp.protectionLevel 10538 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10539 + ")"); 10540 } 10541 } 10542 } 10543 } 10544 10545 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10546 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10547 // This is the first that we have heard about this package, so the 10548 // permissions we have now selected are fixed until explicitly 10549 // changed. 10550 ps.installPermissionsFixed = true; 10551 } 10552 10553 // Persist the runtime permissions state for users with changes. If permissions 10554 // were revoked because no app in the shared user declares them we have to 10555 // write synchronously to avoid losing runtime permissions state. 10556 for (int userId : changedRuntimePermissionUserIds) { 10557 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10558 } 10559 } 10560 10561 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10562 boolean allowed = false; 10563 final int NP = PackageParser.NEW_PERMISSIONS.length; 10564 for (int ip=0; ip<NP; ip++) { 10565 final PackageParser.NewPermissionInfo npi 10566 = PackageParser.NEW_PERMISSIONS[ip]; 10567 if (npi.name.equals(perm) 10568 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10569 allowed = true; 10570 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10571 + pkg.packageName); 10572 break; 10573 } 10574 } 10575 return allowed; 10576 } 10577 10578 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10579 BasePermission bp, PermissionsState origPermissions) { 10580 boolean privilegedPermission = (bp.protectionLevel 10581 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0; 10582 boolean privappPermissionsDisable = 10583 RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_DISABLE; 10584 boolean platformPermission = PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage); 10585 boolean platformPackage = PLATFORM_PACKAGE_NAME.equals(pkg.packageName); 10586 if (!privappPermissionsDisable && privilegedPermission && pkg.isPrivilegedApp() 10587 && !platformPackage && platformPermission) { 10588 ArraySet<String> wlPermissions = SystemConfig.getInstance() 10589 .getPrivAppPermissions(pkg.packageName); 10590 boolean whitelisted = wlPermissions != null && wlPermissions.contains(perm); 10591 if (!whitelisted) { 10592 Slog.w(TAG, "Privileged permission " + perm + " for package " 10593 + pkg.packageName + " - not in privapp-permissions whitelist"); 10594 if (RoSystemProperties.CONTROL_PRIVAPP_PERMISSIONS_ENFORCE) { 10595 return false; 10596 } 10597 } 10598 } 10599 boolean allowed = (compareSignatures( 10600 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10601 == PackageManager.SIGNATURE_MATCH) 10602 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10603 == PackageManager.SIGNATURE_MATCH); 10604 if (!allowed && privilegedPermission) { 10605 if (isSystemApp(pkg)) { 10606 // For updated system applications, a system permission 10607 // is granted only if it had been defined by the original application. 10608 if (pkg.isUpdatedSystemApp()) { 10609 final PackageSetting sysPs = mSettings 10610 .getDisabledSystemPkgLPr(pkg.packageName); 10611 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10612 // If the original was granted this permission, we take 10613 // that grant decision as read and propagate it to the 10614 // update. 10615 if (sysPs.isPrivileged()) { 10616 allowed = true; 10617 } 10618 } else { 10619 // The system apk may have been updated with an older 10620 // version of the one on the data partition, but which 10621 // granted a new system permission that it didn't have 10622 // before. In this case we do want to allow the app to 10623 // now get the new permission if the ancestral apk is 10624 // privileged to get it. 10625 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10626 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10627 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10628 allowed = true; 10629 break; 10630 } 10631 } 10632 } 10633 // Also if a privileged parent package on the system image or any of 10634 // its children requested a privileged permission, the updated child 10635 // packages can also get the permission. 10636 if (pkg.parentPackage != null) { 10637 final PackageSetting disabledSysParentPs = mSettings 10638 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10639 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10640 && disabledSysParentPs.isPrivileged()) { 10641 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10642 allowed = true; 10643 } else if (disabledSysParentPs.pkg.childPackages != null) { 10644 final int count = disabledSysParentPs.pkg.childPackages.size(); 10645 for (int i = 0; i < count; i++) { 10646 PackageParser.Package disabledSysChildPkg = 10647 disabledSysParentPs.pkg.childPackages.get(i); 10648 if (isPackageRequestingPermission(disabledSysChildPkg, 10649 perm)) { 10650 allowed = true; 10651 break; 10652 } 10653 } 10654 } 10655 } 10656 } 10657 } 10658 } else { 10659 allowed = isPrivilegedApp(pkg); 10660 } 10661 } 10662 } 10663 if (!allowed) { 10664 if (!allowed && (bp.protectionLevel 10665 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10666 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10667 // If this was a previously normal/dangerous permission that got moved 10668 // to a system permission as part of the runtime permission redesign, then 10669 // we still want to blindly grant it to old apps. 10670 allowed = true; 10671 } 10672 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10673 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10674 // If this permission is to be granted to the system installer and 10675 // this app is an installer, then it gets the permission. 10676 allowed = true; 10677 } 10678 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10679 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10680 // If this permission is to be granted to the system verifier and 10681 // this app is a verifier, then it gets the permission. 10682 allowed = true; 10683 } 10684 if (!allowed && (bp.protectionLevel 10685 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10686 && isSystemApp(pkg)) { 10687 // Any pre-installed system app is allowed to get this permission. 10688 allowed = true; 10689 } 10690 if (!allowed && (bp.protectionLevel 10691 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10692 // For development permissions, a development permission 10693 // is granted only if it was already granted. 10694 allowed = origPermissions.hasInstallPermission(perm); 10695 } 10696 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10697 && pkg.packageName.equals(mSetupWizardPackage)) { 10698 // If this permission is to be granted to the system setup wizard and 10699 // this app is a setup wizard, then it gets the permission. 10700 allowed = true; 10701 } 10702 } 10703 return allowed; 10704 } 10705 10706 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10707 final int permCount = pkg.requestedPermissions.size(); 10708 for (int j = 0; j < permCount; j++) { 10709 String requestedPermission = pkg.requestedPermissions.get(j); 10710 if (permission.equals(requestedPermission)) { 10711 return true; 10712 } 10713 } 10714 return false; 10715 } 10716 10717 final class ActivityIntentResolver 10718 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10719 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10720 boolean defaultOnly, int userId) { 10721 if (!sUserManager.exists(userId)) return null; 10722 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10723 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10724 } 10725 10726 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10727 int userId) { 10728 if (!sUserManager.exists(userId)) return null; 10729 mFlags = flags; 10730 return super.queryIntent(intent, resolvedType, 10731 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10732 } 10733 10734 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10735 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10736 if (!sUserManager.exists(userId)) return null; 10737 if (packageActivities == null) { 10738 return null; 10739 } 10740 mFlags = flags; 10741 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10742 final int N = packageActivities.size(); 10743 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10744 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10745 10746 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10747 for (int i = 0; i < N; ++i) { 10748 intentFilters = packageActivities.get(i).intents; 10749 if (intentFilters != null && intentFilters.size() > 0) { 10750 PackageParser.ActivityIntentInfo[] array = 10751 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10752 intentFilters.toArray(array); 10753 listCut.add(array); 10754 } 10755 } 10756 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10757 } 10758 10759 /** 10760 * Finds a privileged activity that matches the specified activity names. 10761 */ 10762 private PackageParser.Activity findMatchingActivity( 10763 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10764 for (PackageParser.Activity sysActivity : activityList) { 10765 if (sysActivity.info.name.equals(activityInfo.name)) { 10766 return sysActivity; 10767 } 10768 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10769 return sysActivity; 10770 } 10771 if (sysActivity.info.targetActivity != null) { 10772 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10773 return sysActivity; 10774 } 10775 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10776 return sysActivity; 10777 } 10778 } 10779 } 10780 return null; 10781 } 10782 10783 public class IterGenerator<E> { 10784 public Iterator<E> generate(ActivityIntentInfo info) { 10785 return null; 10786 } 10787 } 10788 10789 public class ActionIterGenerator extends IterGenerator<String> { 10790 @Override 10791 public Iterator<String> generate(ActivityIntentInfo info) { 10792 return info.actionsIterator(); 10793 } 10794 } 10795 10796 public class CategoriesIterGenerator extends IterGenerator<String> { 10797 @Override 10798 public Iterator<String> generate(ActivityIntentInfo info) { 10799 return info.categoriesIterator(); 10800 } 10801 } 10802 10803 public class SchemesIterGenerator extends IterGenerator<String> { 10804 @Override 10805 public Iterator<String> generate(ActivityIntentInfo info) { 10806 return info.schemesIterator(); 10807 } 10808 } 10809 10810 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10811 @Override 10812 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10813 return info.authoritiesIterator(); 10814 } 10815 } 10816 10817 /** 10818 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10819 * MODIFIED. Do not pass in a list that should not be changed. 10820 */ 10821 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10822 IterGenerator<T> generator, Iterator<T> searchIterator) { 10823 // loop through the set of actions; every one must be found in the intent filter 10824 while (searchIterator.hasNext()) { 10825 // we must have at least one filter in the list to consider a match 10826 if (intentList.size() == 0) { 10827 break; 10828 } 10829 10830 final T searchAction = searchIterator.next(); 10831 10832 // loop through the set of intent filters 10833 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10834 while (intentIter.hasNext()) { 10835 final ActivityIntentInfo intentInfo = intentIter.next(); 10836 boolean selectionFound = false; 10837 10838 // loop through the intent filter's selection criteria; at least one 10839 // of them must match the searched criteria 10840 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10841 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10842 final T intentSelection = intentSelectionIter.next(); 10843 if (intentSelection != null && intentSelection.equals(searchAction)) { 10844 selectionFound = true; 10845 break; 10846 } 10847 } 10848 10849 // the selection criteria wasn't found in this filter's set; this filter 10850 // is not a potential match 10851 if (!selectionFound) { 10852 intentIter.remove(); 10853 } 10854 } 10855 } 10856 } 10857 10858 private boolean isProtectedAction(ActivityIntentInfo filter) { 10859 final Iterator<String> actionsIter = filter.actionsIterator(); 10860 while (actionsIter != null && actionsIter.hasNext()) { 10861 final String filterAction = actionsIter.next(); 10862 if (PROTECTED_ACTIONS.contains(filterAction)) { 10863 return true; 10864 } 10865 } 10866 return false; 10867 } 10868 10869 /** 10870 * Adjusts the priority of the given intent filter according to policy. 10871 * <p> 10872 * <ul> 10873 * <li>The priority for non privileged applications is capped to '0'</li> 10874 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10875 * <li>The priority for unbundled updates to privileged applications is capped to the 10876 * priority defined on the system partition</li> 10877 * </ul> 10878 * <p> 10879 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10880 * allowed to obtain any priority on any action. 10881 */ 10882 private void adjustPriority( 10883 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10884 // nothing to do; priority is fine as-is 10885 if (intent.getPriority() <= 0) { 10886 return; 10887 } 10888 10889 final ActivityInfo activityInfo = intent.activity.info; 10890 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10891 10892 final boolean privilegedApp = 10893 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10894 if (!privilegedApp) { 10895 // non-privileged applications can never define a priority >0 10896 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10897 + " package: " + applicationInfo.packageName 10898 + " activity: " + intent.activity.className 10899 + " origPrio: " + intent.getPriority()); 10900 intent.setPriority(0); 10901 return; 10902 } 10903 10904 if (systemActivities == null) { 10905 // the system package is not disabled; we're parsing the system partition 10906 if (isProtectedAction(intent)) { 10907 if (mDeferProtectedFilters) { 10908 // We can't deal with these just yet. No component should ever obtain a 10909 // >0 priority for a protected actions, with ONE exception -- the setup 10910 // wizard. The setup wizard, however, cannot be known until we're able to 10911 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10912 // until all intent filters have been processed. Chicken, meet egg. 10913 // Let the filter temporarily have a high priority and rectify the 10914 // priorities after all system packages have been scanned. 10915 mProtectedFilters.add(intent); 10916 if (DEBUG_FILTERS) { 10917 Slog.i(TAG, "Protected action; save for later;" 10918 + " package: " + applicationInfo.packageName 10919 + " activity: " + intent.activity.className 10920 + " origPrio: " + intent.getPriority()); 10921 } 10922 return; 10923 } else { 10924 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10925 Slog.i(TAG, "No setup wizard;" 10926 + " All protected intents capped to priority 0"); 10927 } 10928 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10929 if (DEBUG_FILTERS) { 10930 Slog.i(TAG, "Found setup wizard;" 10931 + " allow priority " + intent.getPriority() + ";" 10932 + " package: " + intent.activity.info.packageName 10933 + " activity: " + intent.activity.className 10934 + " priority: " + intent.getPriority()); 10935 } 10936 // setup wizard gets whatever it wants 10937 return; 10938 } 10939 Slog.w(TAG, "Protected action; cap priority to 0;" 10940 + " package: " + intent.activity.info.packageName 10941 + " activity: " + intent.activity.className 10942 + " origPrio: " + intent.getPriority()); 10943 intent.setPriority(0); 10944 return; 10945 } 10946 } 10947 // privileged apps on the system image get whatever priority they request 10948 return; 10949 } 10950 10951 // privileged app unbundled update ... try to find the same activity 10952 final PackageParser.Activity foundActivity = 10953 findMatchingActivity(systemActivities, activityInfo); 10954 if (foundActivity == null) { 10955 // this is a new activity; it cannot obtain >0 priority 10956 if (DEBUG_FILTERS) { 10957 Slog.i(TAG, "New activity; cap priority to 0;" 10958 + " package: " + applicationInfo.packageName 10959 + " activity: " + intent.activity.className 10960 + " origPrio: " + intent.getPriority()); 10961 } 10962 intent.setPriority(0); 10963 return; 10964 } 10965 10966 // found activity, now check for filter equivalence 10967 10968 // a shallow copy is enough; we modify the list, not its contents 10969 final List<ActivityIntentInfo> intentListCopy = 10970 new ArrayList<>(foundActivity.intents); 10971 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10972 10973 // find matching action subsets 10974 final Iterator<String> actionsIterator = intent.actionsIterator(); 10975 if (actionsIterator != null) { 10976 getIntentListSubset( 10977 intentListCopy, new ActionIterGenerator(), actionsIterator); 10978 if (intentListCopy.size() == 0) { 10979 // no more intents to match; we're not equivalent 10980 if (DEBUG_FILTERS) { 10981 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10982 + " package: " + applicationInfo.packageName 10983 + " activity: " + intent.activity.className 10984 + " origPrio: " + intent.getPriority()); 10985 } 10986 intent.setPriority(0); 10987 return; 10988 } 10989 } 10990 10991 // find matching category subsets 10992 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10993 if (categoriesIterator != null) { 10994 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10995 categoriesIterator); 10996 if (intentListCopy.size() == 0) { 10997 // no more intents to match; we're not equivalent 10998 if (DEBUG_FILTERS) { 10999 Slog.i(TAG, "Mismatched category; cap priority to 0;" 11000 + " package: " + applicationInfo.packageName 11001 + " activity: " + intent.activity.className 11002 + " origPrio: " + intent.getPriority()); 11003 } 11004 intent.setPriority(0); 11005 return; 11006 } 11007 } 11008 11009 // find matching schemes subsets 11010 final Iterator<String> schemesIterator = intent.schemesIterator(); 11011 if (schemesIterator != null) { 11012 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 11013 schemesIterator); 11014 if (intentListCopy.size() == 0) { 11015 // no more intents to match; we're not equivalent 11016 if (DEBUG_FILTERS) { 11017 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 11018 + " package: " + applicationInfo.packageName 11019 + " activity: " + intent.activity.className 11020 + " origPrio: " + intent.getPriority()); 11021 } 11022 intent.setPriority(0); 11023 return; 11024 } 11025 } 11026 11027 // find matching authorities subsets 11028 final Iterator<IntentFilter.AuthorityEntry> 11029 authoritiesIterator = intent.authoritiesIterator(); 11030 if (authoritiesIterator != null) { 11031 getIntentListSubset(intentListCopy, 11032 new AuthoritiesIterGenerator(), 11033 authoritiesIterator); 11034 if (intentListCopy.size() == 0) { 11035 // no more intents to match; we're not equivalent 11036 if (DEBUG_FILTERS) { 11037 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 11038 + " package: " + applicationInfo.packageName 11039 + " activity: " + intent.activity.className 11040 + " origPrio: " + intent.getPriority()); 11041 } 11042 intent.setPriority(0); 11043 return; 11044 } 11045 } 11046 11047 // we found matching filter(s); app gets the max priority of all intents 11048 int cappedPriority = 0; 11049 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 11050 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 11051 } 11052 if (intent.getPriority() > cappedPriority) { 11053 if (DEBUG_FILTERS) { 11054 Slog.i(TAG, "Found matching filter(s);" 11055 + " cap priority to " + cappedPriority + ";" 11056 + " package: " + applicationInfo.packageName 11057 + " activity: " + intent.activity.className 11058 + " origPrio: " + intent.getPriority()); 11059 } 11060 intent.setPriority(cappedPriority); 11061 return; 11062 } 11063 // all this for nothing; the requested priority was <= what was on the system 11064 } 11065 11066 public final void addActivity(PackageParser.Activity a, String type) { 11067 mActivities.put(a.getComponentName(), a); 11068 if (DEBUG_SHOW_INFO) 11069 Log.v( 11070 TAG, " " + type + " " + 11071 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 11072 if (DEBUG_SHOW_INFO) 11073 Log.v(TAG, " Class=" + a.info.name); 11074 final int NI = a.intents.size(); 11075 for (int j=0; j<NI; j++) { 11076 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11077 if ("activity".equals(type)) { 11078 final PackageSetting ps = 11079 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 11080 final List<PackageParser.Activity> systemActivities = 11081 ps != null && ps.pkg != null ? ps.pkg.activities : null; 11082 adjustPriority(systemActivities, intent); 11083 } 11084 if (DEBUG_SHOW_INFO) { 11085 Log.v(TAG, " IntentFilter:"); 11086 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11087 } 11088 if (!intent.debugCheck()) { 11089 Log.w(TAG, "==> For Activity " + a.info.name); 11090 } 11091 addFilter(intent); 11092 } 11093 } 11094 11095 public final void removeActivity(PackageParser.Activity a, String type) { 11096 mActivities.remove(a.getComponentName()); 11097 if (DEBUG_SHOW_INFO) { 11098 Log.v(TAG, " " + type + " " 11099 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 11100 : a.info.name) + ":"); 11101 Log.v(TAG, " Class=" + a.info.name); 11102 } 11103 final int NI = a.intents.size(); 11104 for (int j=0; j<NI; j++) { 11105 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 11106 if (DEBUG_SHOW_INFO) { 11107 Log.v(TAG, " IntentFilter:"); 11108 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11109 } 11110 removeFilter(intent); 11111 } 11112 } 11113 11114 @Override 11115 protected boolean allowFilterResult( 11116 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 11117 ActivityInfo filterAi = filter.activity.info; 11118 for (int i=dest.size()-1; i>=0; i--) { 11119 ActivityInfo destAi = dest.get(i).activityInfo; 11120 if (destAi.name == filterAi.name 11121 && destAi.packageName == filterAi.packageName) { 11122 return false; 11123 } 11124 } 11125 return true; 11126 } 11127 11128 @Override 11129 protected ActivityIntentInfo[] newArray(int size) { 11130 return new ActivityIntentInfo[size]; 11131 } 11132 11133 @Override 11134 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 11135 if (!sUserManager.exists(userId)) return true; 11136 PackageParser.Package p = filter.activity.owner; 11137 if (p != null) { 11138 PackageSetting ps = (PackageSetting)p.mExtras; 11139 if (ps != null) { 11140 // System apps are never considered stopped for purposes of 11141 // filtering, because there may be no way for the user to 11142 // actually re-launch them. 11143 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 11144 && ps.getStopped(userId); 11145 } 11146 } 11147 return false; 11148 } 11149 11150 @Override 11151 protected boolean isPackageForFilter(String packageName, 11152 PackageParser.ActivityIntentInfo info) { 11153 return packageName.equals(info.activity.owner.packageName); 11154 } 11155 11156 @Override 11157 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 11158 int match, int userId) { 11159 if (!sUserManager.exists(userId)) return null; 11160 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 11161 return null; 11162 } 11163 final PackageParser.Activity activity = info.activity; 11164 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 11165 if (ps == null) { 11166 return null; 11167 } 11168 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 11169 ps.readUserState(userId), userId); 11170 if (ai == null) { 11171 return null; 11172 } 11173 final ResolveInfo res = new ResolveInfo(); 11174 res.activityInfo = ai; 11175 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11176 res.filter = info; 11177 } 11178 if (info != null) { 11179 res.handleAllWebDataURI = info.handleAllWebDataURI(); 11180 } 11181 res.priority = info.getPriority(); 11182 res.preferredOrder = activity.owner.mPreferredOrder; 11183 //System.out.println("Result: " + res.activityInfo.className + 11184 // " = " + res.priority); 11185 res.match = match; 11186 res.isDefault = info.hasDefault; 11187 res.labelRes = info.labelRes; 11188 res.nonLocalizedLabel = info.nonLocalizedLabel; 11189 if (userNeedsBadging(userId)) { 11190 res.noResourceId = true; 11191 } else { 11192 res.icon = info.icon; 11193 } 11194 res.iconResourceId = info.icon; 11195 res.system = res.activityInfo.applicationInfo.isSystemApp(); 11196 return res; 11197 } 11198 11199 @Override 11200 protected void sortResults(List<ResolveInfo> results) { 11201 Collections.sort(results, mResolvePrioritySorter); 11202 } 11203 11204 @Override 11205 protected void dumpFilter(PrintWriter out, String prefix, 11206 PackageParser.ActivityIntentInfo filter) { 11207 out.print(prefix); out.print( 11208 Integer.toHexString(System.identityHashCode(filter.activity))); 11209 out.print(' '); 11210 filter.activity.printComponentShortName(out); 11211 out.print(" filter "); 11212 out.println(Integer.toHexString(System.identityHashCode(filter))); 11213 } 11214 11215 @Override 11216 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 11217 return filter.activity; 11218 } 11219 11220 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11221 PackageParser.Activity activity = (PackageParser.Activity)label; 11222 out.print(prefix); out.print( 11223 Integer.toHexString(System.identityHashCode(activity))); 11224 out.print(' '); 11225 activity.printComponentShortName(out); 11226 if (count > 1) { 11227 out.print(" ("); out.print(count); out.print(" filters)"); 11228 } 11229 out.println(); 11230 } 11231 11232 // Keys are String (activity class name), values are Activity. 11233 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 11234 = new ArrayMap<ComponentName, PackageParser.Activity>(); 11235 private int mFlags; 11236 } 11237 11238 private final class ServiceIntentResolver 11239 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 11240 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11241 boolean defaultOnly, int userId) { 11242 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11243 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11244 } 11245 11246 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11247 int userId) { 11248 if (!sUserManager.exists(userId)) return null; 11249 mFlags = flags; 11250 return super.queryIntent(intent, resolvedType, 11251 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11252 } 11253 11254 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11255 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 11256 if (!sUserManager.exists(userId)) return null; 11257 if (packageServices == null) { 11258 return null; 11259 } 11260 mFlags = flags; 11261 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 11262 final int N = packageServices.size(); 11263 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 11264 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 11265 11266 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 11267 for (int i = 0; i < N; ++i) { 11268 intentFilters = packageServices.get(i).intents; 11269 if (intentFilters != null && intentFilters.size() > 0) { 11270 PackageParser.ServiceIntentInfo[] array = 11271 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 11272 intentFilters.toArray(array); 11273 listCut.add(array); 11274 } 11275 } 11276 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11277 } 11278 11279 public final void addService(PackageParser.Service s) { 11280 mServices.put(s.getComponentName(), s); 11281 if (DEBUG_SHOW_INFO) { 11282 Log.v(TAG, " " 11283 + (s.info.nonLocalizedLabel != null 11284 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11285 Log.v(TAG, " Class=" + s.info.name); 11286 } 11287 final int NI = s.intents.size(); 11288 int j; 11289 for (j=0; j<NI; j++) { 11290 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11291 if (DEBUG_SHOW_INFO) { 11292 Log.v(TAG, " IntentFilter:"); 11293 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11294 } 11295 if (!intent.debugCheck()) { 11296 Log.w(TAG, "==> For Service " + s.info.name); 11297 } 11298 addFilter(intent); 11299 } 11300 } 11301 11302 public final void removeService(PackageParser.Service s) { 11303 mServices.remove(s.getComponentName()); 11304 if (DEBUG_SHOW_INFO) { 11305 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11306 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11307 Log.v(TAG, " Class=" + s.info.name); 11308 } 11309 final int NI = s.intents.size(); 11310 int j; 11311 for (j=0; j<NI; j++) { 11312 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11313 if (DEBUG_SHOW_INFO) { 11314 Log.v(TAG, " IntentFilter:"); 11315 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11316 } 11317 removeFilter(intent); 11318 } 11319 } 11320 11321 @Override 11322 protected boolean allowFilterResult( 11323 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11324 ServiceInfo filterSi = filter.service.info; 11325 for (int i=dest.size()-1; i>=0; i--) { 11326 ServiceInfo destAi = dest.get(i).serviceInfo; 11327 if (destAi.name == filterSi.name 11328 && destAi.packageName == filterSi.packageName) { 11329 return false; 11330 } 11331 } 11332 return true; 11333 } 11334 11335 @Override 11336 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11337 return new PackageParser.ServiceIntentInfo[size]; 11338 } 11339 11340 @Override 11341 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11342 if (!sUserManager.exists(userId)) return true; 11343 PackageParser.Package p = filter.service.owner; 11344 if (p != null) { 11345 PackageSetting ps = (PackageSetting)p.mExtras; 11346 if (ps != null) { 11347 // System apps are never considered stopped for purposes of 11348 // filtering, because there may be no way for the user to 11349 // actually re-launch them. 11350 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11351 && ps.getStopped(userId); 11352 } 11353 } 11354 return false; 11355 } 11356 11357 @Override 11358 protected boolean isPackageForFilter(String packageName, 11359 PackageParser.ServiceIntentInfo info) { 11360 return packageName.equals(info.service.owner.packageName); 11361 } 11362 11363 @Override 11364 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11365 int match, int userId) { 11366 if (!sUserManager.exists(userId)) return null; 11367 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11368 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11369 return null; 11370 } 11371 final PackageParser.Service service = info.service; 11372 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11373 if (ps == null) { 11374 return null; 11375 } 11376 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11377 ps.readUserState(userId), userId); 11378 if (si == null) { 11379 return null; 11380 } 11381 final ResolveInfo res = new ResolveInfo(); 11382 res.serviceInfo = si; 11383 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11384 res.filter = filter; 11385 } 11386 res.priority = info.getPriority(); 11387 res.preferredOrder = service.owner.mPreferredOrder; 11388 res.match = match; 11389 res.isDefault = info.hasDefault; 11390 res.labelRes = info.labelRes; 11391 res.nonLocalizedLabel = info.nonLocalizedLabel; 11392 res.icon = info.icon; 11393 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11394 return res; 11395 } 11396 11397 @Override 11398 protected void sortResults(List<ResolveInfo> results) { 11399 Collections.sort(results, mResolvePrioritySorter); 11400 } 11401 11402 @Override 11403 protected void dumpFilter(PrintWriter out, String prefix, 11404 PackageParser.ServiceIntentInfo filter) { 11405 out.print(prefix); out.print( 11406 Integer.toHexString(System.identityHashCode(filter.service))); 11407 out.print(' '); 11408 filter.service.printComponentShortName(out); 11409 out.print(" filter "); 11410 out.println(Integer.toHexString(System.identityHashCode(filter))); 11411 } 11412 11413 @Override 11414 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11415 return filter.service; 11416 } 11417 11418 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11419 PackageParser.Service service = (PackageParser.Service)label; 11420 out.print(prefix); out.print( 11421 Integer.toHexString(System.identityHashCode(service))); 11422 out.print(' '); 11423 service.printComponentShortName(out); 11424 if (count > 1) { 11425 out.print(" ("); out.print(count); out.print(" filters)"); 11426 } 11427 out.println(); 11428 } 11429 11430// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11431// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11432// final List<ResolveInfo> retList = Lists.newArrayList(); 11433// while (i.hasNext()) { 11434// final ResolveInfo resolveInfo = (ResolveInfo) i; 11435// if (isEnabledLP(resolveInfo.serviceInfo)) { 11436// retList.add(resolveInfo); 11437// } 11438// } 11439// return retList; 11440// } 11441 11442 // Keys are String (activity class name), values are Activity. 11443 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11444 = new ArrayMap<ComponentName, PackageParser.Service>(); 11445 private int mFlags; 11446 }; 11447 11448 private final class ProviderIntentResolver 11449 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11450 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11451 boolean defaultOnly, int userId) { 11452 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11453 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11454 } 11455 11456 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11457 int userId) { 11458 if (!sUserManager.exists(userId)) 11459 return null; 11460 mFlags = flags; 11461 return super.queryIntent(intent, resolvedType, 11462 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11463 } 11464 11465 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11466 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11467 if (!sUserManager.exists(userId)) 11468 return null; 11469 if (packageProviders == null) { 11470 return null; 11471 } 11472 mFlags = flags; 11473 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11474 final int N = packageProviders.size(); 11475 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11476 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11477 11478 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11479 for (int i = 0; i < N; ++i) { 11480 intentFilters = packageProviders.get(i).intents; 11481 if (intentFilters != null && intentFilters.size() > 0) { 11482 PackageParser.ProviderIntentInfo[] array = 11483 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11484 intentFilters.toArray(array); 11485 listCut.add(array); 11486 } 11487 } 11488 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11489 } 11490 11491 public final void addProvider(PackageParser.Provider p) { 11492 if (mProviders.containsKey(p.getComponentName())) { 11493 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11494 return; 11495 } 11496 11497 mProviders.put(p.getComponentName(), p); 11498 if (DEBUG_SHOW_INFO) { 11499 Log.v(TAG, " " 11500 + (p.info.nonLocalizedLabel != null 11501 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11502 Log.v(TAG, " Class=" + p.info.name); 11503 } 11504 final int NI = p.intents.size(); 11505 int j; 11506 for (j = 0; j < NI; j++) { 11507 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11508 if (DEBUG_SHOW_INFO) { 11509 Log.v(TAG, " IntentFilter:"); 11510 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11511 } 11512 if (!intent.debugCheck()) { 11513 Log.w(TAG, "==> For Provider " + p.info.name); 11514 } 11515 addFilter(intent); 11516 } 11517 } 11518 11519 public final void removeProvider(PackageParser.Provider p) { 11520 mProviders.remove(p.getComponentName()); 11521 if (DEBUG_SHOW_INFO) { 11522 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11523 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11524 Log.v(TAG, " Class=" + p.info.name); 11525 } 11526 final int NI = p.intents.size(); 11527 int j; 11528 for (j = 0; j < NI; j++) { 11529 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11530 if (DEBUG_SHOW_INFO) { 11531 Log.v(TAG, " IntentFilter:"); 11532 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11533 } 11534 removeFilter(intent); 11535 } 11536 } 11537 11538 @Override 11539 protected boolean allowFilterResult( 11540 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11541 ProviderInfo filterPi = filter.provider.info; 11542 for (int i = dest.size() - 1; i >= 0; i--) { 11543 ProviderInfo destPi = dest.get(i).providerInfo; 11544 if (destPi.name == filterPi.name 11545 && destPi.packageName == filterPi.packageName) { 11546 return false; 11547 } 11548 } 11549 return true; 11550 } 11551 11552 @Override 11553 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11554 return new PackageParser.ProviderIntentInfo[size]; 11555 } 11556 11557 @Override 11558 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11559 if (!sUserManager.exists(userId)) 11560 return true; 11561 PackageParser.Package p = filter.provider.owner; 11562 if (p != null) { 11563 PackageSetting ps = (PackageSetting) p.mExtras; 11564 if (ps != null) { 11565 // System apps are never considered stopped for purposes of 11566 // filtering, because there may be no way for the user to 11567 // actually re-launch them. 11568 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11569 && ps.getStopped(userId); 11570 } 11571 } 11572 return false; 11573 } 11574 11575 @Override 11576 protected boolean isPackageForFilter(String packageName, 11577 PackageParser.ProviderIntentInfo info) { 11578 return packageName.equals(info.provider.owner.packageName); 11579 } 11580 11581 @Override 11582 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11583 int match, int userId) { 11584 if (!sUserManager.exists(userId)) 11585 return null; 11586 final PackageParser.ProviderIntentInfo info = filter; 11587 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11588 return null; 11589 } 11590 final PackageParser.Provider provider = info.provider; 11591 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11592 if (ps == null) { 11593 return null; 11594 } 11595 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11596 ps.readUserState(userId), userId); 11597 if (pi == null) { 11598 return null; 11599 } 11600 final ResolveInfo res = new ResolveInfo(); 11601 res.providerInfo = pi; 11602 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11603 res.filter = filter; 11604 } 11605 res.priority = info.getPriority(); 11606 res.preferredOrder = provider.owner.mPreferredOrder; 11607 res.match = match; 11608 res.isDefault = info.hasDefault; 11609 res.labelRes = info.labelRes; 11610 res.nonLocalizedLabel = info.nonLocalizedLabel; 11611 res.icon = info.icon; 11612 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11613 return res; 11614 } 11615 11616 @Override 11617 protected void sortResults(List<ResolveInfo> results) { 11618 Collections.sort(results, mResolvePrioritySorter); 11619 } 11620 11621 @Override 11622 protected void dumpFilter(PrintWriter out, String prefix, 11623 PackageParser.ProviderIntentInfo filter) { 11624 out.print(prefix); 11625 out.print( 11626 Integer.toHexString(System.identityHashCode(filter.provider))); 11627 out.print(' '); 11628 filter.provider.printComponentShortName(out); 11629 out.print(" filter "); 11630 out.println(Integer.toHexString(System.identityHashCode(filter))); 11631 } 11632 11633 @Override 11634 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11635 return filter.provider; 11636 } 11637 11638 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11639 PackageParser.Provider provider = (PackageParser.Provider)label; 11640 out.print(prefix); out.print( 11641 Integer.toHexString(System.identityHashCode(provider))); 11642 out.print(' '); 11643 provider.printComponentShortName(out); 11644 if (count > 1) { 11645 out.print(" ("); out.print(count); out.print(" filters)"); 11646 } 11647 out.println(); 11648 } 11649 11650 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11651 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11652 private int mFlags; 11653 } 11654 11655 static final class EphemeralIntentResolver 11656 extends IntentResolver<EphemeralResponse, EphemeralResponse> { 11657 /** 11658 * The result that has the highest defined order. Ordering applies on a 11659 * per-package basis. Mapping is from package name to Pair of order and 11660 * EphemeralResolveInfo. 11661 * <p> 11662 * NOTE: This is implemented as a field variable for convenience and efficiency. 11663 * By having a field variable, we're able to track filter ordering as soon as 11664 * a non-zero order is defined. Otherwise, multiple loops across the result set 11665 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 11666 * this needs to be contained entirely within {@link #filterResults()}. 11667 */ 11668 final ArrayMap<String, Pair<Integer, EphemeralResolveInfo>> mOrderResult = new ArrayMap<>(); 11669 11670 @Override 11671 protected EphemeralResponse[] newArray(int size) { 11672 return new EphemeralResponse[size]; 11673 } 11674 11675 @Override 11676 protected boolean isPackageForFilter(String packageName, EphemeralResponse responseObj) { 11677 return true; 11678 } 11679 11680 @Override 11681 protected EphemeralResponse newResult(EphemeralResponse responseObj, int match, 11682 int userId) { 11683 if (!sUserManager.exists(userId)) { 11684 return null; 11685 } 11686 final String packageName = responseObj.resolveInfo.getPackageName(); 11687 final Integer order = responseObj.getOrder(); 11688 final Pair<Integer, EphemeralResolveInfo> lastOrderResult = 11689 mOrderResult.get(packageName); 11690 // ordering is enabled and this item's order isn't high enough 11691 if (lastOrderResult != null && lastOrderResult.first >= order) { 11692 return null; 11693 } 11694 final EphemeralResolveInfo res = responseObj.resolveInfo; 11695 if (order > 0) { 11696 // non-zero order, enable ordering 11697 mOrderResult.put(packageName, new Pair<>(order, res)); 11698 } 11699 return responseObj; 11700 } 11701 11702 @Override 11703 protected void filterResults(List<EphemeralResponse> results) { 11704 // only do work if ordering is enabled [most of the time it won't be] 11705 if (mOrderResult.size() == 0) { 11706 return; 11707 } 11708 int resultSize = results.size(); 11709 for (int i = 0; i < resultSize; i++) { 11710 final EphemeralResolveInfo info = results.get(i).resolveInfo; 11711 final String packageName = info.getPackageName(); 11712 final Pair<Integer, EphemeralResolveInfo> savedInfo = mOrderResult.get(packageName); 11713 if (savedInfo == null) { 11714 // package doesn't having ordering 11715 continue; 11716 } 11717 if (savedInfo.second == info) { 11718 // circled back to the highest ordered item; remove from order list 11719 mOrderResult.remove(savedInfo); 11720 if (mOrderResult.size() == 0) { 11721 // no more ordered items 11722 break; 11723 } 11724 continue; 11725 } 11726 // item has a worse order, remove it from the result list 11727 results.remove(i); 11728 resultSize--; 11729 i--; 11730 } 11731 } 11732 } 11733 11734 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11735 new Comparator<ResolveInfo>() { 11736 public int compare(ResolveInfo r1, ResolveInfo r2) { 11737 int v1 = r1.priority; 11738 int v2 = r2.priority; 11739 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11740 if (v1 != v2) { 11741 return (v1 > v2) ? -1 : 1; 11742 } 11743 v1 = r1.preferredOrder; 11744 v2 = r2.preferredOrder; 11745 if (v1 != v2) { 11746 return (v1 > v2) ? -1 : 1; 11747 } 11748 if (r1.isDefault != r2.isDefault) { 11749 return r1.isDefault ? -1 : 1; 11750 } 11751 v1 = r1.match; 11752 v2 = r2.match; 11753 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11754 if (v1 != v2) { 11755 return (v1 > v2) ? -1 : 1; 11756 } 11757 if (r1.system != r2.system) { 11758 return r1.system ? -1 : 1; 11759 } 11760 if (r1.activityInfo != null) { 11761 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11762 } 11763 if (r1.serviceInfo != null) { 11764 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11765 } 11766 if (r1.providerInfo != null) { 11767 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11768 } 11769 return 0; 11770 } 11771 }; 11772 11773 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11774 new Comparator<ProviderInfo>() { 11775 public int compare(ProviderInfo p1, ProviderInfo p2) { 11776 final int v1 = p1.initOrder; 11777 final int v2 = p2.initOrder; 11778 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11779 } 11780 }; 11781 11782 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11783 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11784 final int[] userIds) { 11785 mHandler.post(new Runnable() { 11786 @Override 11787 public void run() { 11788 try { 11789 final IActivityManager am = ActivityManager.getService(); 11790 if (am == null) return; 11791 final int[] resolvedUserIds; 11792 if (userIds == null) { 11793 resolvedUserIds = am.getRunningUserIds(); 11794 } else { 11795 resolvedUserIds = userIds; 11796 } 11797 for (int id : resolvedUserIds) { 11798 final Intent intent = new Intent(action, 11799 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 11800 if (extras != null) { 11801 intent.putExtras(extras); 11802 } 11803 if (targetPkg != null) { 11804 intent.setPackage(targetPkg); 11805 } 11806 // Modify the UID when posting to other users 11807 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11808 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11809 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11810 intent.putExtra(Intent.EXTRA_UID, uid); 11811 } 11812 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11813 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11814 if (DEBUG_BROADCASTS) { 11815 RuntimeException here = new RuntimeException("here"); 11816 here.fillInStackTrace(); 11817 Slog.d(TAG, "Sending to user " + id + ": " 11818 + intent.toShortString(false, true, false, false) 11819 + " " + intent.getExtras(), here); 11820 } 11821 am.broadcastIntent(null, intent, null, finishedReceiver, 11822 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11823 null, finishedReceiver != null, false, id); 11824 } 11825 } catch (RemoteException ex) { 11826 } 11827 } 11828 }); 11829 } 11830 11831 /** 11832 * Check if the external storage media is available. This is true if there 11833 * is a mounted external storage medium or if the external storage is 11834 * emulated. 11835 */ 11836 private boolean isExternalMediaAvailable() { 11837 return mMediaMounted || Environment.isExternalStorageEmulated(); 11838 } 11839 11840 @Override 11841 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11842 // writer 11843 synchronized (mPackages) { 11844 if (!isExternalMediaAvailable()) { 11845 // If the external storage is no longer mounted at this point, 11846 // the caller may not have been able to delete all of this 11847 // packages files and can not delete any more. Bail. 11848 return null; 11849 } 11850 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11851 if (lastPackage != null) { 11852 pkgs.remove(lastPackage); 11853 } 11854 if (pkgs.size() > 0) { 11855 return pkgs.get(0); 11856 } 11857 } 11858 return null; 11859 } 11860 11861 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11862 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11863 userId, andCode ? 1 : 0, packageName); 11864 if (mSystemReady) { 11865 msg.sendToTarget(); 11866 } else { 11867 if (mPostSystemReadyMessages == null) { 11868 mPostSystemReadyMessages = new ArrayList<>(); 11869 } 11870 mPostSystemReadyMessages.add(msg); 11871 } 11872 } 11873 11874 void startCleaningPackages() { 11875 // reader 11876 if (!isExternalMediaAvailable()) { 11877 return; 11878 } 11879 synchronized (mPackages) { 11880 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11881 return; 11882 } 11883 } 11884 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11885 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11886 IActivityManager am = ActivityManager.getService(); 11887 if (am != null) { 11888 try { 11889 am.startService(null, intent, null, mContext.getOpPackageName(), 11890 UserHandle.USER_SYSTEM); 11891 } catch (RemoteException e) { 11892 } 11893 } 11894 } 11895 11896 @Override 11897 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11898 int installFlags, String installerPackageName, int userId) { 11899 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11900 11901 final int callingUid = Binder.getCallingUid(); 11902 enforceCrossUserPermission(callingUid, userId, 11903 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11904 11905 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11906 try { 11907 if (observer != null) { 11908 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11909 } 11910 } catch (RemoteException re) { 11911 } 11912 return; 11913 } 11914 11915 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11916 installFlags |= PackageManager.INSTALL_FROM_ADB; 11917 11918 } else { 11919 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11920 // about installerPackageName. 11921 11922 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11923 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11924 } 11925 11926 UserHandle user; 11927 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11928 user = UserHandle.ALL; 11929 } else { 11930 user = new UserHandle(userId); 11931 } 11932 11933 // Only system components can circumvent runtime permissions when installing. 11934 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11935 && mContext.checkCallingOrSelfPermission(Manifest.permission 11936 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11937 throw new SecurityException("You need the " 11938 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11939 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11940 } 11941 11942 final File originFile = new File(originPath); 11943 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11944 11945 final Message msg = mHandler.obtainMessage(INIT_COPY); 11946 final VerificationInfo verificationInfo = new VerificationInfo( 11947 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11948 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11949 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11950 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11951 null /*certificates*/); 11952 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11953 msg.obj = params; 11954 11955 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11956 System.identityHashCode(msg.obj)); 11957 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11958 System.identityHashCode(msg.obj)); 11959 11960 mHandler.sendMessage(msg); 11961 } 11962 11963 void installStage(String packageName, File stagedDir, String stagedCid, 11964 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11965 String installerPackageName, int installerUid, UserHandle user, 11966 Certificate[][] certificates) { 11967 if (DEBUG_EPHEMERAL) { 11968 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11969 Slog.d(TAG, "Ephemeral install of " + packageName); 11970 } 11971 } 11972 final VerificationInfo verificationInfo = new VerificationInfo( 11973 sessionParams.originatingUri, sessionParams.referrerUri, 11974 sessionParams.originatingUid, installerUid); 11975 11976 final OriginInfo origin; 11977 if (stagedDir != null) { 11978 origin = OriginInfo.fromStagedFile(stagedDir); 11979 } else { 11980 origin = OriginInfo.fromStagedContainer(stagedCid); 11981 } 11982 11983 final Message msg = mHandler.obtainMessage(INIT_COPY); 11984 final InstallParams params = new InstallParams(origin, null, observer, 11985 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11986 verificationInfo, user, sessionParams.abiOverride, 11987 sessionParams.grantedRuntimePermissions, certificates); 11988 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11989 msg.obj = params; 11990 11991 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11992 System.identityHashCode(msg.obj)); 11993 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11994 System.identityHashCode(msg.obj)); 11995 11996 mHandler.sendMessage(msg); 11997 } 11998 11999 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12000 int userId) { 12001 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12002 sendPackageAddedForNewUsers(packageName, isSystem, pkgSetting.appId, userId); 12003 } 12004 12005 private void sendPackageAddedForNewUsers(String packageName, boolean isSystem, 12006 int appId, int... userIds) { 12007 if (ArrayUtils.isEmpty(userIds)) { 12008 return; 12009 } 12010 Bundle extras = new Bundle(1); 12011 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12012 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userIds[0], appId)); 12013 12014 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12015 packageName, extras, 0, null, null, userIds); 12016 if (isSystem) { 12017 mHandler.post(() -> { 12018 for (int userId : userIds) { 12019 sendBootCompletedBroadcastToSystemApp(packageName, userId); 12020 } 12021 } 12022 ); 12023 } 12024 } 12025 12026 /** 12027 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12028 * automatically without needing an explicit launch. 12029 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12030 */ 12031 private void sendBootCompletedBroadcastToSystemApp(String packageName, int userId) { 12032 // If user is not running, the app didn't miss any broadcast 12033 if (!mUserManagerInternal.isUserRunning(userId)) { 12034 return; 12035 } 12036 final IActivityManager am = ActivityManager.getService(); 12037 try { 12038 // Deliver LOCKED_BOOT_COMPLETED first 12039 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12040 .setPackage(packageName); 12041 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12042 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12043 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12044 12045 // Deliver BOOT_COMPLETED only if user is unlocked 12046 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12047 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12048 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12049 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12050 } 12051 } catch (RemoteException e) { 12052 throw e.rethrowFromSystemServer(); 12053 } 12054 } 12055 12056 @Override 12057 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12058 int userId) { 12059 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12060 PackageSetting pkgSetting; 12061 final int uid = Binder.getCallingUid(); 12062 enforceCrossUserPermission(uid, userId, 12063 true /* requireFullPermission */, true /* checkShell */, 12064 "setApplicationHiddenSetting for user " + userId); 12065 12066 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12067 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12068 return false; 12069 } 12070 12071 long callingId = Binder.clearCallingIdentity(); 12072 try { 12073 boolean sendAdded = false; 12074 boolean sendRemoved = false; 12075 // writer 12076 synchronized (mPackages) { 12077 pkgSetting = mSettings.mPackages.get(packageName); 12078 if (pkgSetting == null) { 12079 return false; 12080 } 12081 // Do not allow "android" is being disabled 12082 if ("android".equals(packageName)) { 12083 Slog.w(TAG, "Cannot hide package: android"); 12084 return false; 12085 } 12086 // Only allow protected packages to hide themselves. 12087 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 12088 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12089 Slog.w(TAG, "Not hiding protected package: " + packageName); 12090 return false; 12091 } 12092 12093 if (pkgSetting.getHidden(userId) != hidden) { 12094 pkgSetting.setHidden(hidden, userId); 12095 mSettings.writePackageRestrictionsLPr(userId); 12096 if (hidden) { 12097 sendRemoved = true; 12098 } else { 12099 sendAdded = true; 12100 } 12101 } 12102 } 12103 if (sendAdded) { 12104 sendPackageAddedForUser(packageName, pkgSetting, userId); 12105 return true; 12106 } 12107 if (sendRemoved) { 12108 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12109 "hiding pkg"); 12110 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12111 return true; 12112 } 12113 } finally { 12114 Binder.restoreCallingIdentity(callingId); 12115 } 12116 return false; 12117 } 12118 12119 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12120 int userId) { 12121 final PackageRemovedInfo info = new PackageRemovedInfo(); 12122 info.removedPackage = packageName; 12123 info.removedUsers = new int[] {userId}; 12124 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12125 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12126 } 12127 12128 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 12129 if (pkgList.length > 0) { 12130 Bundle extras = new Bundle(1); 12131 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12132 12133 sendPackageBroadcast( 12134 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12135 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12136 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12137 new int[] {userId}); 12138 } 12139 } 12140 12141 /** 12142 * Returns true if application is not found or there was an error. Otherwise it returns 12143 * the hidden state of the package for the given user. 12144 */ 12145 @Override 12146 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12147 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12148 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12149 true /* requireFullPermission */, false /* checkShell */, 12150 "getApplicationHidden for user " + userId); 12151 PackageSetting pkgSetting; 12152 long callingId = Binder.clearCallingIdentity(); 12153 try { 12154 // writer 12155 synchronized (mPackages) { 12156 pkgSetting = mSettings.mPackages.get(packageName); 12157 if (pkgSetting == null) { 12158 return true; 12159 } 12160 return pkgSetting.getHidden(userId); 12161 } 12162 } finally { 12163 Binder.restoreCallingIdentity(callingId); 12164 } 12165 } 12166 12167 /** 12168 * @hide 12169 */ 12170 @Override 12171 public int installExistingPackageAsUser(String packageName, int userId) { 12172 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 12173 null); 12174 PackageSetting pkgSetting; 12175 final int uid = Binder.getCallingUid(); 12176 enforceCrossUserPermission(uid, userId, 12177 true /* requireFullPermission */, true /* checkShell */, 12178 "installExistingPackage for user " + userId); 12179 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 12180 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 12181 } 12182 12183 long callingId = Binder.clearCallingIdentity(); 12184 try { 12185 boolean installed = false; 12186 12187 // writer 12188 synchronized (mPackages) { 12189 pkgSetting = mSettings.mPackages.get(packageName); 12190 if (pkgSetting == null) { 12191 return PackageManager.INSTALL_FAILED_INVALID_URI; 12192 } 12193 if (!pkgSetting.getInstalled(userId)) { 12194 pkgSetting.setInstalled(true, userId); 12195 pkgSetting.setHidden(false, userId); 12196 mSettings.writePackageRestrictionsLPr(userId); 12197 installed = true; 12198 } 12199 } 12200 12201 if (installed) { 12202 if (pkgSetting.pkg != null) { 12203 synchronized (mInstallLock) { 12204 // We don't need to freeze for a brand new install 12205 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 12206 } 12207 } 12208 sendPackageAddedForUser(packageName, pkgSetting, userId); 12209 } 12210 } finally { 12211 Binder.restoreCallingIdentity(callingId); 12212 } 12213 12214 return PackageManager.INSTALL_SUCCEEDED; 12215 } 12216 12217 boolean isUserRestricted(int userId, String restrictionKey) { 12218 Bundle restrictions = sUserManager.getUserRestrictions(userId); 12219 if (restrictions.getBoolean(restrictionKey, false)) { 12220 Log.w(TAG, "User is restricted: " + restrictionKey); 12221 return true; 12222 } 12223 return false; 12224 } 12225 12226 @Override 12227 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 12228 int userId) { 12229 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12230 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12231 true /* requireFullPermission */, true /* checkShell */, 12232 "setPackagesSuspended for user " + userId); 12233 12234 if (ArrayUtils.isEmpty(packageNames)) { 12235 return packageNames; 12236 } 12237 12238 // List of package names for whom the suspended state has changed. 12239 List<String> changedPackages = new ArrayList<>(packageNames.length); 12240 // List of package names for whom the suspended state is not set as requested in this 12241 // method. 12242 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 12243 long callingId = Binder.clearCallingIdentity(); 12244 try { 12245 for (int i = 0; i < packageNames.length; i++) { 12246 String packageName = packageNames[i]; 12247 boolean changed = false; 12248 final int appId; 12249 synchronized (mPackages) { 12250 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12251 if (pkgSetting == null) { 12252 Slog.w(TAG, "Could not find package setting for package \"" + packageName 12253 + "\". Skipping suspending/un-suspending."); 12254 unactionedPackages.add(packageName); 12255 continue; 12256 } 12257 appId = pkgSetting.appId; 12258 if (pkgSetting.getSuspended(userId) != suspended) { 12259 if (!canSuspendPackageForUserLocked(packageName, userId)) { 12260 unactionedPackages.add(packageName); 12261 continue; 12262 } 12263 pkgSetting.setSuspended(suspended, userId); 12264 mSettings.writePackageRestrictionsLPr(userId); 12265 changed = true; 12266 changedPackages.add(packageName); 12267 } 12268 } 12269 12270 if (changed && suspended) { 12271 killApplication(packageName, UserHandle.getUid(userId, appId), 12272 "suspending package"); 12273 } 12274 } 12275 } finally { 12276 Binder.restoreCallingIdentity(callingId); 12277 } 12278 12279 if (!changedPackages.isEmpty()) { 12280 sendPackagesSuspendedForUser(changedPackages.toArray( 12281 new String[changedPackages.size()]), userId, suspended); 12282 } 12283 12284 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 12285 } 12286 12287 @Override 12288 public boolean isPackageSuspendedForUser(String packageName, int userId) { 12289 enforceCrossUserPermission(Binder.getCallingUid(), userId, 12290 true /* requireFullPermission */, false /* checkShell */, 12291 "isPackageSuspendedForUser for user " + userId); 12292 synchronized (mPackages) { 12293 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12294 if (pkgSetting == null) { 12295 throw new IllegalArgumentException("Unknown target package: " + packageName); 12296 } 12297 return pkgSetting.getSuspended(userId); 12298 } 12299 } 12300 12301 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 12302 if (isPackageDeviceAdmin(packageName, userId)) { 12303 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12304 + "\": has an active device admin"); 12305 return false; 12306 } 12307 12308 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 12309 if (packageName.equals(activeLauncherPackageName)) { 12310 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12311 + "\": contains the active launcher"); 12312 return false; 12313 } 12314 12315 if (packageName.equals(mRequiredInstallerPackage)) { 12316 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12317 + "\": required for package installation"); 12318 return false; 12319 } 12320 12321 if (packageName.equals(mRequiredUninstallerPackage)) { 12322 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12323 + "\": required for package uninstallation"); 12324 return false; 12325 } 12326 12327 if (packageName.equals(mRequiredVerifierPackage)) { 12328 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12329 + "\": required for package verification"); 12330 return false; 12331 } 12332 12333 if (packageName.equals(getDefaultDialerPackageName(userId))) { 12334 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12335 + "\": is the default dialer"); 12336 return false; 12337 } 12338 12339 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12340 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 12341 + "\": protected package"); 12342 return false; 12343 } 12344 12345 return true; 12346 } 12347 12348 private String getActiveLauncherPackageName(int userId) { 12349 Intent intent = new Intent(Intent.ACTION_MAIN); 12350 intent.addCategory(Intent.CATEGORY_HOME); 12351 ResolveInfo resolveInfo = resolveIntent( 12352 intent, 12353 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 12354 PackageManager.MATCH_DEFAULT_ONLY, 12355 userId); 12356 12357 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 12358 } 12359 12360 private String getDefaultDialerPackageName(int userId) { 12361 synchronized (mPackages) { 12362 return mSettings.getDefaultDialerPackageNameLPw(userId); 12363 } 12364 } 12365 12366 @Override 12367 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 12368 mContext.enforceCallingOrSelfPermission( 12369 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12370 "Only package verification agents can verify applications"); 12371 12372 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12373 final PackageVerificationResponse response = new PackageVerificationResponse( 12374 verificationCode, Binder.getCallingUid()); 12375 msg.arg1 = id; 12376 msg.obj = response; 12377 mHandler.sendMessage(msg); 12378 } 12379 12380 @Override 12381 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 12382 long millisecondsToDelay) { 12383 mContext.enforceCallingOrSelfPermission( 12384 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12385 "Only package verification agents can extend verification timeouts"); 12386 12387 final PackageVerificationState state = mPendingVerification.get(id); 12388 final PackageVerificationResponse response = new PackageVerificationResponse( 12389 verificationCodeAtTimeout, Binder.getCallingUid()); 12390 12391 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 12392 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 12393 } 12394 if (millisecondsToDelay < 0) { 12395 millisecondsToDelay = 0; 12396 } 12397 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 12398 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 12399 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 12400 } 12401 12402 if ((state != null) && !state.timeoutExtended()) { 12403 state.extendTimeout(); 12404 12405 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12406 msg.arg1 = id; 12407 msg.obj = response; 12408 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12409 } 12410 } 12411 12412 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12413 int verificationCode, UserHandle user) { 12414 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12415 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12416 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12417 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12418 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12419 12420 mContext.sendBroadcastAsUser(intent, user, 12421 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12422 } 12423 12424 private ComponentName matchComponentForVerifier(String packageName, 12425 List<ResolveInfo> receivers) { 12426 ActivityInfo targetReceiver = null; 12427 12428 final int NR = receivers.size(); 12429 for (int i = 0; i < NR; i++) { 12430 final ResolveInfo info = receivers.get(i); 12431 if (info.activityInfo == null) { 12432 continue; 12433 } 12434 12435 if (packageName.equals(info.activityInfo.packageName)) { 12436 targetReceiver = info.activityInfo; 12437 break; 12438 } 12439 } 12440 12441 if (targetReceiver == null) { 12442 return null; 12443 } 12444 12445 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12446 } 12447 12448 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12449 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12450 if (pkgInfo.verifiers.length == 0) { 12451 return null; 12452 } 12453 12454 final int N = pkgInfo.verifiers.length; 12455 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12456 for (int i = 0; i < N; i++) { 12457 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12458 12459 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12460 receivers); 12461 if (comp == null) { 12462 continue; 12463 } 12464 12465 final int verifierUid = getUidForVerifier(verifierInfo); 12466 if (verifierUid == -1) { 12467 continue; 12468 } 12469 12470 if (DEBUG_VERIFY) { 12471 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12472 + " with the correct signature"); 12473 } 12474 sufficientVerifiers.add(comp); 12475 verificationState.addSufficientVerifier(verifierUid); 12476 } 12477 12478 return sufficientVerifiers; 12479 } 12480 12481 private int getUidForVerifier(VerifierInfo verifierInfo) { 12482 synchronized (mPackages) { 12483 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12484 if (pkg == null) { 12485 return -1; 12486 } else if (pkg.mSignatures.length != 1) { 12487 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12488 + " has more than one signature; ignoring"); 12489 return -1; 12490 } 12491 12492 /* 12493 * If the public key of the package's signature does not match 12494 * our expected public key, then this is a different package and 12495 * we should skip. 12496 */ 12497 12498 final byte[] expectedPublicKey; 12499 try { 12500 final Signature verifierSig = pkg.mSignatures[0]; 12501 final PublicKey publicKey = verifierSig.getPublicKey(); 12502 expectedPublicKey = publicKey.getEncoded(); 12503 } catch (CertificateException e) { 12504 return -1; 12505 } 12506 12507 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12508 12509 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12510 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12511 + " does not have the expected public key; ignoring"); 12512 return -1; 12513 } 12514 12515 return pkg.applicationInfo.uid; 12516 } 12517 } 12518 12519 @Override 12520 public void finishPackageInstall(int token, boolean didLaunch) { 12521 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12522 12523 if (DEBUG_INSTALL) { 12524 Slog.v(TAG, "BM finishing package install for " + token); 12525 } 12526 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12527 12528 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12529 mHandler.sendMessage(msg); 12530 } 12531 12532 /** 12533 * Get the verification agent timeout. 12534 * 12535 * @return verification timeout in milliseconds 12536 */ 12537 private long getVerificationTimeout() { 12538 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12539 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12540 DEFAULT_VERIFICATION_TIMEOUT); 12541 } 12542 12543 /** 12544 * Get the default verification agent response code. 12545 * 12546 * @return default verification response code 12547 */ 12548 private int getDefaultVerificationResponse() { 12549 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12550 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12551 DEFAULT_VERIFICATION_RESPONSE); 12552 } 12553 12554 /** 12555 * Check whether or not package verification has been enabled. 12556 * 12557 * @return true if verification should be performed 12558 */ 12559 private boolean isVerificationEnabled(int userId, int installFlags) { 12560 if (!DEFAULT_VERIFY_ENABLE) { 12561 return false; 12562 } 12563 // Ephemeral apps don't get the full verification treatment 12564 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12565 if (DEBUG_EPHEMERAL) { 12566 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12567 } 12568 return false; 12569 } 12570 12571 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12572 12573 // Check if installing from ADB 12574 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12575 // Do not run verification in a test harness environment 12576 if (ActivityManager.isRunningInTestHarness()) { 12577 return false; 12578 } 12579 if (ensureVerifyAppsEnabled) { 12580 return true; 12581 } 12582 // Check if the developer does not want package verification for ADB installs 12583 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12584 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12585 return false; 12586 } 12587 } 12588 12589 if (ensureVerifyAppsEnabled) { 12590 return true; 12591 } 12592 12593 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12594 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12595 } 12596 12597 @Override 12598 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12599 throws RemoteException { 12600 mContext.enforceCallingOrSelfPermission( 12601 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12602 "Only intentfilter verification agents can verify applications"); 12603 12604 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12605 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12606 Binder.getCallingUid(), verificationCode, failedDomains); 12607 msg.arg1 = id; 12608 msg.obj = response; 12609 mHandler.sendMessage(msg); 12610 } 12611 12612 @Override 12613 public int getIntentVerificationStatus(String packageName, int userId) { 12614 synchronized (mPackages) { 12615 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12616 } 12617 } 12618 12619 @Override 12620 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12621 mContext.enforceCallingOrSelfPermission( 12622 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12623 12624 boolean result = false; 12625 synchronized (mPackages) { 12626 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12627 } 12628 if (result) { 12629 scheduleWritePackageRestrictionsLocked(userId); 12630 } 12631 return result; 12632 } 12633 12634 @Override 12635 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12636 String packageName) { 12637 synchronized (mPackages) { 12638 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12639 } 12640 } 12641 12642 @Override 12643 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12644 if (TextUtils.isEmpty(packageName)) { 12645 return ParceledListSlice.emptyList(); 12646 } 12647 synchronized (mPackages) { 12648 PackageParser.Package pkg = mPackages.get(packageName); 12649 if (pkg == null || pkg.activities == null) { 12650 return ParceledListSlice.emptyList(); 12651 } 12652 final int count = pkg.activities.size(); 12653 ArrayList<IntentFilter> result = new ArrayList<>(); 12654 for (int n=0; n<count; n++) { 12655 PackageParser.Activity activity = pkg.activities.get(n); 12656 if (activity.intents != null && activity.intents.size() > 0) { 12657 result.addAll(activity.intents); 12658 } 12659 } 12660 return new ParceledListSlice<>(result); 12661 } 12662 } 12663 12664 @Override 12665 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12666 mContext.enforceCallingOrSelfPermission( 12667 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12668 12669 synchronized (mPackages) { 12670 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12671 if (packageName != null) { 12672 result |= updateIntentVerificationStatus(packageName, 12673 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12674 userId); 12675 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12676 packageName, userId); 12677 } 12678 return result; 12679 } 12680 } 12681 12682 @Override 12683 public String getDefaultBrowserPackageName(int userId) { 12684 synchronized (mPackages) { 12685 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12686 } 12687 } 12688 12689 /** 12690 * Get the "allow unknown sources" setting. 12691 * 12692 * @return the current "allow unknown sources" setting 12693 */ 12694 private int getUnknownSourcesSettings() { 12695 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12696 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12697 -1); 12698 } 12699 12700 @Override 12701 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12702 final int uid = Binder.getCallingUid(); 12703 // writer 12704 synchronized (mPackages) { 12705 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12706 if (targetPackageSetting == null) { 12707 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12708 } 12709 12710 PackageSetting installerPackageSetting; 12711 if (installerPackageName != null) { 12712 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12713 if (installerPackageSetting == null) { 12714 throw new IllegalArgumentException("Unknown installer package: " 12715 + installerPackageName); 12716 } 12717 } else { 12718 installerPackageSetting = null; 12719 } 12720 12721 Signature[] callerSignature; 12722 Object obj = mSettings.getUserIdLPr(uid); 12723 if (obj != null) { 12724 if (obj instanceof SharedUserSetting) { 12725 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12726 } else if (obj instanceof PackageSetting) { 12727 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12728 } else { 12729 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12730 } 12731 } else { 12732 throw new SecurityException("Unknown calling UID: " + uid); 12733 } 12734 12735 // Verify: can't set installerPackageName to a package that is 12736 // not signed with the same cert as the caller. 12737 if (installerPackageSetting != null) { 12738 if (compareSignatures(callerSignature, 12739 installerPackageSetting.signatures.mSignatures) 12740 != PackageManager.SIGNATURE_MATCH) { 12741 throw new SecurityException( 12742 "Caller does not have same cert as new installer package " 12743 + installerPackageName); 12744 } 12745 } 12746 12747 // Verify: if target already has an installer package, it must 12748 // be signed with the same cert as the caller. 12749 if (targetPackageSetting.installerPackageName != null) { 12750 PackageSetting setting = mSettings.mPackages.get( 12751 targetPackageSetting.installerPackageName); 12752 // If the currently set package isn't valid, then it's always 12753 // okay to change it. 12754 if (setting != null) { 12755 if (compareSignatures(callerSignature, 12756 setting.signatures.mSignatures) 12757 != PackageManager.SIGNATURE_MATCH) { 12758 throw new SecurityException( 12759 "Caller does not have same cert as old installer package " 12760 + targetPackageSetting.installerPackageName); 12761 } 12762 } 12763 } 12764 12765 // Okay! 12766 targetPackageSetting.installerPackageName = installerPackageName; 12767 if (installerPackageName != null) { 12768 mSettings.mInstallerPackages.add(installerPackageName); 12769 } 12770 scheduleWriteSettingsLocked(); 12771 } 12772 } 12773 12774 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12775 // Queue up an async operation since the package installation may take a little while. 12776 mHandler.post(new Runnable() { 12777 public void run() { 12778 mHandler.removeCallbacks(this); 12779 // Result object to be returned 12780 PackageInstalledInfo res = new PackageInstalledInfo(); 12781 res.setReturnCode(currentStatus); 12782 res.uid = -1; 12783 res.pkg = null; 12784 res.removedInfo = null; 12785 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12786 args.doPreInstall(res.returnCode); 12787 synchronized (mInstallLock) { 12788 installPackageTracedLI(args, res); 12789 } 12790 args.doPostInstall(res.returnCode, res.uid); 12791 } 12792 12793 // A restore should be performed at this point if (a) the install 12794 // succeeded, (b) the operation is not an update, and (c) the new 12795 // package has not opted out of backup participation. 12796 final boolean update = res.removedInfo != null 12797 && res.removedInfo.removedPackage != null; 12798 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12799 boolean doRestore = !update 12800 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12801 12802 // Set up the post-install work request bookkeeping. This will be used 12803 // and cleaned up by the post-install event handling regardless of whether 12804 // there's a restore pass performed. Token values are >= 1. 12805 int token; 12806 if (mNextInstallToken < 0) mNextInstallToken = 1; 12807 token = mNextInstallToken++; 12808 12809 PostInstallData data = new PostInstallData(args, res); 12810 mRunningInstalls.put(token, data); 12811 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12812 12813 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12814 // Pass responsibility to the Backup Manager. It will perform a 12815 // restore if appropriate, then pass responsibility back to the 12816 // Package Manager to run the post-install observer callbacks 12817 // and broadcasts. 12818 IBackupManager bm = IBackupManager.Stub.asInterface( 12819 ServiceManager.getService(Context.BACKUP_SERVICE)); 12820 if (bm != null) { 12821 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12822 + " to BM for possible restore"); 12823 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12824 try { 12825 // TODO: http://b/22388012 12826 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12827 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12828 } else { 12829 doRestore = false; 12830 } 12831 } catch (RemoteException e) { 12832 // can't happen; the backup manager is local 12833 } catch (Exception e) { 12834 Slog.e(TAG, "Exception trying to enqueue restore", e); 12835 doRestore = false; 12836 } 12837 } else { 12838 Slog.e(TAG, "Backup Manager not found!"); 12839 doRestore = false; 12840 } 12841 } 12842 12843 if (!doRestore) { 12844 // No restore possible, or the Backup Manager was mysteriously not 12845 // available -- just fire the post-install work request directly. 12846 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12847 12848 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12849 12850 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12851 mHandler.sendMessage(msg); 12852 } 12853 } 12854 }); 12855 } 12856 12857 /** 12858 * Callback from PackageSettings whenever an app is first transitioned out of the 12859 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12860 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12861 * here whether the app is the target of an ongoing install, and only send the 12862 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12863 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12864 * handling. 12865 */ 12866 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12867 // Serialize this with the rest of the install-process message chain. In the 12868 // restore-at-install case, this Runnable will necessarily run before the 12869 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12870 // are coherent. In the non-restore case, the app has already completed install 12871 // and been launched through some other means, so it is not in a problematic 12872 // state for observers to see the FIRST_LAUNCH signal. 12873 mHandler.post(new Runnable() { 12874 @Override 12875 public void run() { 12876 for (int i = 0; i < mRunningInstalls.size(); i++) { 12877 final PostInstallData data = mRunningInstalls.valueAt(i); 12878 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 12879 continue; 12880 } 12881 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12882 // right package; but is it for the right user? 12883 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12884 if (userId == data.res.newUsers[uIndex]) { 12885 if (DEBUG_BACKUP) { 12886 Slog.i(TAG, "Package " + pkgName 12887 + " being restored so deferring FIRST_LAUNCH"); 12888 } 12889 return; 12890 } 12891 } 12892 } 12893 } 12894 // didn't find it, so not being restored 12895 if (DEBUG_BACKUP) { 12896 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12897 } 12898 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12899 } 12900 }); 12901 } 12902 12903 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12904 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12905 installerPkg, null, userIds); 12906 } 12907 12908 private abstract class HandlerParams { 12909 private static final int MAX_RETRIES = 4; 12910 12911 /** 12912 * Number of times startCopy() has been attempted and had a non-fatal 12913 * error. 12914 */ 12915 private int mRetries = 0; 12916 12917 /** User handle for the user requesting the information or installation. */ 12918 private final UserHandle mUser; 12919 String traceMethod; 12920 int traceCookie; 12921 12922 HandlerParams(UserHandle user) { 12923 mUser = user; 12924 } 12925 12926 UserHandle getUser() { 12927 return mUser; 12928 } 12929 12930 HandlerParams setTraceMethod(String traceMethod) { 12931 this.traceMethod = traceMethod; 12932 return this; 12933 } 12934 12935 HandlerParams setTraceCookie(int traceCookie) { 12936 this.traceCookie = traceCookie; 12937 return this; 12938 } 12939 12940 final boolean startCopy() { 12941 boolean res; 12942 try { 12943 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12944 12945 if (++mRetries > MAX_RETRIES) { 12946 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12947 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12948 handleServiceError(); 12949 return false; 12950 } else { 12951 handleStartCopy(); 12952 res = true; 12953 } 12954 } catch (RemoteException e) { 12955 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12956 mHandler.sendEmptyMessage(MCS_RECONNECT); 12957 res = false; 12958 } 12959 handleReturnCode(); 12960 return res; 12961 } 12962 12963 final void serviceError() { 12964 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12965 handleServiceError(); 12966 handleReturnCode(); 12967 } 12968 12969 abstract void handleStartCopy() throws RemoteException; 12970 abstract void handleServiceError(); 12971 abstract void handleReturnCode(); 12972 } 12973 12974 class MeasureParams extends HandlerParams { 12975 private final PackageStats mStats; 12976 private boolean mSuccess; 12977 12978 private final IPackageStatsObserver mObserver; 12979 12980 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12981 super(new UserHandle(stats.userHandle)); 12982 mObserver = observer; 12983 mStats = stats; 12984 } 12985 12986 @Override 12987 public String toString() { 12988 return "MeasureParams{" 12989 + Integer.toHexString(System.identityHashCode(this)) 12990 + " " + mStats.packageName + "}"; 12991 } 12992 12993 @Override 12994 void handleStartCopy() throws RemoteException { 12995 synchronized (mInstallLock) { 12996 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12997 } 12998 12999 if (mSuccess) { 13000 boolean mounted = false; 13001 try { 13002 final String status = Environment.getExternalStorageState(); 13003 mounted = (Environment.MEDIA_MOUNTED.equals(status) 13004 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 13005 } catch (Exception e) { 13006 } 13007 13008 if (mounted) { 13009 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 13010 13011 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 13012 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 13013 13014 mStats.externalDataSize = calculateDirectorySize(mContainerService, 13015 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 13016 13017 // Always subtract cache size, since it's a subdirectory 13018 mStats.externalDataSize -= mStats.externalCacheSize; 13019 13020 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 13021 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 13022 13023 mStats.externalObbSize = calculateDirectorySize(mContainerService, 13024 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 13025 } 13026 } 13027 } 13028 13029 @Override 13030 void handleReturnCode() { 13031 if (mObserver != null) { 13032 try { 13033 mObserver.onGetStatsCompleted(mStats, mSuccess); 13034 } catch (RemoteException e) { 13035 Slog.i(TAG, "Observer no longer exists."); 13036 } 13037 } 13038 } 13039 13040 @Override 13041 void handleServiceError() { 13042 Slog.e(TAG, "Could not measure application " + mStats.packageName 13043 + " external storage"); 13044 } 13045 } 13046 13047 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 13048 throws RemoteException { 13049 long result = 0; 13050 for (File path : paths) { 13051 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 13052 } 13053 return result; 13054 } 13055 13056 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 13057 for (File path : paths) { 13058 try { 13059 mcs.clearDirectory(path.getAbsolutePath()); 13060 } catch (RemoteException e) { 13061 } 13062 } 13063 } 13064 13065 static class OriginInfo { 13066 /** 13067 * Location where install is coming from, before it has been 13068 * copied/renamed into place. This could be a single monolithic APK 13069 * file, or a cluster directory. This location may be untrusted. 13070 */ 13071 final File file; 13072 final String cid; 13073 13074 /** 13075 * Flag indicating that {@link #file} or {@link #cid} has already been 13076 * staged, meaning downstream users don't need to defensively copy the 13077 * contents. 13078 */ 13079 final boolean staged; 13080 13081 /** 13082 * Flag indicating that {@link #file} or {@link #cid} is an already 13083 * installed app that is being moved. 13084 */ 13085 final boolean existing; 13086 13087 final String resolvedPath; 13088 final File resolvedFile; 13089 13090 static OriginInfo fromNothing() { 13091 return new OriginInfo(null, null, false, false); 13092 } 13093 13094 static OriginInfo fromUntrustedFile(File file) { 13095 return new OriginInfo(file, null, false, false); 13096 } 13097 13098 static OriginInfo fromExistingFile(File file) { 13099 return new OriginInfo(file, null, false, true); 13100 } 13101 13102 static OriginInfo fromStagedFile(File file) { 13103 return new OriginInfo(file, null, true, false); 13104 } 13105 13106 static OriginInfo fromStagedContainer(String cid) { 13107 return new OriginInfo(null, cid, true, false); 13108 } 13109 13110 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 13111 this.file = file; 13112 this.cid = cid; 13113 this.staged = staged; 13114 this.existing = existing; 13115 13116 if (cid != null) { 13117 resolvedPath = PackageHelper.getSdDir(cid); 13118 resolvedFile = new File(resolvedPath); 13119 } else if (file != null) { 13120 resolvedPath = file.getAbsolutePath(); 13121 resolvedFile = file; 13122 } else { 13123 resolvedPath = null; 13124 resolvedFile = null; 13125 } 13126 } 13127 } 13128 13129 static class MoveInfo { 13130 final int moveId; 13131 final String fromUuid; 13132 final String toUuid; 13133 final String packageName; 13134 final String dataAppName; 13135 final int appId; 13136 final String seinfo; 13137 final int targetSdkVersion; 13138 13139 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 13140 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 13141 this.moveId = moveId; 13142 this.fromUuid = fromUuid; 13143 this.toUuid = toUuid; 13144 this.packageName = packageName; 13145 this.dataAppName = dataAppName; 13146 this.appId = appId; 13147 this.seinfo = seinfo; 13148 this.targetSdkVersion = targetSdkVersion; 13149 } 13150 } 13151 13152 static class VerificationInfo { 13153 /** A constant used to indicate that a uid value is not present. */ 13154 public static final int NO_UID = -1; 13155 13156 /** URI referencing where the package was downloaded from. */ 13157 final Uri originatingUri; 13158 13159 /** HTTP referrer URI associated with the originatingURI. */ 13160 final Uri referrer; 13161 13162 /** UID of the application that the install request originated from. */ 13163 final int originatingUid; 13164 13165 /** UID of application requesting the install */ 13166 final int installerUid; 13167 13168 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 13169 this.originatingUri = originatingUri; 13170 this.referrer = referrer; 13171 this.originatingUid = originatingUid; 13172 this.installerUid = installerUid; 13173 } 13174 } 13175 13176 class InstallParams extends HandlerParams { 13177 final OriginInfo origin; 13178 final MoveInfo move; 13179 final IPackageInstallObserver2 observer; 13180 int installFlags; 13181 final String installerPackageName; 13182 final String volumeUuid; 13183 private InstallArgs mArgs; 13184 private int mRet; 13185 final String packageAbiOverride; 13186 final String[] grantedRuntimePermissions; 13187 final VerificationInfo verificationInfo; 13188 final Certificate[][] certificates; 13189 13190 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13191 int installFlags, String installerPackageName, String volumeUuid, 13192 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 13193 String[] grantedPermissions, Certificate[][] certificates) { 13194 super(user); 13195 this.origin = origin; 13196 this.move = move; 13197 this.observer = observer; 13198 this.installFlags = installFlags; 13199 this.installerPackageName = installerPackageName; 13200 this.volumeUuid = volumeUuid; 13201 this.verificationInfo = verificationInfo; 13202 this.packageAbiOverride = packageAbiOverride; 13203 this.grantedRuntimePermissions = grantedPermissions; 13204 this.certificates = certificates; 13205 } 13206 13207 @Override 13208 public String toString() { 13209 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 13210 + " file=" + origin.file + " cid=" + origin.cid + "}"; 13211 } 13212 13213 private int installLocationPolicy(PackageInfoLite pkgLite) { 13214 String packageName = pkgLite.packageName; 13215 int installLocation = pkgLite.installLocation; 13216 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13217 // reader 13218 synchronized (mPackages) { 13219 // Currently installed package which the new package is attempting to replace or 13220 // null if no such package is installed. 13221 PackageParser.Package installedPkg = mPackages.get(packageName); 13222 // Package which currently owns the data which the new package will own if installed. 13223 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 13224 // will be null whereas dataOwnerPkg will contain information about the package 13225 // which was uninstalled while keeping its data. 13226 PackageParser.Package dataOwnerPkg = installedPkg; 13227 if (dataOwnerPkg == null) { 13228 PackageSetting ps = mSettings.mPackages.get(packageName); 13229 if (ps != null) { 13230 dataOwnerPkg = ps.pkg; 13231 } 13232 } 13233 13234 if (dataOwnerPkg != null) { 13235 // If installed, the package will get access to data left on the device by its 13236 // predecessor. As a security measure, this is permited only if this is not a 13237 // version downgrade or if the predecessor package is marked as debuggable and 13238 // a downgrade is explicitly requested. 13239 // 13240 // On debuggable platform builds, downgrades are permitted even for 13241 // non-debuggable packages to make testing easier. Debuggable platform builds do 13242 // not offer security guarantees and thus it's OK to disable some security 13243 // mechanisms to make debugging/testing easier on those builds. However, even on 13244 // debuggable builds downgrades of packages are permitted only if requested via 13245 // installFlags. This is because we aim to keep the behavior of debuggable 13246 // platform builds as close as possible to the behavior of non-debuggable 13247 // platform builds. 13248 final boolean downgradeRequested = 13249 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 13250 final boolean packageDebuggable = 13251 (dataOwnerPkg.applicationInfo.flags 13252 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 13253 final boolean downgradePermitted = 13254 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 13255 if (!downgradePermitted) { 13256 try { 13257 checkDowngrade(dataOwnerPkg, pkgLite); 13258 } catch (PackageManagerException e) { 13259 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 13260 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 13261 } 13262 } 13263 } 13264 13265 if (installedPkg != null) { 13266 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 13267 // Check for updated system application. 13268 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 13269 if (onSd) { 13270 Slog.w(TAG, "Cannot install update to system app on sdcard"); 13271 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 13272 } 13273 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13274 } else { 13275 if (onSd) { 13276 // Install flag overrides everything. 13277 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13278 } 13279 // If current upgrade specifies particular preference 13280 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 13281 // Application explicitly specified internal. 13282 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13283 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 13284 // App explictly prefers external. Let policy decide 13285 } else { 13286 // Prefer previous location 13287 if (isExternal(installedPkg)) { 13288 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13289 } 13290 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 13291 } 13292 } 13293 } else { 13294 // Invalid install. Return error code 13295 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 13296 } 13297 } 13298 } 13299 // All the special cases have been taken care of. 13300 // Return result based on recommended install location. 13301 if (onSd) { 13302 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 13303 } 13304 return pkgLite.recommendedInstallLocation; 13305 } 13306 13307 /* 13308 * Invoke remote method to get package information and install 13309 * location values. Override install location based on default 13310 * policy if needed and then create install arguments based 13311 * on the install location. 13312 */ 13313 public void handleStartCopy() throws RemoteException { 13314 int ret = PackageManager.INSTALL_SUCCEEDED; 13315 13316 // If we're already staged, we've firmly committed to an install location 13317 if (origin.staged) { 13318 if (origin.file != null) { 13319 installFlags |= PackageManager.INSTALL_INTERNAL; 13320 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13321 } else if (origin.cid != null) { 13322 installFlags |= PackageManager.INSTALL_EXTERNAL; 13323 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13324 } else { 13325 throw new IllegalStateException("Invalid stage location"); 13326 } 13327 } 13328 13329 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13330 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 13331 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13332 PackageInfoLite pkgLite = null; 13333 13334 if (onInt && onSd) { 13335 // Check if both bits are set. 13336 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 13337 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13338 } else if (onSd && ephemeral) { 13339 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 13340 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13341 } else { 13342 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 13343 packageAbiOverride); 13344 13345 if (DEBUG_EPHEMERAL && ephemeral) { 13346 Slog.v(TAG, "pkgLite for install: " + pkgLite); 13347 } 13348 13349 /* 13350 * If we have too little free space, try to free cache 13351 * before giving up. 13352 */ 13353 if (!origin.staged && pkgLite.recommendedInstallLocation 13354 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13355 // TODO: focus freeing disk space on the target device 13356 final StorageManager storage = StorageManager.from(mContext); 13357 final long lowThreshold = storage.getStorageLowBytes( 13358 Environment.getDataDirectory()); 13359 13360 final long sizeBytes = mContainerService.calculateInstalledSize( 13361 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 13362 13363 try { 13364 mInstaller.freeCache(null, sizeBytes + lowThreshold); 13365 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 13366 installFlags, packageAbiOverride); 13367 } catch (InstallerException e) { 13368 Slog.w(TAG, "Failed to free cache", e); 13369 } 13370 13371 /* 13372 * The cache free must have deleted the file we 13373 * downloaded to install. 13374 * 13375 * TODO: fix the "freeCache" call to not delete 13376 * the file we care about. 13377 */ 13378 if (pkgLite.recommendedInstallLocation 13379 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13380 pkgLite.recommendedInstallLocation 13381 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 13382 } 13383 } 13384 } 13385 13386 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13387 int loc = pkgLite.recommendedInstallLocation; 13388 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 13389 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 13390 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 13391 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 13392 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 13393 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13394 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 13395 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 13396 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 13397 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 13398 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 13399 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 13400 } else { 13401 // Override with defaults if needed. 13402 loc = installLocationPolicy(pkgLite); 13403 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13404 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13405 } else if (!onSd && !onInt) { 13406 // Override install location with flags 13407 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13408 // Set the flag to install on external media. 13409 installFlags |= PackageManager.INSTALL_EXTERNAL; 13410 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13411 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13412 if (DEBUG_EPHEMERAL) { 13413 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13414 } 13415 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13416 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13417 |PackageManager.INSTALL_INTERNAL); 13418 } else { 13419 // Make sure the flag for installing on external 13420 // media is unset 13421 installFlags |= PackageManager.INSTALL_INTERNAL; 13422 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13423 } 13424 } 13425 } 13426 } 13427 13428 final InstallArgs args = createInstallArgs(this); 13429 mArgs = args; 13430 13431 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13432 // TODO: http://b/22976637 13433 // Apps installed for "all" users use the device owner to verify the app 13434 UserHandle verifierUser = getUser(); 13435 if (verifierUser == UserHandle.ALL) { 13436 verifierUser = UserHandle.SYSTEM; 13437 } 13438 13439 /* 13440 * Determine if we have any installed package verifiers. If we 13441 * do, then we'll defer to them to verify the packages. 13442 */ 13443 final int requiredUid = mRequiredVerifierPackage == null ? -1 13444 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13445 verifierUser.getIdentifier()); 13446 if (!origin.existing && requiredUid != -1 13447 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13448 final Intent verification = new Intent( 13449 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13450 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13451 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13452 PACKAGE_MIME_TYPE); 13453 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13454 13455 // Query all live verifiers based on current user state 13456 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13457 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13458 13459 if (DEBUG_VERIFY) { 13460 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13461 + verification.toString() + " with " + pkgLite.verifiers.length 13462 + " optional verifiers"); 13463 } 13464 13465 final int verificationId = mPendingVerificationToken++; 13466 13467 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13468 13469 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13470 installerPackageName); 13471 13472 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13473 installFlags); 13474 13475 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13476 pkgLite.packageName); 13477 13478 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13479 pkgLite.versionCode); 13480 13481 if (verificationInfo != null) { 13482 if (verificationInfo.originatingUri != null) { 13483 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13484 verificationInfo.originatingUri); 13485 } 13486 if (verificationInfo.referrer != null) { 13487 verification.putExtra(Intent.EXTRA_REFERRER, 13488 verificationInfo.referrer); 13489 } 13490 if (verificationInfo.originatingUid >= 0) { 13491 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13492 verificationInfo.originatingUid); 13493 } 13494 if (verificationInfo.installerUid >= 0) { 13495 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13496 verificationInfo.installerUid); 13497 } 13498 } 13499 13500 final PackageVerificationState verificationState = new PackageVerificationState( 13501 requiredUid, args); 13502 13503 mPendingVerification.append(verificationId, verificationState); 13504 13505 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13506 receivers, verificationState); 13507 13508 /* 13509 * If any sufficient verifiers were listed in the package 13510 * manifest, attempt to ask them. 13511 */ 13512 if (sufficientVerifiers != null) { 13513 final int N = sufficientVerifiers.size(); 13514 if (N == 0) { 13515 Slog.i(TAG, "Additional verifiers required, but none installed."); 13516 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13517 } else { 13518 for (int i = 0; i < N; i++) { 13519 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13520 13521 final Intent sufficientIntent = new Intent(verification); 13522 sufficientIntent.setComponent(verifierComponent); 13523 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13524 } 13525 } 13526 } 13527 13528 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13529 mRequiredVerifierPackage, receivers); 13530 if (ret == PackageManager.INSTALL_SUCCEEDED 13531 && mRequiredVerifierPackage != null) { 13532 Trace.asyncTraceBegin( 13533 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13534 /* 13535 * Send the intent to the required verification agent, 13536 * but only start the verification timeout after the 13537 * target BroadcastReceivers have run. 13538 */ 13539 verification.setComponent(requiredVerifierComponent); 13540 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13541 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13542 new BroadcastReceiver() { 13543 @Override 13544 public void onReceive(Context context, Intent intent) { 13545 final Message msg = mHandler 13546 .obtainMessage(CHECK_PENDING_VERIFICATION); 13547 msg.arg1 = verificationId; 13548 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13549 } 13550 }, null, 0, null, null); 13551 13552 /* 13553 * We don't want the copy to proceed until verification 13554 * succeeds, so null out this field. 13555 */ 13556 mArgs = null; 13557 } 13558 } else { 13559 /* 13560 * No package verification is enabled, so immediately start 13561 * the remote call to initiate copy using temporary file. 13562 */ 13563 ret = args.copyApk(mContainerService, true); 13564 } 13565 } 13566 13567 mRet = ret; 13568 } 13569 13570 @Override 13571 void handleReturnCode() { 13572 // If mArgs is null, then MCS couldn't be reached. When it 13573 // reconnects, it will try again to install. At that point, this 13574 // will succeed. 13575 if (mArgs != null) { 13576 processPendingInstall(mArgs, mRet); 13577 } 13578 } 13579 13580 @Override 13581 void handleServiceError() { 13582 mArgs = createInstallArgs(this); 13583 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13584 } 13585 13586 public boolean isForwardLocked() { 13587 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13588 } 13589 } 13590 13591 /** 13592 * Used during creation of InstallArgs 13593 * 13594 * @param installFlags package installation flags 13595 * @return true if should be installed on external storage 13596 */ 13597 private static boolean installOnExternalAsec(int installFlags) { 13598 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13599 return false; 13600 } 13601 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13602 return true; 13603 } 13604 return false; 13605 } 13606 13607 /** 13608 * Used during creation of InstallArgs 13609 * 13610 * @param installFlags package installation flags 13611 * @return true if should be installed as forward locked 13612 */ 13613 private static boolean installForwardLocked(int installFlags) { 13614 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13615 } 13616 13617 private InstallArgs createInstallArgs(InstallParams params) { 13618 if (params.move != null) { 13619 return new MoveInstallArgs(params); 13620 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13621 return new AsecInstallArgs(params); 13622 } else { 13623 return new FileInstallArgs(params); 13624 } 13625 } 13626 13627 /** 13628 * Create args that describe an existing installed package. Typically used 13629 * when cleaning up old installs, or used as a move source. 13630 */ 13631 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13632 String resourcePath, String[] instructionSets) { 13633 final boolean isInAsec; 13634 if (installOnExternalAsec(installFlags)) { 13635 /* Apps on SD card are always in ASEC containers. */ 13636 isInAsec = true; 13637 } else if (installForwardLocked(installFlags) 13638 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13639 /* 13640 * Forward-locked apps are only in ASEC containers if they're the 13641 * new style 13642 */ 13643 isInAsec = true; 13644 } else { 13645 isInAsec = false; 13646 } 13647 13648 if (isInAsec) { 13649 return new AsecInstallArgs(codePath, instructionSets, 13650 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13651 } else { 13652 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13653 } 13654 } 13655 13656 static abstract class InstallArgs { 13657 /** @see InstallParams#origin */ 13658 final OriginInfo origin; 13659 /** @see InstallParams#move */ 13660 final MoveInfo move; 13661 13662 final IPackageInstallObserver2 observer; 13663 // Always refers to PackageManager flags only 13664 final int installFlags; 13665 final String installerPackageName; 13666 final String volumeUuid; 13667 final UserHandle user; 13668 final String abiOverride; 13669 final String[] installGrantPermissions; 13670 /** If non-null, drop an async trace when the install completes */ 13671 final String traceMethod; 13672 final int traceCookie; 13673 final Certificate[][] certificates; 13674 13675 // The list of instruction sets supported by this app. This is currently 13676 // only used during the rmdex() phase to clean up resources. We can get rid of this 13677 // if we move dex files under the common app path. 13678 /* nullable */ String[] instructionSets; 13679 13680 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13681 int installFlags, String installerPackageName, String volumeUuid, 13682 UserHandle user, String[] instructionSets, 13683 String abiOverride, String[] installGrantPermissions, 13684 String traceMethod, int traceCookie, Certificate[][] certificates) { 13685 this.origin = origin; 13686 this.move = move; 13687 this.installFlags = installFlags; 13688 this.observer = observer; 13689 this.installerPackageName = installerPackageName; 13690 this.volumeUuid = volumeUuid; 13691 this.user = user; 13692 this.instructionSets = instructionSets; 13693 this.abiOverride = abiOverride; 13694 this.installGrantPermissions = installGrantPermissions; 13695 this.traceMethod = traceMethod; 13696 this.traceCookie = traceCookie; 13697 this.certificates = certificates; 13698 } 13699 13700 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13701 abstract int doPreInstall(int status); 13702 13703 /** 13704 * Rename package into final resting place. All paths on the given 13705 * scanned package should be updated to reflect the rename. 13706 */ 13707 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13708 abstract int doPostInstall(int status, int uid); 13709 13710 /** @see PackageSettingBase#codePathString */ 13711 abstract String getCodePath(); 13712 /** @see PackageSettingBase#resourcePathString */ 13713 abstract String getResourcePath(); 13714 13715 // Need installer lock especially for dex file removal. 13716 abstract void cleanUpResourcesLI(); 13717 abstract boolean doPostDeleteLI(boolean delete); 13718 13719 /** 13720 * Called before the source arguments are copied. This is used mostly 13721 * for MoveParams when it needs to read the source file to put it in the 13722 * destination. 13723 */ 13724 int doPreCopy() { 13725 return PackageManager.INSTALL_SUCCEEDED; 13726 } 13727 13728 /** 13729 * Called after the source arguments are copied. This is used mostly for 13730 * MoveParams when it needs to read the source file to put it in the 13731 * destination. 13732 */ 13733 int doPostCopy(int uid) { 13734 return PackageManager.INSTALL_SUCCEEDED; 13735 } 13736 13737 protected boolean isFwdLocked() { 13738 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13739 } 13740 13741 protected boolean isExternalAsec() { 13742 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13743 } 13744 13745 protected boolean isEphemeral() { 13746 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13747 } 13748 13749 UserHandle getUser() { 13750 return user; 13751 } 13752 } 13753 13754 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13755 if (!allCodePaths.isEmpty()) { 13756 if (instructionSets == null) { 13757 throw new IllegalStateException("instructionSet == null"); 13758 } 13759 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13760 for (String codePath : allCodePaths) { 13761 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13762 try { 13763 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13764 } catch (InstallerException ignored) { 13765 } 13766 } 13767 } 13768 } 13769 } 13770 13771 /** 13772 * Logic to handle installation of non-ASEC applications, including copying 13773 * and renaming logic. 13774 */ 13775 class FileInstallArgs extends InstallArgs { 13776 private File codeFile; 13777 private File resourceFile; 13778 13779 // Example topology: 13780 // /data/app/com.example/base.apk 13781 // /data/app/com.example/split_foo.apk 13782 // /data/app/com.example/lib/arm/libfoo.so 13783 // /data/app/com.example/lib/arm64/libfoo.so 13784 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13785 13786 /** New install */ 13787 FileInstallArgs(InstallParams params) { 13788 super(params.origin, params.move, params.observer, params.installFlags, 13789 params.installerPackageName, params.volumeUuid, 13790 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13791 params.grantedRuntimePermissions, 13792 params.traceMethod, params.traceCookie, params.certificates); 13793 if (isFwdLocked()) { 13794 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13795 } 13796 } 13797 13798 /** Existing install */ 13799 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13800 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13801 null, null, null, 0, null /*certificates*/); 13802 this.codeFile = (codePath != null) ? new File(codePath) : null; 13803 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13804 } 13805 13806 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13808 try { 13809 return doCopyApk(imcs, temp); 13810 } finally { 13811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13812 } 13813 } 13814 13815 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13816 if (origin.staged) { 13817 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13818 codeFile = origin.file; 13819 resourceFile = origin.file; 13820 return PackageManager.INSTALL_SUCCEEDED; 13821 } 13822 13823 try { 13824 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13825 final File tempDir = 13826 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13827 codeFile = tempDir; 13828 resourceFile = tempDir; 13829 } catch (IOException e) { 13830 Slog.w(TAG, "Failed to create copy file: " + e); 13831 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13832 } 13833 13834 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13835 @Override 13836 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13837 if (!FileUtils.isValidExtFilename(name)) { 13838 throw new IllegalArgumentException("Invalid filename: " + name); 13839 } 13840 try { 13841 final File file = new File(codeFile, name); 13842 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13843 O_RDWR | O_CREAT, 0644); 13844 Os.chmod(file.getAbsolutePath(), 0644); 13845 return new ParcelFileDescriptor(fd); 13846 } catch (ErrnoException e) { 13847 throw new RemoteException("Failed to open: " + e.getMessage()); 13848 } 13849 } 13850 }; 13851 13852 int ret = PackageManager.INSTALL_SUCCEEDED; 13853 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13854 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13855 Slog.e(TAG, "Failed to copy package"); 13856 return ret; 13857 } 13858 13859 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13860 NativeLibraryHelper.Handle handle = null; 13861 try { 13862 handle = NativeLibraryHelper.Handle.create(codeFile); 13863 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13864 abiOverride); 13865 } catch (IOException e) { 13866 Slog.e(TAG, "Copying native libraries failed", e); 13867 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13868 } finally { 13869 IoUtils.closeQuietly(handle); 13870 } 13871 13872 return ret; 13873 } 13874 13875 int doPreInstall(int status) { 13876 if (status != PackageManager.INSTALL_SUCCEEDED) { 13877 cleanUp(); 13878 } 13879 return status; 13880 } 13881 13882 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13883 if (status != PackageManager.INSTALL_SUCCEEDED) { 13884 cleanUp(); 13885 return false; 13886 } 13887 13888 final File targetDir = codeFile.getParentFile(); 13889 final File beforeCodeFile = codeFile; 13890 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13891 13892 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13893 try { 13894 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13895 } catch (ErrnoException e) { 13896 Slog.w(TAG, "Failed to rename", e); 13897 return false; 13898 } 13899 13900 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13901 Slog.w(TAG, "Failed to restorecon"); 13902 return false; 13903 } 13904 13905 // Reflect the rename internally 13906 codeFile = afterCodeFile; 13907 resourceFile = afterCodeFile; 13908 13909 // Reflect the rename in scanned details 13910 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13911 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13912 afterCodeFile, pkg.baseCodePath)); 13913 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13914 afterCodeFile, pkg.splitCodePaths)); 13915 13916 // Reflect the rename in app info 13917 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13918 pkg.setApplicationInfoCodePath(pkg.codePath); 13919 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13920 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13921 pkg.setApplicationInfoResourcePath(pkg.codePath); 13922 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13923 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13924 13925 return true; 13926 } 13927 13928 int doPostInstall(int status, int uid) { 13929 if (status != PackageManager.INSTALL_SUCCEEDED) { 13930 cleanUp(); 13931 } 13932 return status; 13933 } 13934 13935 @Override 13936 String getCodePath() { 13937 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13938 } 13939 13940 @Override 13941 String getResourcePath() { 13942 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13943 } 13944 13945 private boolean cleanUp() { 13946 if (codeFile == null || !codeFile.exists()) { 13947 return false; 13948 } 13949 13950 removeCodePathLI(codeFile); 13951 13952 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13953 resourceFile.delete(); 13954 } 13955 13956 return true; 13957 } 13958 13959 void cleanUpResourcesLI() { 13960 // Try enumerating all code paths before deleting 13961 List<String> allCodePaths = Collections.EMPTY_LIST; 13962 if (codeFile != null && codeFile.exists()) { 13963 try { 13964 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13965 allCodePaths = pkg.getAllCodePaths(); 13966 } catch (PackageParserException e) { 13967 // Ignored; we tried our best 13968 } 13969 } 13970 13971 cleanUp(); 13972 removeDexFiles(allCodePaths, instructionSets); 13973 } 13974 13975 boolean doPostDeleteLI(boolean delete) { 13976 // XXX err, shouldn't we respect the delete flag? 13977 cleanUpResourcesLI(); 13978 return true; 13979 } 13980 } 13981 13982 private boolean isAsecExternal(String cid) { 13983 final String asecPath = PackageHelper.getSdFilesystem(cid); 13984 return !asecPath.startsWith(mAsecInternalPath); 13985 } 13986 13987 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13988 PackageManagerException { 13989 if (copyRet < 0) { 13990 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13991 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13992 throw new PackageManagerException(copyRet, message); 13993 } 13994 } 13995 } 13996 13997 /** 13998 * Extract the StorageManagerService "container ID" from the full code path of an 13999 * .apk. 14000 */ 14001 static String cidFromCodePath(String fullCodePath) { 14002 int eidx = fullCodePath.lastIndexOf("/"); 14003 String subStr1 = fullCodePath.substring(0, eidx); 14004 int sidx = subStr1.lastIndexOf("/"); 14005 return subStr1.substring(sidx+1, eidx); 14006 } 14007 14008 /** 14009 * Logic to handle installation of ASEC applications, including copying and 14010 * renaming logic. 14011 */ 14012 class AsecInstallArgs extends InstallArgs { 14013 static final String RES_FILE_NAME = "pkg.apk"; 14014 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 14015 14016 String cid; 14017 String packagePath; 14018 String resourcePath; 14019 14020 /** New install */ 14021 AsecInstallArgs(InstallParams params) { 14022 super(params.origin, params.move, params.observer, params.installFlags, 14023 params.installerPackageName, params.volumeUuid, 14024 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14025 params.grantedRuntimePermissions, 14026 params.traceMethod, params.traceCookie, params.certificates); 14027 } 14028 14029 /** Existing install */ 14030 AsecInstallArgs(String fullCodePath, String[] instructionSets, 14031 boolean isExternal, boolean isForwardLocked) { 14032 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 14033 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14034 instructionSets, null, null, null, 0, null /*certificates*/); 14035 // Hackily pretend we're still looking at a full code path 14036 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 14037 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 14038 } 14039 14040 // Extract cid from fullCodePath 14041 int eidx = fullCodePath.lastIndexOf("/"); 14042 String subStr1 = fullCodePath.substring(0, eidx); 14043 int sidx = subStr1.lastIndexOf("/"); 14044 cid = subStr1.substring(sidx+1, eidx); 14045 setMountPath(subStr1); 14046 } 14047 14048 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 14049 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 14050 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 14051 instructionSets, null, null, null, 0, null /*certificates*/); 14052 this.cid = cid; 14053 setMountPath(PackageHelper.getSdDir(cid)); 14054 } 14055 14056 void createCopyFile() { 14057 cid = mInstallerService.allocateExternalStageCidLegacy(); 14058 } 14059 14060 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 14061 if (origin.staged && origin.cid != null) { 14062 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 14063 cid = origin.cid; 14064 setMountPath(PackageHelper.getSdDir(cid)); 14065 return PackageManager.INSTALL_SUCCEEDED; 14066 } 14067 14068 if (temp) { 14069 createCopyFile(); 14070 } else { 14071 /* 14072 * Pre-emptively destroy the container since it's destroyed if 14073 * copying fails due to it existing anyway. 14074 */ 14075 PackageHelper.destroySdDir(cid); 14076 } 14077 14078 final String newMountPath = imcs.copyPackageToContainer( 14079 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 14080 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 14081 14082 if (newMountPath != null) { 14083 setMountPath(newMountPath); 14084 return PackageManager.INSTALL_SUCCEEDED; 14085 } else { 14086 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14087 } 14088 } 14089 14090 @Override 14091 String getCodePath() { 14092 return packagePath; 14093 } 14094 14095 @Override 14096 String getResourcePath() { 14097 return resourcePath; 14098 } 14099 14100 int doPreInstall(int status) { 14101 if (status != PackageManager.INSTALL_SUCCEEDED) { 14102 // Destroy container 14103 PackageHelper.destroySdDir(cid); 14104 } else { 14105 boolean mounted = PackageHelper.isContainerMounted(cid); 14106 if (!mounted) { 14107 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 14108 Process.SYSTEM_UID); 14109 if (newMountPath != null) { 14110 setMountPath(newMountPath); 14111 } else { 14112 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14113 } 14114 } 14115 } 14116 return status; 14117 } 14118 14119 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14120 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 14121 String newMountPath = null; 14122 if (PackageHelper.isContainerMounted(cid)) { 14123 // Unmount the container 14124 if (!PackageHelper.unMountSdDir(cid)) { 14125 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 14126 return false; 14127 } 14128 } 14129 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14130 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 14131 " which might be stale. Will try to clean up."); 14132 // Clean up the stale container and proceed to recreate. 14133 if (!PackageHelper.destroySdDir(newCacheId)) { 14134 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 14135 return false; 14136 } 14137 // Successfully cleaned up stale container. Try to rename again. 14138 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 14139 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 14140 + " inspite of cleaning it up."); 14141 return false; 14142 } 14143 } 14144 if (!PackageHelper.isContainerMounted(newCacheId)) { 14145 Slog.w(TAG, "Mounting container " + newCacheId); 14146 newMountPath = PackageHelper.mountSdDir(newCacheId, 14147 getEncryptKey(), Process.SYSTEM_UID); 14148 } else { 14149 newMountPath = PackageHelper.getSdDir(newCacheId); 14150 } 14151 if (newMountPath == null) { 14152 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 14153 return false; 14154 } 14155 Log.i(TAG, "Succesfully renamed " + cid + 14156 " to " + newCacheId + 14157 " at new path: " + newMountPath); 14158 cid = newCacheId; 14159 14160 final File beforeCodeFile = new File(packagePath); 14161 setMountPath(newMountPath); 14162 final File afterCodeFile = new File(packagePath); 14163 14164 // Reflect the rename in scanned details 14165 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 14166 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 14167 afterCodeFile, pkg.baseCodePath)); 14168 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 14169 afterCodeFile, pkg.splitCodePaths)); 14170 14171 // Reflect the rename in app info 14172 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14173 pkg.setApplicationInfoCodePath(pkg.codePath); 14174 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14175 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14176 pkg.setApplicationInfoResourcePath(pkg.codePath); 14177 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14178 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14179 14180 return true; 14181 } 14182 14183 private void setMountPath(String mountPath) { 14184 final File mountFile = new File(mountPath); 14185 14186 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 14187 if (monolithicFile.exists()) { 14188 packagePath = monolithicFile.getAbsolutePath(); 14189 if (isFwdLocked()) { 14190 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 14191 } else { 14192 resourcePath = packagePath; 14193 } 14194 } else { 14195 packagePath = mountFile.getAbsolutePath(); 14196 resourcePath = packagePath; 14197 } 14198 } 14199 14200 int doPostInstall(int status, int uid) { 14201 if (status != PackageManager.INSTALL_SUCCEEDED) { 14202 cleanUp(); 14203 } else { 14204 final int groupOwner; 14205 final String protectedFile; 14206 if (isFwdLocked()) { 14207 groupOwner = UserHandle.getSharedAppGid(uid); 14208 protectedFile = RES_FILE_NAME; 14209 } else { 14210 groupOwner = -1; 14211 protectedFile = null; 14212 } 14213 14214 if (uid < Process.FIRST_APPLICATION_UID 14215 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 14216 Slog.e(TAG, "Failed to finalize " + cid); 14217 PackageHelper.destroySdDir(cid); 14218 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14219 } 14220 14221 boolean mounted = PackageHelper.isContainerMounted(cid); 14222 if (!mounted) { 14223 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 14224 } 14225 } 14226 return status; 14227 } 14228 14229 private void cleanUp() { 14230 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 14231 14232 // Destroy secure container 14233 PackageHelper.destroySdDir(cid); 14234 } 14235 14236 private List<String> getAllCodePaths() { 14237 final File codeFile = new File(getCodePath()); 14238 if (codeFile != null && codeFile.exists()) { 14239 try { 14240 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 14241 return pkg.getAllCodePaths(); 14242 } catch (PackageParserException e) { 14243 // Ignored; we tried our best 14244 } 14245 } 14246 return Collections.EMPTY_LIST; 14247 } 14248 14249 void cleanUpResourcesLI() { 14250 // Enumerate all code paths before deleting 14251 cleanUpResourcesLI(getAllCodePaths()); 14252 } 14253 14254 private void cleanUpResourcesLI(List<String> allCodePaths) { 14255 cleanUp(); 14256 removeDexFiles(allCodePaths, instructionSets); 14257 } 14258 14259 String getPackageName() { 14260 return getAsecPackageName(cid); 14261 } 14262 14263 boolean doPostDeleteLI(boolean delete) { 14264 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 14265 final List<String> allCodePaths = getAllCodePaths(); 14266 boolean mounted = PackageHelper.isContainerMounted(cid); 14267 if (mounted) { 14268 // Unmount first 14269 if (PackageHelper.unMountSdDir(cid)) { 14270 mounted = false; 14271 } 14272 } 14273 if (!mounted && delete) { 14274 cleanUpResourcesLI(allCodePaths); 14275 } 14276 return !mounted; 14277 } 14278 14279 @Override 14280 int doPreCopy() { 14281 if (isFwdLocked()) { 14282 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 14283 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 14284 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14285 } 14286 } 14287 14288 return PackageManager.INSTALL_SUCCEEDED; 14289 } 14290 14291 @Override 14292 int doPostCopy(int uid) { 14293 if (isFwdLocked()) { 14294 if (uid < Process.FIRST_APPLICATION_UID 14295 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 14296 RES_FILE_NAME)) { 14297 Slog.e(TAG, "Failed to finalize " + cid); 14298 PackageHelper.destroySdDir(cid); 14299 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 14300 } 14301 } 14302 14303 return PackageManager.INSTALL_SUCCEEDED; 14304 } 14305 } 14306 14307 /** 14308 * Logic to handle movement of existing installed applications. 14309 */ 14310 class MoveInstallArgs extends InstallArgs { 14311 private File codeFile; 14312 private File resourceFile; 14313 14314 /** New install */ 14315 MoveInstallArgs(InstallParams params) { 14316 super(params.origin, params.move, params.observer, params.installFlags, 14317 params.installerPackageName, params.volumeUuid, 14318 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 14319 params.grantedRuntimePermissions, 14320 params.traceMethod, params.traceCookie, params.certificates); 14321 } 14322 14323 int copyApk(IMediaContainerService imcs, boolean temp) { 14324 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 14325 + move.fromUuid + " to " + move.toUuid); 14326 synchronized (mInstaller) { 14327 try { 14328 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 14329 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 14330 } catch (InstallerException e) { 14331 Slog.w(TAG, "Failed to move app", e); 14332 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 14333 } 14334 } 14335 14336 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 14337 resourceFile = codeFile; 14338 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 14339 14340 return PackageManager.INSTALL_SUCCEEDED; 14341 } 14342 14343 int doPreInstall(int status) { 14344 if (status != PackageManager.INSTALL_SUCCEEDED) { 14345 cleanUp(move.toUuid); 14346 } 14347 return status; 14348 } 14349 14350 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 14351 if (status != PackageManager.INSTALL_SUCCEEDED) { 14352 cleanUp(move.toUuid); 14353 return false; 14354 } 14355 14356 // Reflect the move in app info 14357 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 14358 pkg.setApplicationInfoCodePath(pkg.codePath); 14359 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 14360 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 14361 pkg.setApplicationInfoResourcePath(pkg.codePath); 14362 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 14363 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 14364 14365 return true; 14366 } 14367 14368 int doPostInstall(int status, int uid) { 14369 if (status == PackageManager.INSTALL_SUCCEEDED) { 14370 cleanUp(move.fromUuid); 14371 } else { 14372 cleanUp(move.toUuid); 14373 } 14374 return status; 14375 } 14376 14377 @Override 14378 String getCodePath() { 14379 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 14380 } 14381 14382 @Override 14383 String getResourcePath() { 14384 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 14385 } 14386 14387 private boolean cleanUp(String volumeUuid) { 14388 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 14389 move.dataAppName); 14390 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 14391 final int[] userIds = sUserManager.getUserIds(); 14392 synchronized (mInstallLock) { 14393 // Clean up both app data and code 14394 // All package moves are frozen until finished 14395 for (int userId : userIds) { 14396 try { 14397 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 14398 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 14399 } catch (InstallerException e) { 14400 Slog.w(TAG, String.valueOf(e)); 14401 } 14402 } 14403 removeCodePathLI(codeFile); 14404 } 14405 return true; 14406 } 14407 14408 void cleanUpResourcesLI() { 14409 throw new UnsupportedOperationException(); 14410 } 14411 14412 boolean doPostDeleteLI(boolean delete) { 14413 throw new UnsupportedOperationException(); 14414 } 14415 } 14416 14417 static String getAsecPackageName(String packageCid) { 14418 int idx = packageCid.lastIndexOf("-"); 14419 if (idx == -1) { 14420 return packageCid; 14421 } 14422 return packageCid.substring(0, idx); 14423 } 14424 14425 // Utility method used to create code paths based on package name and available index. 14426 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14427 String idxStr = ""; 14428 int idx = 1; 14429 // Fall back to default value of idx=1 if prefix is not 14430 // part of oldCodePath 14431 if (oldCodePath != null) { 14432 String subStr = oldCodePath; 14433 // Drop the suffix right away 14434 if (suffix != null && subStr.endsWith(suffix)) { 14435 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14436 } 14437 // If oldCodePath already contains prefix find out the 14438 // ending index to either increment or decrement. 14439 int sidx = subStr.lastIndexOf(prefix); 14440 if (sidx != -1) { 14441 subStr = subStr.substring(sidx + prefix.length()); 14442 if (subStr != null) { 14443 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14444 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14445 } 14446 try { 14447 idx = Integer.parseInt(subStr); 14448 if (idx <= 1) { 14449 idx++; 14450 } else { 14451 idx--; 14452 } 14453 } catch(NumberFormatException e) { 14454 } 14455 } 14456 } 14457 } 14458 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14459 return prefix + idxStr; 14460 } 14461 14462 private File getNextCodePath(File targetDir, String packageName) { 14463 File result; 14464 SecureRandom random = new SecureRandom(); 14465 byte[] bytes = new byte[16]; 14466 do { 14467 random.nextBytes(bytes); 14468 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 14469 result = new File(targetDir, packageName + "-" + suffix); 14470 } while (result.exists()); 14471 return result; 14472 } 14473 14474 // Utility method that returns the relative package path with respect 14475 // to the installation directory. Like say for /data/data/com.test-1.apk 14476 // string com.test-1 is returned. 14477 static String deriveCodePathName(String codePath) { 14478 if (codePath == null) { 14479 return null; 14480 } 14481 final File codeFile = new File(codePath); 14482 final String name = codeFile.getName(); 14483 if (codeFile.isDirectory()) { 14484 return name; 14485 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14486 final int lastDot = name.lastIndexOf('.'); 14487 return name.substring(0, lastDot); 14488 } else { 14489 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14490 return null; 14491 } 14492 } 14493 14494 static class PackageInstalledInfo { 14495 String name; 14496 int uid; 14497 // The set of users that originally had this package installed. 14498 int[] origUsers; 14499 // The set of users that now have this package installed. 14500 int[] newUsers; 14501 PackageParser.Package pkg; 14502 int returnCode; 14503 String returnMsg; 14504 PackageRemovedInfo removedInfo; 14505 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14506 14507 public void setError(int code, String msg) { 14508 setReturnCode(code); 14509 setReturnMessage(msg); 14510 Slog.w(TAG, msg); 14511 } 14512 14513 public void setError(String msg, PackageParserException e) { 14514 setReturnCode(e.error); 14515 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14516 Slog.w(TAG, msg, e); 14517 } 14518 14519 public void setError(String msg, PackageManagerException e) { 14520 returnCode = e.error; 14521 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14522 Slog.w(TAG, msg, e); 14523 } 14524 14525 public void setReturnCode(int returnCode) { 14526 this.returnCode = returnCode; 14527 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14528 for (int i = 0; i < childCount; i++) { 14529 addedChildPackages.valueAt(i).returnCode = returnCode; 14530 } 14531 } 14532 14533 private void setReturnMessage(String returnMsg) { 14534 this.returnMsg = returnMsg; 14535 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14536 for (int i = 0; i < childCount; i++) { 14537 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14538 } 14539 } 14540 14541 // In some error cases we want to convey more info back to the observer 14542 String origPackage; 14543 String origPermission; 14544 } 14545 14546 /* 14547 * Install a non-existing package. 14548 */ 14549 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14550 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14551 PackageInstalledInfo res) { 14552 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14553 14554 // Remember this for later, in case we need to rollback this install 14555 String pkgName = pkg.packageName; 14556 14557 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14558 14559 synchronized(mPackages) { 14560 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 14561 if (renamedPackage != null) { 14562 // A package with the same name is already installed, though 14563 // it has been renamed to an older name. The package we 14564 // are trying to install should be installed as an update to 14565 // the existing one, but that has not been requested, so bail. 14566 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14567 + " without first uninstalling package running as " 14568 + renamedPackage); 14569 return; 14570 } 14571 if (mPackages.containsKey(pkgName)) { 14572 // Don't allow installation over an existing package with the same name. 14573 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14574 + " without first uninstalling."); 14575 return; 14576 } 14577 } 14578 14579 try { 14580 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14581 System.currentTimeMillis(), user); 14582 14583 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14584 14585 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14586 prepareAppDataAfterInstallLIF(newPackage); 14587 14588 } else { 14589 // Remove package from internal structures, but keep around any 14590 // data that might have already existed 14591 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14592 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14593 } 14594 } catch (PackageManagerException e) { 14595 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14596 } 14597 14598 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14599 } 14600 14601 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14602 // Can't rotate keys during boot or if sharedUser. 14603 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14604 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14605 return false; 14606 } 14607 // app is using upgradeKeySets; make sure all are valid 14608 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14609 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14610 for (int i = 0; i < upgradeKeySets.length; i++) { 14611 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14612 Slog.wtf(TAG, "Package " 14613 + (oldPs.name != null ? oldPs.name : "<null>") 14614 + " contains upgrade-key-set reference to unknown key-set: " 14615 + upgradeKeySets[i] 14616 + " reverting to signatures check."); 14617 return false; 14618 } 14619 } 14620 return true; 14621 } 14622 14623 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14624 // Upgrade keysets are being used. Determine if new package has a superset of the 14625 // required keys. 14626 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14627 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14628 for (int i = 0; i < upgradeKeySets.length; i++) { 14629 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14630 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14631 return true; 14632 } 14633 } 14634 return false; 14635 } 14636 14637 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14638 try (DigestInputStream digestStream = 14639 new DigestInputStream(new FileInputStream(file), digest)) { 14640 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14641 } 14642 } 14643 14644 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14645 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14646 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14647 14648 final PackageParser.Package oldPackage; 14649 final String pkgName = pkg.packageName; 14650 final int[] allUsers; 14651 final int[] installedUsers; 14652 14653 synchronized(mPackages) { 14654 oldPackage = mPackages.get(pkgName); 14655 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14656 14657 // don't allow upgrade to target a release SDK from a pre-release SDK 14658 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14659 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14660 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14661 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14662 if (oldTargetsPreRelease 14663 && !newTargetsPreRelease 14664 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14665 Slog.w(TAG, "Can't install package targeting released sdk"); 14666 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14667 return; 14668 } 14669 14670 // don't allow an upgrade from full to ephemeral 14671 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14672 if (isEphemeral && !oldIsEphemeral) { 14673 // can't downgrade from full to ephemeral 14674 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14675 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14676 return; 14677 } 14678 14679 // verify signatures are valid 14680 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14681 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14682 if (!checkUpgradeKeySetLP(ps, pkg)) { 14683 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14684 "New package not signed by keys specified by upgrade-keysets: " 14685 + pkgName); 14686 return; 14687 } 14688 } else { 14689 // default to original signature matching 14690 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14691 != PackageManager.SIGNATURE_MATCH) { 14692 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14693 "New package has a different signature: " + pkgName); 14694 return; 14695 } 14696 } 14697 14698 // don't allow a system upgrade unless the upgrade hash matches 14699 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14700 byte[] digestBytes = null; 14701 try { 14702 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14703 updateDigest(digest, new File(pkg.baseCodePath)); 14704 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14705 for (String path : pkg.splitCodePaths) { 14706 updateDigest(digest, new File(path)); 14707 } 14708 } 14709 digestBytes = digest.digest(); 14710 } catch (NoSuchAlgorithmException | IOException e) { 14711 res.setError(INSTALL_FAILED_INVALID_APK, 14712 "Could not compute hash: " + pkgName); 14713 return; 14714 } 14715 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14716 res.setError(INSTALL_FAILED_INVALID_APK, 14717 "New package fails restrict-update check: " + pkgName); 14718 return; 14719 } 14720 // retain upgrade restriction 14721 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14722 } 14723 14724 // Check for shared user id changes 14725 String invalidPackageName = 14726 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14727 if (invalidPackageName != null) { 14728 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14729 "Package " + invalidPackageName + " tried to change user " 14730 + oldPackage.mSharedUserId); 14731 return; 14732 } 14733 14734 // In case of rollback, remember per-user/profile install state 14735 allUsers = sUserManager.getUserIds(); 14736 installedUsers = ps.queryInstalledUsers(allUsers, true); 14737 } 14738 14739 // Update what is removed 14740 res.removedInfo = new PackageRemovedInfo(); 14741 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14742 res.removedInfo.removedPackage = oldPackage.packageName; 14743 res.removedInfo.isUpdate = true; 14744 res.removedInfo.origUsers = installedUsers; 14745 final int childCount = (oldPackage.childPackages != null) 14746 ? oldPackage.childPackages.size() : 0; 14747 for (int i = 0; i < childCount; i++) { 14748 boolean childPackageUpdated = false; 14749 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14750 if (res.addedChildPackages != null) { 14751 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14752 if (childRes != null) { 14753 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14754 childRes.removedInfo.removedPackage = childPkg.packageName; 14755 childRes.removedInfo.isUpdate = true; 14756 childPackageUpdated = true; 14757 } 14758 } 14759 if (!childPackageUpdated) { 14760 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14761 childRemovedRes.removedPackage = childPkg.packageName; 14762 childRemovedRes.isUpdate = false; 14763 childRemovedRes.dataRemoved = true; 14764 synchronized (mPackages) { 14765 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 14766 if (childPs != null) { 14767 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14768 } 14769 } 14770 if (res.removedInfo.removedChildPackages == null) { 14771 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14772 } 14773 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14774 } 14775 } 14776 14777 boolean sysPkg = (isSystemApp(oldPackage)); 14778 if (sysPkg) { 14779 // Set the system/privileged flags as needed 14780 final boolean privileged = 14781 (oldPackage.applicationInfo.privateFlags 14782 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14783 final int systemPolicyFlags = policyFlags 14784 | PackageParser.PARSE_IS_SYSTEM 14785 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14786 14787 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14788 user, allUsers, installerPackageName, res); 14789 } else { 14790 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14791 user, allUsers, installerPackageName, res); 14792 } 14793 } 14794 14795 public List<String> getPreviousCodePaths(String packageName) { 14796 final PackageSetting ps = mSettings.mPackages.get(packageName); 14797 final List<String> result = new ArrayList<String>(); 14798 if (ps != null && ps.oldCodePaths != null) { 14799 result.addAll(ps.oldCodePaths); 14800 } 14801 return result; 14802 } 14803 14804 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14805 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14806 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14807 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14808 + deletedPackage); 14809 14810 String pkgName = deletedPackage.packageName; 14811 boolean deletedPkg = true; 14812 boolean addedPkg = false; 14813 boolean updatedSettings = false; 14814 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14815 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14816 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14817 14818 final long origUpdateTime = (pkg.mExtras != null) 14819 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14820 14821 // First delete the existing package while retaining the data directory 14822 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14823 res.removedInfo, true, pkg)) { 14824 // If the existing package wasn't successfully deleted 14825 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14826 deletedPkg = false; 14827 } else { 14828 // Successfully deleted the old package; proceed with replace. 14829 14830 // If deleted package lived in a container, give users a chance to 14831 // relinquish resources before killing. 14832 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14833 if (DEBUG_INSTALL) { 14834 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14835 } 14836 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14837 final ArrayList<String> pkgList = new ArrayList<String>(1); 14838 pkgList.add(deletedPackage.applicationInfo.packageName); 14839 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14840 } 14841 14842 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14843 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14844 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14845 14846 try { 14847 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14848 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14849 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14850 14851 // Update the in-memory copy of the previous code paths. 14852 PackageSetting ps = mSettings.mPackages.get(pkgName); 14853 if (!killApp) { 14854 if (ps.oldCodePaths == null) { 14855 ps.oldCodePaths = new ArraySet<>(); 14856 } 14857 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14858 if (deletedPackage.splitCodePaths != null) { 14859 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14860 } 14861 } else { 14862 ps.oldCodePaths = null; 14863 } 14864 if (ps.childPackageNames != null) { 14865 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14866 final String childPkgName = ps.childPackageNames.get(i); 14867 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14868 childPs.oldCodePaths = ps.oldCodePaths; 14869 } 14870 } 14871 prepareAppDataAfterInstallLIF(newPackage); 14872 addedPkg = true; 14873 } catch (PackageManagerException e) { 14874 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14875 } 14876 } 14877 14878 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14879 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14880 14881 // Revert all internal state mutations and added folders for the failed install 14882 if (addedPkg) { 14883 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14884 res.removedInfo, true, null); 14885 } 14886 14887 // Restore the old package 14888 if (deletedPkg) { 14889 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14890 File restoreFile = new File(deletedPackage.codePath); 14891 // Parse old package 14892 boolean oldExternal = isExternal(deletedPackage); 14893 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14894 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14895 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14896 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14897 try { 14898 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14899 null); 14900 } catch (PackageManagerException e) { 14901 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14902 + e.getMessage()); 14903 return; 14904 } 14905 14906 synchronized (mPackages) { 14907 // Ensure the installer package name up to date 14908 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14909 14910 // Update permissions for restored package 14911 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14912 14913 mSettings.writeLPr(); 14914 } 14915 14916 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14917 } 14918 } else { 14919 synchronized (mPackages) { 14920 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 14921 if (ps != null) { 14922 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14923 if (res.removedInfo.removedChildPackages != null) { 14924 final int childCount = res.removedInfo.removedChildPackages.size(); 14925 // Iterate in reverse as we may modify the collection 14926 for (int i = childCount - 1; i >= 0; i--) { 14927 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14928 if (res.addedChildPackages.containsKey(childPackageName)) { 14929 res.removedInfo.removedChildPackages.removeAt(i); 14930 } else { 14931 PackageRemovedInfo childInfo = res.removedInfo 14932 .removedChildPackages.valueAt(i); 14933 childInfo.removedForAllUsers = mPackages.get( 14934 childInfo.removedPackage) == null; 14935 } 14936 } 14937 } 14938 } 14939 } 14940 } 14941 } 14942 14943 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14944 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14945 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14946 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14947 + ", old=" + deletedPackage); 14948 14949 final boolean disabledSystem; 14950 14951 // Remove existing system package 14952 removePackageLI(deletedPackage, true); 14953 14954 synchronized (mPackages) { 14955 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14956 } 14957 if (!disabledSystem) { 14958 // We didn't need to disable the .apk as a current system package, 14959 // which means we are replacing another update that is already 14960 // installed. We need to make sure to delete the older one's .apk. 14961 res.removedInfo.args = createInstallArgsForExisting(0, 14962 deletedPackage.applicationInfo.getCodePath(), 14963 deletedPackage.applicationInfo.getResourcePath(), 14964 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14965 } else { 14966 res.removedInfo.args = null; 14967 } 14968 14969 // Successfully disabled the old package. Now proceed with re-installation 14970 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14971 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14972 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14973 14974 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14975 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14976 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14977 14978 PackageParser.Package newPackage = null; 14979 try { 14980 // Add the package to the internal data structures 14981 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14982 14983 // Set the update and install times 14984 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14985 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14986 System.currentTimeMillis()); 14987 14988 // Update the package dynamic state if succeeded 14989 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14990 // Now that the install succeeded make sure we remove data 14991 // directories for any child package the update removed. 14992 final int deletedChildCount = (deletedPackage.childPackages != null) 14993 ? deletedPackage.childPackages.size() : 0; 14994 final int newChildCount = (newPackage.childPackages != null) 14995 ? newPackage.childPackages.size() : 0; 14996 for (int i = 0; i < deletedChildCount; i++) { 14997 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14998 boolean childPackageDeleted = true; 14999 for (int j = 0; j < newChildCount; j++) { 15000 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 15001 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 15002 childPackageDeleted = false; 15003 break; 15004 } 15005 } 15006 if (childPackageDeleted) { 15007 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 15008 deletedChildPkg.packageName); 15009 if (ps != null && res.removedInfo.removedChildPackages != null) { 15010 PackageRemovedInfo removedChildRes = res.removedInfo 15011 .removedChildPackages.get(deletedChildPkg.packageName); 15012 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 15013 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 15014 } 15015 } 15016 } 15017 15018 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 15019 prepareAppDataAfterInstallLIF(newPackage); 15020 } 15021 } catch (PackageManagerException e) { 15022 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 15023 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15024 } 15025 15026 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 15027 // Re installation failed. Restore old information 15028 // Remove new pkg information 15029 if (newPackage != null) { 15030 removeInstalledPackageLI(newPackage, true); 15031 } 15032 // Add back the old system package 15033 try { 15034 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 15035 } catch (PackageManagerException e) { 15036 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 15037 } 15038 15039 synchronized (mPackages) { 15040 if (disabledSystem) { 15041 enableSystemPackageLPw(deletedPackage); 15042 } 15043 15044 // Ensure the installer package name up to date 15045 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 15046 15047 // Update permissions for restored package 15048 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 15049 15050 mSettings.writeLPr(); 15051 } 15052 15053 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 15054 + " after failed upgrade"); 15055 } 15056 } 15057 15058 /** 15059 * Checks whether the parent or any of the child packages have a change shared 15060 * user. For a package to be a valid update the shred users of the parent and 15061 * the children should match. We may later support changing child shared users. 15062 * @param oldPkg The updated package. 15063 * @param newPkg The update package. 15064 * @return The shared user that change between the versions. 15065 */ 15066 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15067 PackageParser.Package newPkg) { 15068 // Check parent shared user 15069 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15070 return newPkg.packageName; 15071 } 15072 // Check child shared users 15073 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15074 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15075 for (int i = 0; i < newChildCount; i++) { 15076 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15077 // If this child was present, did it have the same shared user? 15078 for (int j = 0; j < oldChildCount; j++) { 15079 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15080 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15081 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15082 return newChildPkg.packageName; 15083 } 15084 } 15085 } 15086 return null; 15087 } 15088 15089 private void removeNativeBinariesLI(PackageSetting ps) { 15090 // Remove the lib path for the parent package 15091 if (ps != null) { 15092 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15093 // Remove the lib path for the child packages 15094 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15095 for (int i = 0; i < childCount; i++) { 15096 PackageSetting childPs = null; 15097 synchronized (mPackages) { 15098 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15099 } 15100 if (childPs != null) { 15101 NativeLibraryHelper.removeNativeBinariesLI(childPs 15102 .legacyNativeLibraryPathString); 15103 } 15104 } 15105 } 15106 } 15107 15108 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15109 // Enable the parent package 15110 mSettings.enableSystemPackageLPw(pkg.packageName); 15111 // Enable the child packages 15112 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15113 for (int i = 0; i < childCount; i++) { 15114 PackageParser.Package childPkg = pkg.childPackages.get(i); 15115 mSettings.enableSystemPackageLPw(childPkg.packageName); 15116 } 15117 } 15118 15119 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15120 PackageParser.Package newPkg) { 15121 // Disable the parent package (parent always replaced) 15122 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15123 // Disable the child packages 15124 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15125 for (int i = 0; i < childCount; i++) { 15126 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15127 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15128 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15129 } 15130 return disabled; 15131 } 15132 15133 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15134 String installerPackageName) { 15135 // Enable the parent package 15136 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15137 // Enable the child packages 15138 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15139 for (int i = 0; i < childCount; i++) { 15140 PackageParser.Package childPkg = pkg.childPackages.get(i); 15141 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15142 } 15143 } 15144 15145 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 15146 // Collect all used permissions in the UID 15147 ArraySet<String> usedPermissions = new ArraySet<>(); 15148 final int packageCount = su.packages.size(); 15149 for (int i = 0; i < packageCount; i++) { 15150 PackageSetting ps = su.packages.valueAt(i); 15151 if (ps.pkg == null) { 15152 continue; 15153 } 15154 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 15155 for (int j = 0; j < requestedPermCount; j++) { 15156 String permission = ps.pkg.requestedPermissions.get(j); 15157 BasePermission bp = mSettings.mPermissions.get(permission); 15158 if (bp != null) { 15159 usedPermissions.add(permission); 15160 } 15161 } 15162 } 15163 15164 PermissionsState permissionsState = su.getPermissionsState(); 15165 // Prune install permissions 15166 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 15167 final int installPermCount = installPermStates.size(); 15168 for (int i = installPermCount - 1; i >= 0; i--) { 15169 PermissionState permissionState = installPermStates.get(i); 15170 if (!usedPermissions.contains(permissionState.getName())) { 15171 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15172 if (bp != null) { 15173 permissionsState.revokeInstallPermission(bp); 15174 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 15175 PackageManager.MASK_PERMISSION_FLAGS, 0); 15176 } 15177 } 15178 } 15179 15180 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 15181 15182 // Prune runtime permissions 15183 for (int userId : allUserIds) { 15184 List<PermissionState> runtimePermStates = permissionsState 15185 .getRuntimePermissionStates(userId); 15186 final int runtimePermCount = runtimePermStates.size(); 15187 for (int i = runtimePermCount - 1; i >= 0; i--) { 15188 PermissionState permissionState = runtimePermStates.get(i); 15189 if (!usedPermissions.contains(permissionState.getName())) { 15190 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 15191 if (bp != null) { 15192 permissionsState.revokeRuntimePermission(bp, userId); 15193 permissionsState.updatePermissionFlags(bp, userId, 15194 PackageManager.MASK_PERMISSION_FLAGS, 0); 15195 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 15196 runtimePermissionChangedUserIds, userId); 15197 } 15198 } 15199 } 15200 } 15201 15202 return runtimePermissionChangedUserIds; 15203 } 15204 15205 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15206 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 15207 // Update the parent package setting 15208 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15209 res, user); 15210 // Update the child packages setting 15211 final int childCount = (newPackage.childPackages != null) 15212 ? newPackage.childPackages.size() : 0; 15213 for (int i = 0; i < childCount; i++) { 15214 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15215 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15216 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15217 childRes.origUsers, childRes, user); 15218 } 15219 } 15220 15221 private void updateSettingsInternalLI(PackageParser.Package newPackage, 15222 String installerPackageName, int[] allUsers, int[] installedForUsers, 15223 PackageInstalledInfo res, UserHandle user) { 15224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15225 15226 String pkgName = newPackage.packageName; 15227 synchronized (mPackages) { 15228 //write settings. the installStatus will be incomplete at this stage. 15229 //note that the new package setting would have already been 15230 //added to mPackages. It hasn't been persisted yet. 15231 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 15232 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15233 mSettings.writeLPr(); 15234 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15235 } 15236 15237 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 15238 synchronized (mPackages) { 15239 updatePermissionsLPw(newPackage.packageName, newPackage, 15240 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 15241 ? UPDATE_PERMISSIONS_ALL : 0)); 15242 // For system-bundled packages, we assume that installing an upgraded version 15243 // of the package implies that the user actually wants to run that new code, 15244 // so we enable the package. 15245 PackageSetting ps = mSettings.mPackages.get(pkgName); 15246 final int userId = user.getIdentifier(); 15247 if (ps != null) { 15248 if (isSystemApp(newPackage)) { 15249 if (DEBUG_INSTALL) { 15250 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15251 } 15252 // Enable system package for requested users 15253 if (res.origUsers != null) { 15254 for (int origUserId : res.origUsers) { 15255 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15256 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15257 origUserId, installerPackageName); 15258 } 15259 } 15260 } 15261 // Also convey the prior install/uninstall state 15262 if (allUsers != null && installedForUsers != null) { 15263 for (int currentUserId : allUsers) { 15264 final boolean installed = ArrayUtils.contains( 15265 installedForUsers, currentUserId); 15266 if (DEBUG_INSTALL) { 15267 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15268 } 15269 ps.setInstalled(installed, currentUserId); 15270 } 15271 // these install state changes will be persisted in the 15272 // upcoming call to mSettings.writeLPr(). 15273 } 15274 } 15275 // It's implied that when a user requests installation, they want the app to be 15276 // installed and enabled. 15277 if (userId != UserHandle.USER_ALL) { 15278 ps.setInstalled(true, userId); 15279 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15280 } 15281 } 15282 res.name = pkgName; 15283 res.uid = newPackage.applicationInfo.uid; 15284 res.pkg = newPackage; 15285 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 15286 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15287 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15288 //to update install status 15289 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15290 mSettings.writeLPr(); 15291 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15292 } 15293 15294 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15295 } 15296 15297 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 15298 try { 15299 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 15300 installPackageLI(args, res); 15301 } finally { 15302 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15303 } 15304 } 15305 15306 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 15307 final int installFlags = args.installFlags; 15308 final String installerPackageName = args.installerPackageName; 15309 final String volumeUuid = args.volumeUuid; 15310 final File tmpPackageFile = new File(args.getCodePath()); 15311 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 15312 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 15313 || (args.volumeUuid != null)); 15314 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 15315 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 15316 boolean replace = false; 15317 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 15318 if (args.move != null) { 15319 // moving a complete application; perform an initial scan on the new install location 15320 scanFlags |= SCAN_INITIAL; 15321 } 15322 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 15323 scanFlags |= SCAN_DONT_KILL_APP; 15324 } 15325 15326 // Result object to be returned 15327 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15328 15329 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 15330 15331 // Sanity check 15332 if (ephemeral && (forwardLocked || onExternal)) { 15333 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 15334 + " external=" + onExternal); 15335 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 15336 return; 15337 } 15338 15339 // Retrieve PackageSettings and parse package 15340 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 15341 | PackageParser.PARSE_ENFORCE_CODE 15342 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 15343 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 15344 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 15345 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 15346 PackageParser pp = new PackageParser(); 15347 pp.setSeparateProcesses(mSeparateProcesses); 15348 pp.setDisplayMetrics(mMetrics); 15349 15350 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 15351 final PackageParser.Package pkg; 15352 try { 15353 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 15354 } catch (PackageParserException e) { 15355 res.setError("Failed parse during installPackageLI", e); 15356 return; 15357 } finally { 15358 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15359 } 15360 15361 // If we are installing a clustered package add results for the children 15362 if (pkg.childPackages != null) { 15363 synchronized (mPackages) { 15364 final int childCount = pkg.childPackages.size(); 15365 for (int i = 0; i < childCount; i++) { 15366 PackageParser.Package childPkg = pkg.childPackages.get(i); 15367 PackageInstalledInfo childRes = new PackageInstalledInfo(); 15368 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15369 childRes.pkg = childPkg; 15370 childRes.name = childPkg.packageName; 15371 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15372 if (childPs != null) { 15373 childRes.origUsers = childPs.queryInstalledUsers( 15374 sUserManager.getUserIds(), true); 15375 } 15376 if ((mPackages.containsKey(childPkg.packageName))) { 15377 childRes.removedInfo = new PackageRemovedInfo(); 15378 childRes.removedInfo.removedPackage = childPkg.packageName; 15379 } 15380 if (res.addedChildPackages == null) { 15381 res.addedChildPackages = new ArrayMap<>(); 15382 } 15383 res.addedChildPackages.put(childPkg.packageName, childRes); 15384 } 15385 } 15386 } 15387 15388 // If package doesn't declare API override, mark that we have an install 15389 // time CPU ABI override. 15390 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 15391 pkg.cpuAbiOverride = args.abiOverride; 15392 } 15393 15394 String pkgName = res.name = pkg.packageName; 15395 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 15396 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 15397 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 15398 return; 15399 } 15400 } 15401 15402 try { 15403 // either use what we've been given or parse directly from the APK 15404 if (args.certificates != null) { 15405 try { 15406 PackageParser.populateCertificates(pkg, args.certificates); 15407 } catch (PackageParserException e) { 15408 // there was something wrong with the certificates we were given; 15409 // try to pull them from the APK 15410 PackageParser.collectCertificates(pkg, parseFlags); 15411 } 15412 } else { 15413 PackageParser.collectCertificates(pkg, parseFlags); 15414 } 15415 } catch (PackageParserException e) { 15416 res.setError("Failed collect during installPackageLI", e); 15417 return; 15418 } 15419 15420 // Get rid of all references to package scan path via parser. 15421 pp = null; 15422 String oldCodePath = null; 15423 boolean systemApp = false; 15424 synchronized (mPackages) { 15425 // Check if installing already existing package 15426 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15427 String oldName = mSettings.getRenamedPackageLPr(pkgName); 15428 if (pkg.mOriginalPackages != null 15429 && pkg.mOriginalPackages.contains(oldName) 15430 && mPackages.containsKey(oldName)) { 15431 // This package is derived from an original package, 15432 // and this device has been updating from that original 15433 // name. We must continue using the original name, so 15434 // rename the new package here. 15435 pkg.setPackageName(oldName); 15436 pkgName = pkg.packageName; 15437 replace = true; 15438 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15439 + oldName + " pkgName=" + pkgName); 15440 } else if (mPackages.containsKey(pkgName)) { 15441 // This package, under its official name, already exists 15442 // on the device; we should replace it. 15443 replace = true; 15444 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15445 } 15446 15447 // Child packages are installed through the parent package 15448 if (pkg.parentPackage != null) { 15449 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15450 "Package " + pkg.packageName + " is child of package " 15451 + pkg.parentPackage.parentPackage + ". Child packages " 15452 + "can be updated only through the parent package."); 15453 return; 15454 } 15455 15456 if (replace) { 15457 // Prevent apps opting out from runtime permissions 15458 PackageParser.Package oldPackage = mPackages.get(pkgName); 15459 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15460 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15461 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15462 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15463 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15464 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15465 + " doesn't support runtime permissions but the old" 15466 + " target SDK " + oldTargetSdk + " does."); 15467 return; 15468 } 15469 15470 // Prevent installing of child packages 15471 if (oldPackage.parentPackage != null) { 15472 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15473 "Package " + pkg.packageName + " is child of package " 15474 + oldPackage.parentPackage + ". Child packages " 15475 + "can be updated only through the parent package."); 15476 return; 15477 } 15478 } 15479 } 15480 15481 PackageSetting ps = mSettings.mPackages.get(pkgName); 15482 if (ps != null) { 15483 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15484 15485 // Quick sanity check that we're signed correctly if updating; 15486 // we'll check this again later when scanning, but we want to 15487 // bail early here before tripping over redefined permissions. 15488 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15489 if (!checkUpgradeKeySetLP(ps, pkg)) { 15490 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15491 + pkg.packageName + " upgrade keys do not match the " 15492 + "previously installed version"); 15493 return; 15494 } 15495 } else { 15496 try { 15497 verifySignaturesLP(ps, pkg); 15498 } catch (PackageManagerException e) { 15499 res.setError(e.error, e.getMessage()); 15500 return; 15501 } 15502 } 15503 15504 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15505 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15506 systemApp = (ps.pkg.applicationInfo.flags & 15507 ApplicationInfo.FLAG_SYSTEM) != 0; 15508 } 15509 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15510 } 15511 15512 // Check whether the newly-scanned package wants to define an already-defined perm 15513 int N = pkg.permissions.size(); 15514 for (int i = N-1; i >= 0; i--) { 15515 PackageParser.Permission perm = pkg.permissions.get(i); 15516 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15517 if (bp != null) { 15518 // If the defining package is signed with our cert, it's okay. This 15519 // also includes the "updating the same package" case, of course. 15520 // "updating same package" could also involve key-rotation. 15521 final boolean sigsOk; 15522 if (bp.sourcePackage.equals(pkg.packageName) 15523 && (bp.packageSetting instanceof PackageSetting) 15524 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15525 scanFlags))) { 15526 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15527 } else { 15528 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15529 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15530 } 15531 if (!sigsOk) { 15532 // If the owning package is the system itself, we log but allow 15533 // install to proceed; we fail the install on all other permission 15534 // redefinitions. 15535 if (!bp.sourcePackage.equals("android")) { 15536 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15537 + pkg.packageName + " attempting to redeclare permission " 15538 + perm.info.name + " already owned by " + bp.sourcePackage); 15539 res.origPermission = perm.info.name; 15540 res.origPackage = bp.sourcePackage; 15541 return; 15542 } else { 15543 Slog.w(TAG, "Package " + pkg.packageName 15544 + " attempting to redeclare system permission " 15545 + perm.info.name + "; ignoring new declaration"); 15546 pkg.permissions.remove(i); 15547 } 15548 } 15549 } 15550 } 15551 } 15552 15553 if (systemApp) { 15554 if (onExternal) { 15555 // Abort update; system app can't be replaced with app on sdcard 15556 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15557 "Cannot install updates to system apps on sdcard"); 15558 return; 15559 } else if (ephemeral) { 15560 // Abort update; system app can't be replaced with an ephemeral app 15561 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15562 "Cannot update a system app with an ephemeral app"); 15563 return; 15564 } 15565 } 15566 15567 if (args.move != null) { 15568 // We did an in-place move, so dex is ready to roll 15569 scanFlags |= SCAN_NO_DEX; 15570 scanFlags |= SCAN_MOVE; 15571 15572 synchronized (mPackages) { 15573 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15574 if (ps == null) { 15575 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15576 "Missing settings for moved package " + pkgName); 15577 } 15578 15579 // We moved the entire application as-is, so bring over the 15580 // previously derived ABI information. 15581 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15582 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15583 } 15584 15585 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15586 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15587 scanFlags |= SCAN_NO_DEX; 15588 15589 try { 15590 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15591 args.abiOverride : pkg.cpuAbiOverride); 15592 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15593 true /*extractLibs*/, mAppLib32InstallDir); 15594 } catch (PackageManagerException pme) { 15595 Slog.e(TAG, "Error deriving application ABI", pme); 15596 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15597 return; 15598 } 15599 15600 // Shared libraries for the package need to be updated. 15601 synchronized (mPackages) { 15602 try { 15603 updateSharedLibrariesLPr(pkg, null); 15604 } catch (PackageManagerException e) { 15605 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15606 } 15607 } 15608 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15609 // Do not run PackageDexOptimizer through the local performDexOpt 15610 // method because `pkg` may not be in `mPackages` yet. 15611 // 15612 // Also, don't fail application installs if the dexopt step fails. 15613 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15614 null /* instructionSets */, false /* checkProfiles */, 15615 getCompilerFilterForReason(REASON_INSTALL), 15616 getOrCreateCompilerPackageStats(pkg)); 15617 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15618 15619 // Notify BackgroundDexOptService that the package has been changed. 15620 // If this is an update of a package which used to fail to compile, 15621 // BDOS will remove it from its blacklist. 15622 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15623 } 15624 15625 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15626 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15627 return; 15628 } 15629 15630 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15631 15632 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15633 "installPackageLI")) { 15634 if (replace) { 15635 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15636 installerPackageName, res); 15637 } else { 15638 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15639 args.user, installerPackageName, volumeUuid, res); 15640 } 15641 } 15642 synchronized (mPackages) { 15643 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15644 if (ps != null) { 15645 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15646 } 15647 15648 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15649 for (int i = 0; i < childCount; i++) { 15650 PackageParser.Package childPkg = pkg.childPackages.get(i); 15651 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15652 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15653 if (childPs != null) { 15654 childRes.newUsers = childPs.queryInstalledUsers( 15655 sUserManager.getUserIds(), true); 15656 } 15657 } 15658 } 15659 } 15660 15661 private void startIntentFilterVerifications(int userId, boolean replacing, 15662 PackageParser.Package pkg) { 15663 if (mIntentFilterVerifierComponent == null) { 15664 Slog.w(TAG, "No IntentFilter verification will not be done as " 15665 + "there is no IntentFilterVerifier available!"); 15666 return; 15667 } 15668 15669 final int verifierUid = getPackageUid( 15670 mIntentFilterVerifierComponent.getPackageName(), 15671 MATCH_DEBUG_TRIAGED_MISSING, 15672 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15673 15674 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15675 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15676 mHandler.sendMessage(msg); 15677 15678 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15679 for (int i = 0; i < childCount; i++) { 15680 PackageParser.Package childPkg = pkg.childPackages.get(i); 15681 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15682 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15683 mHandler.sendMessage(msg); 15684 } 15685 } 15686 15687 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15688 PackageParser.Package pkg) { 15689 int size = pkg.activities.size(); 15690 if (size == 0) { 15691 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15692 "No activity, so no need to verify any IntentFilter!"); 15693 return; 15694 } 15695 15696 final boolean hasDomainURLs = hasDomainURLs(pkg); 15697 if (!hasDomainURLs) { 15698 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15699 "No domain URLs, so no need to verify any IntentFilter!"); 15700 return; 15701 } 15702 15703 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15704 + " if any IntentFilter from the " + size 15705 + " Activities needs verification ..."); 15706 15707 int count = 0; 15708 final String packageName = pkg.packageName; 15709 15710 synchronized (mPackages) { 15711 // If this is a new install and we see that we've already run verification for this 15712 // package, we have nothing to do: it means the state was restored from backup. 15713 if (!replacing) { 15714 IntentFilterVerificationInfo ivi = 15715 mSettings.getIntentFilterVerificationLPr(packageName); 15716 if (ivi != null) { 15717 if (DEBUG_DOMAIN_VERIFICATION) { 15718 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15719 + ivi.getStatusString()); 15720 } 15721 return; 15722 } 15723 } 15724 15725 // If any filters need to be verified, then all need to be. 15726 boolean needToVerify = false; 15727 for (PackageParser.Activity a : pkg.activities) { 15728 for (ActivityIntentInfo filter : a.intents) { 15729 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15730 if (DEBUG_DOMAIN_VERIFICATION) { 15731 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15732 } 15733 needToVerify = true; 15734 break; 15735 } 15736 } 15737 } 15738 15739 if (needToVerify) { 15740 final int verificationId = mIntentFilterVerificationToken++; 15741 for (PackageParser.Activity a : pkg.activities) { 15742 for (ActivityIntentInfo filter : a.intents) { 15743 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15744 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15745 "Verification needed for IntentFilter:" + filter.toString()); 15746 mIntentFilterVerifier.addOneIntentFilterVerification( 15747 verifierUid, userId, verificationId, filter, packageName); 15748 count++; 15749 } 15750 } 15751 } 15752 } 15753 } 15754 15755 if (count > 0) { 15756 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15757 + " IntentFilter verification" + (count > 1 ? "s" : "") 15758 + " for userId:" + userId); 15759 mIntentFilterVerifier.startVerifications(userId); 15760 } else { 15761 if (DEBUG_DOMAIN_VERIFICATION) { 15762 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15763 } 15764 } 15765 } 15766 15767 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15768 final ComponentName cn = filter.activity.getComponentName(); 15769 final String packageName = cn.getPackageName(); 15770 15771 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15772 packageName); 15773 if (ivi == null) { 15774 return true; 15775 } 15776 int status = ivi.getStatus(); 15777 switch (status) { 15778 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15779 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15780 return true; 15781 15782 default: 15783 // Nothing to do 15784 return false; 15785 } 15786 } 15787 15788 private static boolean isMultiArch(ApplicationInfo info) { 15789 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15790 } 15791 15792 private static boolean isExternal(PackageParser.Package pkg) { 15793 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15794 } 15795 15796 private static boolean isExternal(PackageSetting ps) { 15797 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15798 } 15799 15800 private static boolean isEphemeral(PackageParser.Package pkg) { 15801 return pkg.applicationInfo.isEphemeralApp(); 15802 } 15803 15804 private static boolean isEphemeral(PackageSetting ps) { 15805 return ps.pkg != null && isEphemeral(ps.pkg); 15806 } 15807 15808 private static boolean isSystemApp(PackageParser.Package pkg) { 15809 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15810 } 15811 15812 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15813 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15814 } 15815 15816 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15817 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15818 } 15819 15820 private static boolean isSystemApp(PackageSetting ps) { 15821 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15822 } 15823 15824 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15825 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15826 } 15827 15828 private int packageFlagsToInstallFlags(PackageSetting ps) { 15829 int installFlags = 0; 15830 if (isEphemeral(ps)) { 15831 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15832 } 15833 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15834 // This existing package was an external ASEC install when we have 15835 // the external flag without a UUID 15836 installFlags |= PackageManager.INSTALL_EXTERNAL; 15837 } 15838 if (ps.isForwardLocked()) { 15839 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15840 } 15841 return installFlags; 15842 } 15843 15844 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15845 if (isExternal(pkg)) { 15846 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15847 return StorageManager.UUID_PRIMARY_PHYSICAL; 15848 } else { 15849 return pkg.volumeUuid; 15850 } 15851 } else { 15852 return StorageManager.UUID_PRIVATE_INTERNAL; 15853 } 15854 } 15855 15856 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15857 if (isExternal(pkg)) { 15858 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15859 return mSettings.getExternalVersion(); 15860 } else { 15861 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15862 } 15863 } else { 15864 return mSettings.getInternalVersion(); 15865 } 15866 } 15867 15868 private void deleteTempPackageFiles() { 15869 final FilenameFilter filter = new FilenameFilter() { 15870 public boolean accept(File dir, String name) { 15871 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15872 } 15873 }; 15874 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15875 file.delete(); 15876 } 15877 } 15878 15879 @Override 15880 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15881 int flags) { 15882 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15883 flags); 15884 } 15885 15886 @Override 15887 public void deletePackage(final String packageName, 15888 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15889 mContext.enforceCallingOrSelfPermission( 15890 android.Manifest.permission.DELETE_PACKAGES, null); 15891 Preconditions.checkNotNull(packageName); 15892 Preconditions.checkNotNull(observer); 15893 final int uid = Binder.getCallingUid(); 15894 if (!isOrphaned(packageName) 15895 && !isCallerAllowedToSilentlyUninstall(uid, packageName)) { 15896 try { 15897 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 15898 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 15899 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 15900 observer.onUserActionRequired(intent); 15901 } catch (RemoteException re) { 15902 } 15903 return; 15904 } 15905 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15906 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15907 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15908 mContext.enforceCallingOrSelfPermission( 15909 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15910 "deletePackage for user " + userId); 15911 } 15912 15913 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15914 try { 15915 observer.onPackageDeleted(packageName, 15916 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15917 } catch (RemoteException re) { 15918 } 15919 return; 15920 } 15921 15922 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15923 try { 15924 observer.onPackageDeleted(packageName, 15925 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15926 } catch (RemoteException re) { 15927 } 15928 return; 15929 } 15930 15931 if (DEBUG_REMOVE) { 15932 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15933 + " deleteAllUsers: " + deleteAllUsers ); 15934 } 15935 // Queue up an async operation since the package deletion may take a little while. 15936 mHandler.post(new Runnable() { 15937 public void run() { 15938 mHandler.removeCallbacks(this); 15939 int returnCode; 15940 if (!deleteAllUsers) { 15941 returnCode = deletePackageX(packageName, userId, deleteFlags); 15942 } else { 15943 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15944 // If nobody is blocking uninstall, proceed with delete for all users 15945 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15946 returnCode = deletePackageX(packageName, userId, deleteFlags); 15947 } else { 15948 // Otherwise uninstall individually for users with blockUninstalls=false 15949 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15950 for (int userId : users) { 15951 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15952 returnCode = deletePackageX(packageName, userId, userFlags); 15953 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15954 Slog.w(TAG, "Package delete failed for user " + userId 15955 + ", returnCode " + returnCode); 15956 } 15957 } 15958 } 15959 // The app has only been marked uninstalled for certain users. 15960 // We still need to report that delete was blocked 15961 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15962 } 15963 } 15964 try { 15965 observer.onPackageDeleted(packageName, returnCode, null); 15966 } catch (RemoteException e) { 15967 Log.i(TAG, "Observer no longer exists."); 15968 } //end catch 15969 } //end run 15970 }); 15971 } 15972 15973 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 15974 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 15975 || callingUid == Process.SYSTEM_UID) { 15976 return true; 15977 } 15978 final int callingUserId = UserHandle.getUserId(callingUid); 15979 // If the caller installed the pkgName, then allow it to silently uninstall. 15980 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 15981 return true; 15982 } 15983 15984 // Allow package verifier to silently uninstall. 15985 if (mRequiredVerifierPackage != null && 15986 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 15987 return true; 15988 } 15989 15990 // Allow package uninstaller to silently uninstall. 15991 if (mRequiredUninstallerPackage != null && 15992 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 15993 return true; 15994 } 15995 15996 // Allow storage manager to silently uninstall. 15997 if (mStorageManagerPackage != null && 15998 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 15999 return true; 16000 } 16001 return false; 16002 } 16003 16004 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 16005 int[] result = EMPTY_INT_ARRAY; 16006 for (int userId : userIds) { 16007 if (getBlockUninstallForUser(packageName, userId)) { 16008 result = ArrayUtils.appendInt(result, userId); 16009 } 16010 } 16011 return result; 16012 } 16013 16014 @Override 16015 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 16016 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 16017 } 16018 16019 private boolean isPackageDeviceAdmin(String packageName, int userId) { 16020 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 16021 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 16022 try { 16023 if (dpm != null) { 16024 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 16025 /* callingUserOnly =*/ false); 16026 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 16027 : deviceOwnerComponentName.getPackageName(); 16028 // Does the package contains the device owner? 16029 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 16030 // this check is probably not needed, since DO should be registered as a device 16031 // admin on some user too. (Original bug for this: b/17657954) 16032 if (packageName.equals(deviceOwnerPackageName)) { 16033 return true; 16034 } 16035 // Does it contain a device admin for any user? 16036 int[] users; 16037 if (userId == UserHandle.USER_ALL) { 16038 users = sUserManager.getUserIds(); 16039 } else { 16040 users = new int[]{userId}; 16041 } 16042 for (int i = 0; i < users.length; ++i) { 16043 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 16044 return true; 16045 } 16046 } 16047 } 16048 } catch (RemoteException e) { 16049 } 16050 return false; 16051 } 16052 16053 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 16054 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 16055 } 16056 16057 /** 16058 * This method is an internal method that could be get invoked either 16059 * to delete an installed package or to clean up a failed installation. 16060 * After deleting an installed package, a broadcast is sent to notify any 16061 * listeners that the package has been removed. For cleaning up a failed 16062 * installation, the broadcast is not necessary since the package's 16063 * installation wouldn't have sent the initial broadcast either 16064 * The key steps in deleting a package are 16065 * deleting the package information in internal structures like mPackages, 16066 * deleting the packages base directories through installd 16067 * updating mSettings to reflect current status 16068 * persisting settings for later use 16069 * sending a broadcast if necessary 16070 */ 16071 private int deletePackageX(String packageName, int userId, int deleteFlags) { 16072 final PackageRemovedInfo info = new PackageRemovedInfo(); 16073 final boolean res; 16074 16075 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 16076 ? UserHandle.USER_ALL : userId; 16077 16078 if (isPackageDeviceAdmin(packageName, removeUser)) { 16079 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 16080 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 16081 } 16082 16083 PackageSetting uninstalledPs = null; 16084 16085 // for the uninstall-updates case and restricted profiles, remember the per- 16086 // user handle installed state 16087 int[] allUsers; 16088 synchronized (mPackages) { 16089 uninstalledPs = mSettings.mPackages.get(packageName); 16090 if (uninstalledPs == null) { 16091 Slog.w(TAG, "Not removing non-existent package " + packageName); 16092 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16093 } 16094 allUsers = sUserManager.getUserIds(); 16095 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 16096 } 16097 16098 final int freezeUser; 16099 if (isUpdatedSystemApp(uninstalledPs) 16100 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 16101 // We're downgrading a system app, which will apply to all users, so 16102 // freeze them all during the downgrade 16103 freezeUser = UserHandle.USER_ALL; 16104 } else { 16105 freezeUser = removeUser; 16106 } 16107 16108 synchronized (mInstallLock) { 16109 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 16110 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 16111 deleteFlags, "deletePackageX")) { 16112 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 16113 deleteFlags | REMOVE_CHATTY, info, true, null); 16114 } 16115 synchronized (mPackages) { 16116 if (res) { 16117 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 16118 } 16119 } 16120 } 16121 16122 if (res) { 16123 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 16124 info.sendPackageRemovedBroadcasts(killApp); 16125 info.sendSystemPackageUpdatedBroadcasts(); 16126 info.sendSystemPackageAppearedBroadcasts(); 16127 } 16128 // Force a gc here. 16129 Runtime.getRuntime().gc(); 16130 // Delete the resources here after sending the broadcast to let 16131 // other processes clean up before deleting resources. 16132 if (info.args != null) { 16133 synchronized (mInstallLock) { 16134 info.args.doPostDeleteLI(true); 16135 } 16136 } 16137 16138 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 16139 } 16140 16141 class PackageRemovedInfo { 16142 String removedPackage; 16143 int uid = -1; 16144 int removedAppId = -1; 16145 int[] origUsers; 16146 int[] removedUsers = null; 16147 boolean isRemovedPackageSystemUpdate = false; 16148 boolean isUpdate; 16149 boolean dataRemoved; 16150 boolean removedForAllUsers; 16151 // Clean up resources deleted packages. 16152 InstallArgs args = null; 16153 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 16154 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 16155 16156 void sendPackageRemovedBroadcasts(boolean killApp) { 16157 sendPackageRemovedBroadcastInternal(killApp); 16158 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 16159 for (int i = 0; i < childCount; i++) { 16160 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16161 childInfo.sendPackageRemovedBroadcastInternal(killApp); 16162 } 16163 } 16164 16165 void sendSystemPackageUpdatedBroadcasts() { 16166 if (isRemovedPackageSystemUpdate) { 16167 sendSystemPackageUpdatedBroadcastsInternal(); 16168 final int childCount = (removedChildPackages != null) 16169 ? removedChildPackages.size() : 0; 16170 for (int i = 0; i < childCount; i++) { 16171 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 16172 if (childInfo.isRemovedPackageSystemUpdate) { 16173 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 16174 } 16175 } 16176 } 16177 } 16178 16179 void sendSystemPackageAppearedBroadcasts() { 16180 final int packageCount = (appearedChildPackages != null) 16181 ? appearedChildPackages.size() : 0; 16182 for (int i = 0; i < packageCount; i++) { 16183 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 16184 sendPackageAddedForNewUsers(installedInfo.name, true, 16185 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers); 16186 } 16187 } 16188 16189 private void sendSystemPackageUpdatedBroadcastsInternal() { 16190 Bundle extras = new Bundle(2); 16191 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16192 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16193 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 16194 extras, 0, null, null, null); 16195 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 16196 extras, 0, null, null, null); 16197 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 16198 null, 0, removedPackage, null, null); 16199 } 16200 16201 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 16202 Bundle extras = new Bundle(2); 16203 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 16204 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 16205 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 16206 if (isUpdate || isRemovedPackageSystemUpdate) { 16207 extras.putBoolean(Intent.EXTRA_REPLACING, true); 16208 } 16209 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 16210 if (removedPackage != null) { 16211 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 16212 extras, 0, null, null, removedUsers); 16213 if (dataRemoved && !isRemovedPackageSystemUpdate) { 16214 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 16215 removedPackage, extras, 0, null, null, removedUsers); 16216 } 16217 } 16218 if (removedAppId >= 0) { 16219 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 16220 removedUsers); 16221 } 16222 } 16223 } 16224 16225 /* 16226 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 16227 * flag is not set, the data directory is removed as well. 16228 * make sure this flag is set for partially installed apps. If not its meaningless to 16229 * delete a partially installed application. 16230 */ 16231 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 16232 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 16233 String packageName = ps.name; 16234 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 16235 // Retrieve object to delete permissions for shared user later on 16236 final PackageParser.Package deletedPkg; 16237 final PackageSetting deletedPs; 16238 // reader 16239 synchronized (mPackages) { 16240 deletedPkg = mPackages.get(packageName); 16241 deletedPs = mSettings.mPackages.get(packageName); 16242 if (outInfo != null) { 16243 outInfo.removedPackage = packageName; 16244 outInfo.removedUsers = deletedPs != null 16245 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 16246 : null; 16247 } 16248 } 16249 16250 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 16251 16252 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 16253 final PackageParser.Package resolvedPkg; 16254 if (deletedPkg != null) { 16255 resolvedPkg = deletedPkg; 16256 } else { 16257 // We don't have a parsed package when it lives on an ejected 16258 // adopted storage device, so fake something together 16259 resolvedPkg = new PackageParser.Package(ps.name); 16260 resolvedPkg.setVolumeUuid(ps.volumeUuid); 16261 } 16262 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 16263 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16264 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 16265 if (outInfo != null) { 16266 outInfo.dataRemoved = true; 16267 } 16268 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 16269 } 16270 16271 // writer 16272 synchronized (mPackages) { 16273 if (deletedPs != null) { 16274 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 16275 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 16276 clearDefaultBrowserIfNeeded(packageName); 16277 if (outInfo != null) { 16278 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 16279 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 16280 } 16281 updatePermissionsLPw(deletedPs.name, null, 0); 16282 if (deletedPs.sharedUser != null) { 16283 // Remove permissions associated with package. Since runtime 16284 // permissions are per user we have to kill the removed package 16285 // or packages running under the shared user of the removed 16286 // package if revoking the permissions requested only by the removed 16287 // package is successful and this causes a change in gids. 16288 for (int userId : UserManagerService.getInstance().getUserIds()) { 16289 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 16290 userId); 16291 if (userIdToKill == UserHandle.USER_ALL 16292 || userIdToKill >= UserHandle.USER_SYSTEM) { 16293 // If gids changed for this user, kill all affected packages. 16294 mHandler.post(new Runnable() { 16295 @Override 16296 public void run() { 16297 // This has to happen with no lock held. 16298 killApplication(deletedPs.name, deletedPs.appId, 16299 KILL_APP_REASON_GIDS_CHANGED); 16300 } 16301 }); 16302 break; 16303 } 16304 } 16305 } 16306 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 16307 } 16308 // make sure to preserve per-user disabled state if this removal was just 16309 // a downgrade of a system app to the factory package 16310 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 16311 if (DEBUG_REMOVE) { 16312 Slog.d(TAG, "Propagating install state across downgrade"); 16313 } 16314 for (int userId : allUserHandles) { 16315 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16316 if (DEBUG_REMOVE) { 16317 Slog.d(TAG, " user " + userId + " => " + installed); 16318 } 16319 ps.setInstalled(installed, userId); 16320 } 16321 } 16322 } 16323 // can downgrade to reader 16324 if (writeSettings) { 16325 // Save settings now 16326 mSettings.writeLPr(); 16327 } 16328 } 16329 if (outInfo != null) { 16330 // A user ID was deleted here. Go through all users and remove it 16331 // from KeyStore. 16332 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 16333 } 16334 } 16335 16336 static boolean locationIsPrivileged(File path) { 16337 try { 16338 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 16339 .getCanonicalPath(); 16340 return path.getCanonicalPath().startsWith(privilegedAppDir); 16341 } catch (IOException e) { 16342 Slog.e(TAG, "Unable to access code path " + path); 16343 } 16344 return false; 16345 } 16346 16347 /* 16348 * Tries to delete system package. 16349 */ 16350 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 16351 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 16352 boolean writeSettings) { 16353 if (deletedPs.parentPackageName != null) { 16354 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 16355 return false; 16356 } 16357 16358 final boolean applyUserRestrictions 16359 = (allUserHandles != null) && (outInfo.origUsers != null); 16360 final PackageSetting disabledPs; 16361 // Confirm if the system package has been updated 16362 // An updated system app can be deleted. This will also have to restore 16363 // the system pkg from system partition 16364 // reader 16365 synchronized (mPackages) { 16366 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 16367 } 16368 16369 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 16370 + " disabledPs=" + disabledPs); 16371 16372 if (disabledPs == null) { 16373 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 16374 return false; 16375 } else if (DEBUG_REMOVE) { 16376 Slog.d(TAG, "Deleting system pkg from data partition"); 16377 } 16378 16379 if (DEBUG_REMOVE) { 16380 if (applyUserRestrictions) { 16381 Slog.d(TAG, "Remembering install states:"); 16382 for (int userId : allUserHandles) { 16383 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 16384 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 16385 } 16386 } 16387 } 16388 16389 // Delete the updated package 16390 outInfo.isRemovedPackageSystemUpdate = true; 16391 if (outInfo.removedChildPackages != null) { 16392 final int childCount = (deletedPs.childPackageNames != null) 16393 ? deletedPs.childPackageNames.size() : 0; 16394 for (int i = 0; i < childCount; i++) { 16395 String childPackageName = deletedPs.childPackageNames.get(i); 16396 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 16397 .contains(childPackageName)) { 16398 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16399 childPackageName); 16400 if (childInfo != null) { 16401 childInfo.isRemovedPackageSystemUpdate = true; 16402 } 16403 } 16404 } 16405 } 16406 16407 if (disabledPs.versionCode < deletedPs.versionCode) { 16408 // Delete data for downgrades 16409 flags &= ~PackageManager.DELETE_KEEP_DATA; 16410 } else { 16411 // Preserve data by setting flag 16412 flags |= PackageManager.DELETE_KEEP_DATA; 16413 } 16414 16415 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 16416 outInfo, writeSettings, disabledPs.pkg); 16417 if (!ret) { 16418 return false; 16419 } 16420 16421 // writer 16422 synchronized (mPackages) { 16423 // Reinstate the old system package 16424 enableSystemPackageLPw(disabledPs.pkg); 16425 // Remove any native libraries from the upgraded package. 16426 removeNativeBinariesLI(deletedPs); 16427 } 16428 16429 // Install the system package 16430 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 16431 int parseFlags = mDefParseFlags 16432 | PackageParser.PARSE_MUST_BE_APK 16433 | PackageParser.PARSE_IS_SYSTEM 16434 | PackageParser.PARSE_IS_SYSTEM_DIR; 16435 if (locationIsPrivileged(disabledPs.codePath)) { 16436 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 16437 } 16438 16439 final PackageParser.Package newPkg; 16440 try { 16441 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, 0 /* scanFlags */, 16442 0 /* currentTime */, null); 16443 } catch (PackageManagerException e) { 16444 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 16445 + e.getMessage()); 16446 return false; 16447 } 16448 try { 16449 // update shared libraries for the newly re-installed system package 16450 updateSharedLibrariesLPr(newPkg, null); 16451 } catch (PackageManagerException e) { 16452 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16453 } 16454 16455 prepareAppDataAfterInstallLIF(newPkg); 16456 16457 // writer 16458 synchronized (mPackages) { 16459 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16460 16461 // Propagate the permissions state as we do not want to drop on the floor 16462 // runtime permissions. The update permissions method below will take 16463 // care of removing obsolete permissions and grant install permissions. 16464 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16465 updatePermissionsLPw(newPkg.packageName, newPkg, 16466 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16467 16468 if (applyUserRestrictions) { 16469 if (DEBUG_REMOVE) { 16470 Slog.d(TAG, "Propagating install state across reinstall"); 16471 } 16472 for (int userId : allUserHandles) { 16473 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16474 if (DEBUG_REMOVE) { 16475 Slog.d(TAG, " user " + userId + " => " + installed); 16476 } 16477 ps.setInstalled(installed, userId); 16478 16479 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16480 } 16481 // Regardless of writeSettings we need to ensure that this restriction 16482 // state propagation is persisted 16483 mSettings.writeAllUsersPackageRestrictionsLPr(); 16484 } 16485 // can downgrade to reader here 16486 if (writeSettings) { 16487 mSettings.writeLPr(); 16488 } 16489 } 16490 return true; 16491 } 16492 16493 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16494 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16495 PackageRemovedInfo outInfo, boolean writeSettings, 16496 PackageParser.Package replacingPackage) { 16497 synchronized (mPackages) { 16498 if (outInfo != null) { 16499 outInfo.uid = ps.appId; 16500 } 16501 16502 if (outInfo != null && outInfo.removedChildPackages != null) { 16503 final int childCount = (ps.childPackageNames != null) 16504 ? ps.childPackageNames.size() : 0; 16505 for (int i = 0; i < childCount; i++) { 16506 String childPackageName = ps.childPackageNames.get(i); 16507 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16508 if (childPs == null) { 16509 return false; 16510 } 16511 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16512 childPackageName); 16513 if (childInfo != null) { 16514 childInfo.uid = childPs.appId; 16515 } 16516 } 16517 } 16518 } 16519 16520 // Delete package data from internal structures and also remove data if flag is set 16521 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16522 16523 // Delete the child packages data 16524 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16525 for (int i = 0; i < childCount; i++) { 16526 PackageSetting childPs; 16527 synchronized (mPackages) { 16528 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16529 } 16530 if (childPs != null) { 16531 PackageRemovedInfo childOutInfo = (outInfo != null 16532 && outInfo.removedChildPackages != null) 16533 ? outInfo.removedChildPackages.get(childPs.name) : null; 16534 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16535 && (replacingPackage != null 16536 && !replacingPackage.hasChildPackage(childPs.name)) 16537 ? flags & ~DELETE_KEEP_DATA : flags; 16538 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16539 deleteFlags, writeSettings); 16540 } 16541 } 16542 16543 // Delete application code and resources only for parent packages 16544 if (ps.parentPackageName == null) { 16545 if (deleteCodeAndResources && (outInfo != null)) { 16546 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16547 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16548 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16549 } 16550 } 16551 16552 return true; 16553 } 16554 16555 @Override 16556 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16557 int userId) { 16558 mContext.enforceCallingOrSelfPermission( 16559 android.Manifest.permission.DELETE_PACKAGES, null); 16560 synchronized (mPackages) { 16561 PackageSetting ps = mSettings.mPackages.get(packageName); 16562 if (ps == null) { 16563 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16564 return false; 16565 } 16566 if (!ps.getInstalled(userId)) { 16567 // Can't block uninstall for an app that is not installed or enabled. 16568 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16569 return false; 16570 } 16571 ps.setBlockUninstall(blockUninstall, userId); 16572 mSettings.writePackageRestrictionsLPr(userId); 16573 } 16574 return true; 16575 } 16576 16577 @Override 16578 public boolean getBlockUninstallForUser(String packageName, int userId) { 16579 synchronized (mPackages) { 16580 PackageSetting ps = mSettings.mPackages.get(packageName); 16581 if (ps == null) { 16582 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16583 return false; 16584 } 16585 return ps.getBlockUninstall(userId); 16586 } 16587 } 16588 16589 @Override 16590 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16591 int callingUid = Binder.getCallingUid(); 16592 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16593 throw new SecurityException( 16594 "setRequiredForSystemUser can only be run by the system or root"); 16595 } 16596 synchronized (mPackages) { 16597 PackageSetting ps = mSettings.mPackages.get(packageName); 16598 if (ps == null) { 16599 Log.w(TAG, "Package doesn't exist: " + packageName); 16600 return false; 16601 } 16602 if (systemUserApp) { 16603 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16604 } else { 16605 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16606 } 16607 mSettings.writeLPr(); 16608 } 16609 return true; 16610 } 16611 16612 /* 16613 * This method handles package deletion in general 16614 */ 16615 private boolean deletePackageLIF(String packageName, UserHandle user, 16616 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16617 PackageRemovedInfo outInfo, boolean writeSettings, 16618 PackageParser.Package replacingPackage) { 16619 if (packageName == null) { 16620 Slog.w(TAG, "Attempt to delete null packageName."); 16621 return false; 16622 } 16623 16624 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16625 16626 PackageSetting ps; 16627 16628 synchronized (mPackages) { 16629 ps = mSettings.mPackages.get(packageName); 16630 if (ps == null) { 16631 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16632 return false; 16633 } 16634 16635 if (ps.parentPackageName != null && (!isSystemApp(ps) 16636 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16637 if (DEBUG_REMOVE) { 16638 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16639 + ((user == null) ? UserHandle.USER_ALL : user)); 16640 } 16641 final int removedUserId = (user != null) ? user.getIdentifier() 16642 : UserHandle.USER_ALL; 16643 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16644 return false; 16645 } 16646 markPackageUninstalledForUserLPw(ps, user); 16647 scheduleWritePackageRestrictionsLocked(user); 16648 return true; 16649 } 16650 } 16651 16652 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16653 && user.getIdentifier() != UserHandle.USER_ALL)) { 16654 // The caller is asking that the package only be deleted for a single 16655 // user. To do this, we just mark its uninstalled state and delete 16656 // its data. If this is a system app, we only allow this to happen if 16657 // they have set the special DELETE_SYSTEM_APP which requests different 16658 // semantics than normal for uninstalling system apps. 16659 markPackageUninstalledForUserLPw(ps, user); 16660 16661 if (!isSystemApp(ps)) { 16662 // Do not uninstall the APK if an app should be cached 16663 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16664 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16665 // Other user still have this package installed, so all 16666 // we need to do is clear this user's data and save that 16667 // it is uninstalled. 16668 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16669 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16670 return false; 16671 } 16672 scheduleWritePackageRestrictionsLocked(user); 16673 return true; 16674 } else { 16675 // We need to set it back to 'installed' so the uninstall 16676 // broadcasts will be sent correctly. 16677 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16678 ps.setInstalled(true, user.getIdentifier()); 16679 } 16680 } else { 16681 // This is a system app, so we assume that the 16682 // other users still have this package installed, so all 16683 // we need to do is clear this user's data and save that 16684 // it is uninstalled. 16685 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16686 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16687 return false; 16688 } 16689 scheduleWritePackageRestrictionsLocked(user); 16690 return true; 16691 } 16692 } 16693 16694 // If we are deleting a composite package for all users, keep track 16695 // of result for each child. 16696 if (ps.childPackageNames != null && outInfo != null) { 16697 synchronized (mPackages) { 16698 final int childCount = ps.childPackageNames.size(); 16699 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16700 for (int i = 0; i < childCount; i++) { 16701 String childPackageName = ps.childPackageNames.get(i); 16702 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16703 childInfo.removedPackage = childPackageName; 16704 outInfo.removedChildPackages.put(childPackageName, childInfo); 16705 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16706 if (childPs != null) { 16707 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16708 } 16709 } 16710 } 16711 } 16712 16713 boolean ret = false; 16714 if (isSystemApp(ps)) { 16715 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16716 // When an updated system application is deleted we delete the existing resources 16717 // as well and fall back to existing code in system partition 16718 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16719 } else { 16720 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16721 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16722 outInfo, writeSettings, replacingPackage); 16723 } 16724 16725 // Take a note whether we deleted the package for all users 16726 if (outInfo != null) { 16727 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16728 if (outInfo.removedChildPackages != null) { 16729 synchronized (mPackages) { 16730 final int childCount = outInfo.removedChildPackages.size(); 16731 for (int i = 0; i < childCount; i++) { 16732 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16733 if (childInfo != null) { 16734 childInfo.removedForAllUsers = mPackages.get( 16735 childInfo.removedPackage) == null; 16736 } 16737 } 16738 } 16739 } 16740 // If we uninstalled an update to a system app there may be some 16741 // child packages that appeared as they are declared in the system 16742 // app but were not declared in the update. 16743 if (isSystemApp(ps)) { 16744 synchronized (mPackages) { 16745 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 16746 final int childCount = (updatedPs.childPackageNames != null) 16747 ? updatedPs.childPackageNames.size() : 0; 16748 for (int i = 0; i < childCount; i++) { 16749 String childPackageName = updatedPs.childPackageNames.get(i); 16750 if (outInfo.removedChildPackages == null 16751 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16752 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 16753 if (childPs == null) { 16754 continue; 16755 } 16756 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16757 installRes.name = childPackageName; 16758 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16759 installRes.pkg = mPackages.get(childPackageName); 16760 installRes.uid = childPs.pkg.applicationInfo.uid; 16761 if (outInfo.appearedChildPackages == null) { 16762 outInfo.appearedChildPackages = new ArrayMap<>(); 16763 } 16764 outInfo.appearedChildPackages.put(childPackageName, installRes); 16765 } 16766 } 16767 } 16768 } 16769 } 16770 16771 return ret; 16772 } 16773 16774 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16775 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16776 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16777 for (int nextUserId : userIds) { 16778 if (DEBUG_REMOVE) { 16779 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16780 } 16781 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16782 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16783 false /*hidden*/, false /*suspended*/, null, null, null, 16784 false /*blockUninstall*/, 16785 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16786 } 16787 } 16788 16789 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16790 PackageRemovedInfo outInfo) { 16791 final PackageParser.Package pkg; 16792 synchronized (mPackages) { 16793 pkg = mPackages.get(ps.name); 16794 } 16795 16796 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16797 : new int[] {userId}; 16798 for (int nextUserId : userIds) { 16799 if (DEBUG_REMOVE) { 16800 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16801 + nextUserId); 16802 } 16803 16804 destroyAppDataLIF(pkg, userId, 16805 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16806 destroyAppProfilesLIF(pkg, userId); 16807 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16808 schedulePackageCleaning(ps.name, nextUserId, false); 16809 synchronized (mPackages) { 16810 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16811 scheduleWritePackageRestrictionsLocked(nextUserId); 16812 } 16813 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16814 } 16815 } 16816 16817 if (outInfo != null) { 16818 outInfo.removedPackage = ps.name; 16819 outInfo.removedAppId = ps.appId; 16820 outInfo.removedUsers = userIds; 16821 } 16822 16823 return true; 16824 } 16825 16826 private final class ClearStorageConnection implements ServiceConnection { 16827 IMediaContainerService mContainerService; 16828 16829 @Override 16830 public void onServiceConnected(ComponentName name, IBinder service) { 16831 synchronized (this) { 16832 mContainerService = IMediaContainerService.Stub 16833 .asInterface(Binder.allowBlocking(service)); 16834 notifyAll(); 16835 } 16836 } 16837 16838 @Override 16839 public void onServiceDisconnected(ComponentName name) { 16840 } 16841 } 16842 16843 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16844 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16845 16846 final boolean mounted; 16847 if (Environment.isExternalStorageEmulated()) { 16848 mounted = true; 16849 } else { 16850 final String status = Environment.getExternalStorageState(); 16851 16852 mounted = status.equals(Environment.MEDIA_MOUNTED) 16853 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16854 } 16855 16856 if (!mounted) { 16857 return; 16858 } 16859 16860 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16861 int[] users; 16862 if (userId == UserHandle.USER_ALL) { 16863 users = sUserManager.getUserIds(); 16864 } else { 16865 users = new int[] { userId }; 16866 } 16867 final ClearStorageConnection conn = new ClearStorageConnection(); 16868 if (mContext.bindServiceAsUser( 16869 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16870 try { 16871 for (int curUser : users) { 16872 long timeout = SystemClock.uptimeMillis() + 5000; 16873 synchronized (conn) { 16874 long now; 16875 while (conn.mContainerService == null && 16876 (now = SystemClock.uptimeMillis()) < timeout) { 16877 try { 16878 conn.wait(timeout - now); 16879 } catch (InterruptedException e) { 16880 } 16881 } 16882 } 16883 if (conn.mContainerService == null) { 16884 return; 16885 } 16886 16887 final UserEnvironment userEnv = new UserEnvironment(curUser); 16888 clearDirectory(conn.mContainerService, 16889 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16890 if (allData) { 16891 clearDirectory(conn.mContainerService, 16892 userEnv.buildExternalStorageAppDataDirs(packageName)); 16893 clearDirectory(conn.mContainerService, 16894 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16895 } 16896 } 16897 } finally { 16898 mContext.unbindService(conn); 16899 } 16900 } 16901 } 16902 16903 @Override 16904 public void clearApplicationProfileData(String packageName) { 16905 enforceSystemOrRoot("Only the system can clear all profile data"); 16906 16907 final PackageParser.Package pkg; 16908 synchronized (mPackages) { 16909 pkg = mPackages.get(packageName); 16910 } 16911 16912 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16913 synchronized (mInstallLock) { 16914 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16915 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16916 true /* removeBaseMarker */); 16917 } 16918 } 16919 } 16920 16921 @Override 16922 public void clearApplicationUserData(final String packageName, 16923 final IPackageDataObserver observer, final int userId) { 16924 mContext.enforceCallingOrSelfPermission( 16925 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16926 16927 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16928 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16929 16930 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16931 throw new SecurityException("Cannot clear data for a protected package: " 16932 + packageName); 16933 } 16934 // Queue up an async operation since the package deletion may take a little while. 16935 mHandler.post(new Runnable() { 16936 public void run() { 16937 mHandler.removeCallbacks(this); 16938 final boolean succeeded; 16939 try (PackageFreezer freezer = freezePackage(packageName, 16940 "clearApplicationUserData")) { 16941 synchronized (mInstallLock) { 16942 succeeded = clearApplicationUserDataLIF(packageName, userId); 16943 } 16944 clearExternalStorageDataSync(packageName, userId, true); 16945 } 16946 if (succeeded) { 16947 // invoke DeviceStorageMonitor's update method to clear any notifications 16948 DeviceStorageMonitorInternal dsm = LocalServices 16949 .getService(DeviceStorageMonitorInternal.class); 16950 if (dsm != null) { 16951 dsm.checkMemory(); 16952 } 16953 } 16954 if(observer != null) { 16955 try { 16956 observer.onRemoveCompleted(packageName, succeeded); 16957 } catch (RemoteException e) { 16958 Log.i(TAG, "Observer no longer exists."); 16959 } 16960 } //end if observer 16961 } //end run 16962 }); 16963 } 16964 16965 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16966 if (packageName == null) { 16967 Slog.w(TAG, "Attempt to delete null packageName."); 16968 return false; 16969 } 16970 16971 // Try finding details about the requested package 16972 PackageParser.Package pkg; 16973 synchronized (mPackages) { 16974 pkg = mPackages.get(packageName); 16975 if (pkg == null) { 16976 final PackageSetting ps = mSettings.mPackages.get(packageName); 16977 if (ps != null) { 16978 pkg = ps.pkg; 16979 } 16980 } 16981 16982 if (pkg == null) { 16983 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16984 return false; 16985 } 16986 16987 PackageSetting ps = (PackageSetting) pkg.mExtras; 16988 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16989 } 16990 16991 clearAppDataLIF(pkg, userId, 16992 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16993 16994 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16995 removeKeystoreDataIfNeeded(userId, appId); 16996 16997 UserManagerInternal umInternal = getUserManagerInternal(); 16998 final int flags; 16999 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 17000 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 17001 } else if (umInternal.isUserRunning(userId)) { 17002 flags = StorageManager.FLAG_STORAGE_DE; 17003 } else { 17004 flags = 0; 17005 } 17006 prepareAppDataContentsLIF(pkg, userId, flags); 17007 17008 return true; 17009 } 17010 17011 /** 17012 * Reverts user permission state changes (permissions and flags) in 17013 * all packages for a given user. 17014 * 17015 * @param userId The device user for which to do a reset. 17016 */ 17017 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 17018 final int packageCount = mPackages.size(); 17019 for (int i = 0; i < packageCount; i++) { 17020 PackageParser.Package pkg = mPackages.valueAt(i); 17021 PackageSetting ps = (PackageSetting) pkg.mExtras; 17022 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 17023 } 17024 } 17025 17026 private void resetNetworkPolicies(int userId) { 17027 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 17028 } 17029 17030 /** 17031 * Reverts user permission state changes (permissions and flags). 17032 * 17033 * @param ps The package for which to reset. 17034 * @param userId The device user for which to do a reset. 17035 */ 17036 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 17037 final PackageSetting ps, final int userId) { 17038 if (ps.pkg == null) { 17039 return; 17040 } 17041 17042 // These are flags that can change base on user actions. 17043 final int userSettableMask = FLAG_PERMISSION_USER_SET 17044 | FLAG_PERMISSION_USER_FIXED 17045 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 17046 | FLAG_PERMISSION_REVIEW_REQUIRED; 17047 17048 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 17049 | FLAG_PERMISSION_POLICY_FIXED; 17050 17051 boolean writeInstallPermissions = false; 17052 boolean writeRuntimePermissions = false; 17053 17054 final int permissionCount = ps.pkg.requestedPermissions.size(); 17055 for (int i = 0; i < permissionCount; i++) { 17056 String permission = ps.pkg.requestedPermissions.get(i); 17057 17058 BasePermission bp = mSettings.mPermissions.get(permission); 17059 if (bp == null) { 17060 continue; 17061 } 17062 17063 // If shared user we just reset the state to which only this app contributed. 17064 if (ps.sharedUser != null) { 17065 boolean used = false; 17066 final int packageCount = ps.sharedUser.packages.size(); 17067 for (int j = 0; j < packageCount; j++) { 17068 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 17069 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 17070 && pkg.pkg.requestedPermissions.contains(permission)) { 17071 used = true; 17072 break; 17073 } 17074 } 17075 if (used) { 17076 continue; 17077 } 17078 } 17079 17080 PermissionsState permissionsState = ps.getPermissionsState(); 17081 17082 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 17083 17084 // Always clear the user settable flags. 17085 final boolean hasInstallState = permissionsState.getInstallPermissionState( 17086 bp.name) != null; 17087 // If permission review is enabled and this is a legacy app, mark the 17088 // permission as requiring a review as this is the initial state. 17089 int flags = 0; 17090 if (mPermissionReviewRequired 17091 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 17092 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 17093 } 17094 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 17095 if (hasInstallState) { 17096 writeInstallPermissions = true; 17097 } else { 17098 writeRuntimePermissions = true; 17099 } 17100 } 17101 17102 // Below is only runtime permission handling. 17103 if (!bp.isRuntime()) { 17104 continue; 17105 } 17106 17107 // Never clobber system or policy. 17108 if ((oldFlags & policyOrSystemFlags) != 0) { 17109 continue; 17110 } 17111 17112 // If this permission was granted by default, make sure it is. 17113 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 17114 if (permissionsState.grantRuntimePermission(bp, userId) 17115 != PERMISSION_OPERATION_FAILURE) { 17116 writeRuntimePermissions = true; 17117 } 17118 // If permission review is enabled the permissions for a legacy apps 17119 // are represented as constantly granted runtime ones, so don't revoke. 17120 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 17121 // Otherwise, reset the permission. 17122 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 17123 switch (revokeResult) { 17124 case PERMISSION_OPERATION_SUCCESS: 17125 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 17126 writeRuntimePermissions = true; 17127 final int appId = ps.appId; 17128 mHandler.post(new Runnable() { 17129 @Override 17130 public void run() { 17131 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 17132 } 17133 }); 17134 } break; 17135 } 17136 } 17137 } 17138 17139 // Synchronously write as we are taking permissions away. 17140 if (writeRuntimePermissions) { 17141 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 17142 } 17143 17144 // Synchronously write as we are taking permissions away. 17145 if (writeInstallPermissions) { 17146 mSettings.writeLPr(); 17147 } 17148 } 17149 17150 /** 17151 * Remove entries from the keystore daemon. Will only remove it if the 17152 * {@code appId} is valid. 17153 */ 17154 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 17155 if (appId < 0) { 17156 return; 17157 } 17158 17159 final KeyStore keyStore = KeyStore.getInstance(); 17160 if (keyStore != null) { 17161 if (userId == UserHandle.USER_ALL) { 17162 for (final int individual : sUserManager.getUserIds()) { 17163 keyStore.clearUid(UserHandle.getUid(individual, appId)); 17164 } 17165 } else { 17166 keyStore.clearUid(UserHandle.getUid(userId, appId)); 17167 } 17168 } else { 17169 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 17170 } 17171 } 17172 17173 @Override 17174 public void deleteApplicationCacheFiles(final String packageName, 17175 final IPackageDataObserver observer) { 17176 final int userId = UserHandle.getCallingUserId(); 17177 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 17178 } 17179 17180 @Override 17181 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 17182 final IPackageDataObserver observer) { 17183 mContext.enforceCallingOrSelfPermission( 17184 android.Manifest.permission.DELETE_CACHE_FILES, null); 17185 enforceCrossUserPermission(Binder.getCallingUid(), userId, 17186 /* requireFullPermission= */ true, /* checkShell= */ false, 17187 "delete application cache files"); 17188 17189 final PackageParser.Package pkg; 17190 synchronized (mPackages) { 17191 pkg = mPackages.get(packageName); 17192 } 17193 17194 // Queue up an async operation since the package deletion may take a little while. 17195 mHandler.post(new Runnable() { 17196 public void run() { 17197 synchronized (mInstallLock) { 17198 final int flags = StorageManager.FLAG_STORAGE_DE 17199 | StorageManager.FLAG_STORAGE_CE; 17200 // We're only clearing cache files, so we don't care if the 17201 // app is unfrozen and still able to run 17202 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 17203 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17204 } 17205 clearExternalStorageDataSync(packageName, userId, false); 17206 if (observer != null) { 17207 try { 17208 observer.onRemoveCompleted(packageName, true); 17209 } catch (RemoteException e) { 17210 Log.i(TAG, "Observer no longer exists."); 17211 } 17212 } 17213 } 17214 }); 17215 } 17216 17217 @Override 17218 public void getPackageSizeInfo(final String packageName, int userHandle, 17219 final IPackageStatsObserver observer) { 17220 mContext.enforceCallingOrSelfPermission( 17221 android.Manifest.permission.GET_PACKAGE_SIZE, null); 17222 if (packageName == null) { 17223 throw new IllegalArgumentException("Attempt to get size of null packageName"); 17224 } 17225 17226 PackageStats stats = new PackageStats(packageName, userHandle); 17227 17228 /* 17229 * Queue up an async operation since the package measurement may take a 17230 * little while. 17231 */ 17232 Message msg = mHandler.obtainMessage(INIT_COPY); 17233 msg.obj = new MeasureParams(stats, observer); 17234 mHandler.sendMessage(msg); 17235 } 17236 17237 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 17238 final PackageSetting ps; 17239 synchronized (mPackages) { 17240 ps = mSettings.mPackages.get(packageName); 17241 if (ps == null) { 17242 Slog.w(TAG, "Failed to find settings for " + packageName); 17243 return false; 17244 } 17245 } 17246 try { 17247 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 17248 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 17249 ps.getCeDataInode(userId), ps.codePathString, stats); 17250 } catch (InstallerException e) { 17251 Slog.w(TAG, String.valueOf(e)); 17252 return false; 17253 } 17254 17255 // For now, ignore code size of packages on system partition 17256 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 17257 stats.codeSize = 0; 17258 } 17259 17260 return true; 17261 } 17262 17263 private int getUidTargetSdkVersionLockedLPr(int uid) { 17264 Object obj = mSettings.getUserIdLPr(uid); 17265 if (obj instanceof SharedUserSetting) { 17266 final SharedUserSetting sus = (SharedUserSetting) obj; 17267 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 17268 final Iterator<PackageSetting> it = sus.packages.iterator(); 17269 while (it.hasNext()) { 17270 final PackageSetting ps = it.next(); 17271 if (ps.pkg != null) { 17272 int v = ps.pkg.applicationInfo.targetSdkVersion; 17273 if (v < vers) vers = v; 17274 } 17275 } 17276 return vers; 17277 } else if (obj instanceof PackageSetting) { 17278 final PackageSetting ps = (PackageSetting) obj; 17279 if (ps.pkg != null) { 17280 return ps.pkg.applicationInfo.targetSdkVersion; 17281 } 17282 } 17283 return Build.VERSION_CODES.CUR_DEVELOPMENT; 17284 } 17285 17286 @Override 17287 public void addPreferredActivity(IntentFilter filter, int match, 17288 ComponentName[] set, ComponentName activity, int userId) { 17289 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17290 "Adding preferred"); 17291 } 17292 17293 private void addPreferredActivityInternal(IntentFilter filter, int match, 17294 ComponentName[] set, ComponentName activity, boolean always, int userId, 17295 String opname) { 17296 // writer 17297 int callingUid = Binder.getCallingUid(); 17298 enforceCrossUserPermission(callingUid, userId, 17299 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 17300 if (filter.countActions() == 0) { 17301 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17302 return; 17303 } 17304 synchronized (mPackages) { 17305 if (mContext.checkCallingOrSelfPermission( 17306 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17307 != PackageManager.PERMISSION_GRANTED) { 17308 if (getUidTargetSdkVersionLockedLPr(callingUid) 17309 < Build.VERSION_CODES.FROYO) { 17310 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 17311 + callingUid); 17312 return; 17313 } 17314 mContext.enforceCallingOrSelfPermission( 17315 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17316 } 17317 17318 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 17319 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 17320 + userId + ":"); 17321 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17322 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 17323 scheduleWritePackageRestrictionsLocked(userId); 17324 postPreferredActivityChangedBroadcast(userId); 17325 } 17326 } 17327 17328 private void postPreferredActivityChangedBroadcast(int userId) { 17329 mHandler.post(() -> { 17330 final IActivityManager am = ActivityManager.getService(); 17331 if (am == null) { 17332 return; 17333 } 17334 17335 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 17336 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 17337 try { 17338 am.broadcastIntent(null, intent, null, null, 17339 0, null, null, null, android.app.AppOpsManager.OP_NONE, 17340 null, false, false, userId); 17341 } catch (RemoteException e) { 17342 } 17343 }); 17344 } 17345 17346 @Override 17347 public void replacePreferredActivity(IntentFilter filter, int match, 17348 ComponentName[] set, ComponentName activity, int userId) { 17349 if (filter.countActions() != 1) { 17350 throw new IllegalArgumentException( 17351 "replacePreferredActivity expects filter to have only 1 action."); 17352 } 17353 if (filter.countDataAuthorities() != 0 17354 || filter.countDataPaths() != 0 17355 || filter.countDataSchemes() > 1 17356 || filter.countDataTypes() != 0) { 17357 throw new IllegalArgumentException( 17358 "replacePreferredActivity expects filter to have no data authorities, " + 17359 "paths, or types; and at most one scheme."); 17360 } 17361 17362 final int callingUid = Binder.getCallingUid(); 17363 enforceCrossUserPermission(callingUid, userId, 17364 true /* requireFullPermission */, false /* checkShell */, 17365 "replace preferred activity"); 17366 synchronized (mPackages) { 17367 if (mContext.checkCallingOrSelfPermission( 17368 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17369 != PackageManager.PERMISSION_GRANTED) { 17370 if (getUidTargetSdkVersionLockedLPr(callingUid) 17371 < Build.VERSION_CODES.FROYO) { 17372 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 17373 + Binder.getCallingUid()); 17374 return; 17375 } 17376 mContext.enforceCallingOrSelfPermission( 17377 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17378 } 17379 17380 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17381 if (pir != null) { 17382 // Get all of the existing entries that exactly match this filter. 17383 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 17384 if (existing != null && existing.size() == 1) { 17385 PreferredActivity cur = existing.get(0); 17386 if (DEBUG_PREFERRED) { 17387 Slog.i(TAG, "Checking replace of preferred:"); 17388 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17389 if (!cur.mPref.mAlways) { 17390 Slog.i(TAG, " -- CUR; not mAlways!"); 17391 } else { 17392 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 17393 Slog.i(TAG, " -- CUR: mSet=" 17394 + Arrays.toString(cur.mPref.mSetComponents)); 17395 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 17396 Slog.i(TAG, " -- NEW: mMatch=" 17397 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 17398 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 17399 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 17400 } 17401 } 17402 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 17403 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 17404 && cur.mPref.sameSet(set)) { 17405 // Setting the preferred activity to what it happens to be already 17406 if (DEBUG_PREFERRED) { 17407 Slog.i(TAG, "Replacing with same preferred activity " 17408 + cur.mPref.mShortComponent + " for user " 17409 + userId + ":"); 17410 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17411 } 17412 return; 17413 } 17414 } 17415 17416 if (existing != null) { 17417 if (DEBUG_PREFERRED) { 17418 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 17419 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17420 } 17421 for (int i = 0; i < existing.size(); i++) { 17422 PreferredActivity pa = existing.get(i); 17423 if (DEBUG_PREFERRED) { 17424 Slog.i(TAG, "Removing existing preferred activity " 17425 + pa.mPref.mComponent + ":"); 17426 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 17427 } 17428 pir.removeFilter(pa); 17429 } 17430 } 17431 } 17432 addPreferredActivityInternal(filter, match, set, activity, true, userId, 17433 "Replacing preferred"); 17434 } 17435 } 17436 17437 @Override 17438 public void clearPackagePreferredActivities(String packageName) { 17439 final int uid = Binder.getCallingUid(); 17440 // writer 17441 synchronized (mPackages) { 17442 PackageParser.Package pkg = mPackages.get(packageName); 17443 if (pkg == null || pkg.applicationInfo.uid != uid) { 17444 if (mContext.checkCallingOrSelfPermission( 17445 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 17446 != PackageManager.PERMISSION_GRANTED) { 17447 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 17448 < Build.VERSION_CODES.FROYO) { 17449 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 17450 + Binder.getCallingUid()); 17451 return; 17452 } 17453 mContext.enforceCallingOrSelfPermission( 17454 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17455 } 17456 } 17457 17458 int user = UserHandle.getCallingUserId(); 17459 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 17460 scheduleWritePackageRestrictionsLocked(user); 17461 } 17462 } 17463 } 17464 17465 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17466 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 17467 ArrayList<PreferredActivity> removed = null; 17468 boolean changed = false; 17469 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17470 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 17471 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17472 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 17473 continue; 17474 } 17475 Iterator<PreferredActivity> it = pir.filterIterator(); 17476 while (it.hasNext()) { 17477 PreferredActivity pa = it.next(); 17478 // Mark entry for removal only if it matches the package name 17479 // and the entry is of type "always". 17480 if (packageName == null || 17481 (pa.mPref.mComponent.getPackageName().equals(packageName) 17482 && pa.mPref.mAlways)) { 17483 if (removed == null) { 17484 removed = new ArrayList<PreferredActivity>(); 17485 } 17486 removed.add(pa); 17487 } 17488 } 17489 if (removed != null) { 17490 for (int j=0; j<removed.size(); j++) { 17491 PreferredActivity pa = removed.get(j); 17492 pir.removeFilter(pa); 17493 } 17494 changed = true; 17495 } 17496 } 17497 if (changed) { 17498 postPreferredActivityChangedBroadcast(userId); 17499 } 17500 return changed; 17501 } 17502 17503 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17504 private void clearIntentFilterVerificationsLPw(int userId) { 17505 final int packageCount = mPackages.size(); 17506 for (int i = 0; i < packageCount; i++) { 17507 PackageParser.Package pkg = mPackages.valueAt(i); 17508 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17509 } 17510 } 17511 17512 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17513 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17514 if (userId == UserHandle.USER_ALL) { 17515 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17516 sUserManager.getUserIds())) { 17517 for (int oneUserId : sUserManager.getUserIds()) { 17518 scheduleWritePackageRestrictionsLocked(oneUserId); 17519 } 17520 } 17521 } else { 17522 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17523 scheduleWritePackageRestrictionsLocked(userId); 17524 } 17525 } 17526 } 17527 17528 void clearDefaultBrowserIfNeeded(String packageName) { 17529 for (int oneUserId : sUserManager.getUserIds()) { 17530 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17531 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17532 if (packageName.equals(defaultBrowserPackageName)) { 17533 setDefaultBrowserPackageName(null, oneUserId); 17534 } 17535 } 17536 } 17537 17538 @Override 17539 public void resetApplicationPreferences(int userId) { 17540 mContext.enforceCallingOrSelfPermission( 17541 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17542 final long identity = Binder.clearCallingIdentity(); 17543 // writer 17544 try { 17545 synchronized (mPackages) { 17546 clearPackagePreferredActivitiesLPw(null, userId); 17547 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17548 // TODO: We have to reset the default SMS and Phone. This requires 17549 // significant refactoring to keep all default apps in the package 17550 // manager (cleaner but more work) or have the services provide 17551 // callbacks to the package manager to request a default app reset. 17552 applyFactoryDefaultBrowserLPw(userId); 17553 clearIntentFilterVerificationsLPw(userId); 17554 primeDomainVerificationsLPw(userId); 17555 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17556 scheduleWritePackageRestrictionsLocked(userId); 17557 } 17558 resetNetworkPolicies(userId); 17559 } finally { 17560 Binder.restoreCallingIdentity(identity); 17561 } 17562 } 17563 17564 @Override 17565 public int getPreferredActivities(List<IntentFilter> outFilters, 17566 List<ComponentName> outActivities, String packageName) { 17567 17568 int num = 0; 17569 final int userId = UserHandle.getCallingUserId(); 17570 // reader 17571 synchronized (mPackages) { 17572 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17573 if (pir != null) { 17574 final Iterator<PreferredActivity> it = pir.filterIterator(); 17575 while (it.hasNext()) { 17576 final PreferredActivity pa = it.next(); 17577 if (packageName == null 17578 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17579 && pa.mPref.mAlways)) { 17580 if (outFilters != null) { 17581 outFilters.add(new IntentFilter(pa)); 17582 } 17583 if (outActivities != null) { 17584 outActivities.add(pa.mPref.mComponent); 17585 } 17586 } 17587 } 17588 } 17589 } 17590 17591 return num; 17592 } 17593 17594 @Override 17595 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17596 int userId) { 17597 int callingUid = Binder.getCallingUid(); 17598 if (callingUid != Process.SYSTEM_UID) { 17599 throw new SecurityException( 17600 "addPersistentPreferredActivity can only be run by the system"); 17601 } 17602 if (filter.countActions() == 0) { 17603 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17604 return; 17605 } 17606 synchronized (mPackages) { 17607 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17608 ":"); 17609 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17610 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17611 new PersistentPreferredActivity(filter, activity)); 17612 scheduleWritePackageRestrictionsLocked(userId); 17613 postPreferredActivityChangedBroadcast(userId); 17614 } 17615 } 17616 17617 @Override 17618 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17619 int callingUid = Binder.getCallingUid(); 17620 if (callingUid != Process.SYSTEM_UID) { 17621 throw new SecurityException( 17622 "clearPackagePersistentPreferredActivities can only be run by the system"); 17623 } 17624 ArrayList<PersistentPreferredActivity> removed = null; 17625 boolean changed = false; 17626 synchronized (mPackages) { 17627 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17628 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17629 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17630 .valueAt(i); 17631 if (userId != thisUserId) { 17632 continue; 17633 } 17634 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17635 while (it.hasNext()) { 17636 PersistentPreferredActivity ppa = it.next(); 17637 // Mark entry for removal only if it matches the package name. 17638 if (ppa.mComponent.getPackageName().equals(packageName)) { 17639 if (removed == null) { 17640 removed = new ArrayList<PersistentPreferredActivity>(); 17641 } 17642 removed.add(ppa); 17643 } 17644 } 17645 if (removed != null) { 17646 for (int j=0; j<removed.size(); j++) { 17647 PersistentPreferredActivity ppa = removed.get(j); 17648 ppir.removeFilter(ppa); 17649 } 17650 changed = true; 17651 } 17652 } 17653 17654 if (changed) { 17655 scheduleWritePackageRestrictionsLocked(userId); 17656 postPreferredActivityChangedBroadcast(userId); 17657 } 17658 } 17659 } 17660 17661 /** 17662 * Common machinery for picking apart a restored XML blob and passing 17663 * it to a caller-supplied functor to be applied to the running system. 17664 */ 17665 private void restoreFromXml(XmlPullParser parser, int userId, 17666 String expectedStartTag, BlobXmlRestorer functor) 17667 throws IOException, XmlPullParserException { 17668 int type; 17669 while ((type = parser.next()) != XmlPullParser.START_TAG 17670 && type != XmlPullParser.END_DOCUMENT) { 17671 } 17672 if (type != XmlPullParser.START_TAG) { 17673 // oops didn't find a start tag?! 17674 if (DEBUG_BACKUP) { 17675 Slog.e(TAG, "Didn't find start tag during restore"); 17676 } 17677 return; 17678 } 17679Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17680 // this is supposed to be TAG_PREFERRED_BACKUP 17681 if (!expectedStartTag.equals(parser.getName())) { 17682 if (DEBUG_BACKUP) { 17683 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17684 } 17685 return; 17686 } 17687 17688 // skip interfering stuff, then we're aligned with the backing implementation 17689 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17690Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17691 functor.apply(parser, userId); 17692 } 17693 17694 private interface BlobXmlRestorer { 17695 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17696 } 17697 17698 /** 17699 * Non-Binder method, support for the backup/restore mechanism: write the 17700 * full set of preferred activities in its canonical XML format. Returns the 17701 * XML output as a byte array, or null if there is none. 17702 */ 17703 @Override 17704 public byte[] getPreferredActivityBackup(int userId) { 17705 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17706 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17707 } 17708 17709 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17710 try { 17711 final XmlSerializer serializer = new FastXmlSerializer(); 17712 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17713 serializer.startDocument(null, true); 17714 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17715 17716 synchronized (mPackages) { 17717 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17718 } 17719 17720 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17721 serializer.endDocument(); 17722 serializer.flush(); 17723 } catch (Exception e) { 17724 if (DEBUG_BACKUP) { 17725 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17726 } 17727 return null; 17728 } 17729 17730 return dataStream.toByteArray(); 17731 } 17732 17733 @Override 17734 public void restorePreferredActivities(byte[] backup, int userId) { 17735 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17736 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17737 } 17738 17739 try { 17740 final XmlPullParser parser = Xml.newPullParser(); 17741 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17742 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17743 new BlobXmlRestorer() { 17744 @Override 17745 public void apply(XmlPullParser parser, int userId) 17746 throws XmlPullParserException, IOException { 17747 synchronized (mPackages) { 17748 mSettings.readPreferredActivitiesLPw(parser, userId); 17749 } 17750 } 17751 } ); 17752 } catch (Exception e) { 17753 if (DEBUG_BACKUP) { 17754 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17755 } 17756 } 17757 } 17758 17759 /** 17760 * Non-Binder method, support for the backup/restore mechanism: write the 17761 * default browser (etc) settings in its canonical XML format. Returns the default 17762 * browser XML representation as a byte array, or null if there is none. 17763 */ 17764 @Override 17765 public byte[] getDefaultAppsBackup(int userId) { 17766 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17767 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17768 } 17769 17770 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17771 try { 17772 final XmlSerializer serializer = new FastXmlSerializer(); 17773 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17774 serializer.startDocument(null, true); 17775 serializer.startTag(null, TAG_DEFAULT_APPS); 17776 17777 synchronized (mPackages) { 17778 mSettings.writeDefaultAppsLPr(serializer, userId); 17779 } 17780 17781 serializer.endTag(null, TAG_DEFAULT_APPS); 17782 serializer.endDocument(); 17783 serializer.flush(); 17784 } catch (Exception e) { 17785 if (DEBUG_BACKUP) { 17786 Slog.e(TAG, "Unable to write default apps for backup", e); 17787 } 17788 return null; 17789 } 17790 17791 return dataStream.toByteArray(); 17792 } 17793 17794 @Override 17795 public void restoreDefaultApps(byte[] backup, int userId) { 17796 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17797 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17798 } 17799 17800 try { 17801 final XmlPullParser parser = Xml.newPullParser(); 17802 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17803 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17804 new BlobXmlRestorer() { 17805 @Override 17806 public void apply(XmlPullParser parser, int userId) 17807 throws XmlPullParserException, IOException { 17808 synchronized (mPackages) { 17809 mSettings.readDefaultAppsLPw(parser, userId); 17810 } 17811 } 17812 } ); 17813 } catch (Exception e) { 17814 if (DEBUG_BACKUP) { 17815 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17816 } 17817 } 17818 } 17819 17820 @Override 17821 public byte[] getIntentFilterVerificationBackup(int userId) { 17822 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17823 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17824 } 17825 17826 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17827 try { 17828 final XmlSerializer serializer = new FastXmlSerializer(); 17829 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17830 serializer.startDocument(null, true); 17831 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17832 17833 synchronized (mPackages) { 17834 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17835 } 17836 17837 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17838 serializer.endDocument(); 17839 serializer.flush(); 17840 } catch (Exception e) { 17841 if (DEBUG_BACKUP) { 17842 Slog.e(TAG, "Unable to write default apps for backup", e); 17843 } 17844 return null; 17845 } 17846 17847 return dataStream.toByteArray(); 17848 } 17849 17850 @Override 17851 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17852 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17853 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17854 } 17855 17856 try { 17857 final XmlPullParser parser = Xml.newPullParser(); 17858 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17859 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17860 new BlobXmlRestorer() { 17861 @Override 17862 public void apply(XmlPullParser parser, int userId) 17863 throws XmlPullParserException, IOException { 17864 synchronized (mPackages) { 17865 mSettings.readAllDomainVerificationsLPr(parser, userId); 17866 mSettings.writeLPr(); 17867 } 17868 } 17869 } ); 17870 } catch (Exception e) { 17871 if (DEBUG_BACKUP) { 17872 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17873 } 17874 } 17875 } 17876 17877 @Override 17878 public byte[] getPermissionGrantBackup(int userId) { 17879 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17880 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17881 } 17882 17883 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17884 try { 17885 final XmlSerializer serializer = new FastXmlSerializer(); 17886 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17887 serializer.startDocument(null, true); 17888 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17889 17890 synchronized (mPackages) { 17891 serializeRuntimePermissionGrantsLPr(serializer, userId); 17892 } 17893 17894 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17895 serializer.endDocument(); 17896 serializer.flush(); 17897 } catch (Exception e) { 17898 if (DEBUG_BACKUP) { 17899 Slog.e(TAG, "Unable to write default apps for backup", e); 17900 } 17901 return null; 17902 } 17903 17904 return dataStream.toByteArray(); 17905 } 17906 17907 @Override 17908 public void restorePermissionGrants(byte[] backup, int userId) { 17909 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17910 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17911 } 17912 17913 try { 17914 final XmlPullParser parser = Xml.newPullParser(); 17915 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17916 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17917 new BlobXmlRestorer() { 17918 @Override 17919 public void apply(XmlPullParser parser, int userId) 17920 throws XmlPullParserException, IOException { 17921 synchronized (mPackages) { 17922 processRestoredPermissionGrantsLPr(parser, userId); 17923 } 17924 } 17925 } ); 17926 } catch (Exception e) { 17927 if (DEBUG_BACKUP) { 17928 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17929 } 17930 } 17931 } 17932 17933 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17934 throws IOException { 17935 serializer.startTag(null, TAG_ALL_GRANTS); 17936 17937 final int N = mSettings.mPackages.size(); 17938 for (int i = 0; i < N; i++) { 17939 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17940 boolean pkgGrantsKnown = false; 17941 17942 PermissionsState packagePerms = ps.getPermissionsState(); 17943 17944 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17945 final int grantFlags = state.getFlags(); 17946 // only look at grants that are not system/policy fixed 17947 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17948 final boolean isGranted = state.isGranted(); 17949 // And only back up the user-twiddled state bits 17950 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17951 final String packageName = mSettings.mPackages.keyAt(i); 17952 if (!pkgGrantsKnown) { 17953 serializer.startTag(null, TAG_GRANT); 17954 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17955 pkgGrantsKnown = true; 17956 } 17957 17958 final boolean userSet = 17959 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17960 final boolean userFixed = 17961 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17962 final boolean revoke = 17963 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17964 17965 serializer.startTag(null, TAG_PERMISSION); 17966 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17967 if (isGranted) { 17968 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17969 } 17970 if (userSet) { 17971 serializer.attribute(null, ATTR_USER_SET, "true"); 17972 } 17973 if (userFixed) { 17974 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17975 } 17976 if (revoke) { 17977 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17978 } 17979 serializer.endTag(null, TAG_PERMISSION); 17980 } 17981 } 17982 } 17983 17984 if (pkgGrantsKnown) { 17985 serializer.endTag(null, TAG_GRANT); 17986 } 17987 } 17988 17989 serializer.endTag(null, TAG_ALL_GRANTS); 17990 } 17991 17992 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17993 throws XmlPullParserException, IOException { 17994 String pkgName = null; 17995 int outerDepth = parser.getDepth(); 17996 int type; 17997 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17998 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17999 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 18000 continue; 18001 } 18002 18003 final String tagName = parser.getName(); 18004 if (tagName.equals(TAG_GRANT)) { 18005 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 18006 if (DEBUG_BACKUP) { 18007 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 18008 } 18009 } else if (tagName.equals(TAG_PERMISSION)) { 18010 18011 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 18012 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 18013 18014 int newFlagSet = 0; 18015 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 18016 newFlagSet |= FLAG_PERMISSION_USER_SET; 18017 } 18018 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 18019 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 18020 } 18021 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 18022 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 18023 } 18024 if (DEBUG_BACKUP) { 18025 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 18026 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 18027 } 18028 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18029 if (ps != null) { 18030 // Already installed so we apply the grant immediately 18031 if (DEBUG_BACKUP) { 18032 Slog.v(TAG, " + already installed; applying"); 18033 } 18034 PermissionsState perms = ps.getPermissionsState(); 18035 BasePermission bp = mSettings.mPermissions.get(permName); 18036 if (bp != null) { 18037 if (isGranted) { 18038 perms.grantRuntimePermission(bp, userId); 18039 } 18040 if (newFlagSet != 0) { 18041 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 18042 } 18043 } 18044 } else { 18045 // Need to wait for post-restore install to apply the grant 18046 if (DEBUG_BACKUP) { 18047 Slog.v(TAG, " - not yet installed; saving for later"); 18048 } 18049 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 18050 isGranted, newFlagSet, userId); 18051 } 18052 } else { 18053 PackageManagerService.reportSettingsProblem(Log.WARN, 18054 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 18055 XmlUtils.skipCurrentTag(parser); 18056 } 18057 } 18058 18059 scheduleWriteSettingsLocked(); 18060 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18061 } 18062 18063 @Override 18064 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 18065 int sourceUserId, int targetUserId, int flags) { 18066 mContext.enforceCallingOrSelfPermission( 18067 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18068 int callingUid = Binder.getCallingUid(); 18069 enforceOwnerRights(ownerPackage, callingUid); 18070 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18071 if (intentFilter.countActions() == 0) { 18072 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 18073 return; 18074 } 18075 synchronized (mPackages) { 18076 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 18077 ownerPackage, targetUserId, flags); 18078 CrossProfileIntentResolver resolver = 18079 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18080 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 18081 // We have all those whose filter is equal. Now checking if the rest is equal as well. 18082 if (existing != null) { 18083 int size = existing.size(); 18084 for (int i = 0; i < size; i++) { 18085 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 18086 return; 18087 } 18088 } 18089 } 18090 resolver.addFilter(newFilter); 18091 scheduleWritePackageRestrictionsLocked(sourceUserId); 18092 } 18093 } 18094 18095 @Override 18096 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 18097 mContext.enforceCallingOrSelfPermission( 18098 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 18099 int callingUid = Binder.getCallingUid(); 18100 enforceOwnerRights(ownerPackage, callingUid); 18101 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 18102 synchronized (mPackages) { 18103 CrossProfileIntentResolver resolver = 18104 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 18105 ArraySet<CrossProfileIntentFilter> set = 18106 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 18107 for (CrossProfileIntentFilter filter : set) { 18108 if (filter.getOwnerPackage().equals(ownerPackage)) { 18109 resolver.removeFilter(filter); 18110 } 18111 } 18112 scheduleWritePackageRestrictionsLocked(sourceUserId); 18113 } 18114 } 18115 18116 // Enforcing that callingUid is owning pkg on userId 18117 private void enforceOwnerRights(String pkg, int callingUid) { 18118 // The system owns everything. 18119 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18120 return; 18121 } 18122 int callingUserId = UserHandle.getUserId(callingUid); 18123 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 18124 if (pi == null) { 18125 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 18126 + callingUserId); 18127 } 18128 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 18129 throw new SecurityException("Calling uid " + callingUid 18130 + " does not own package " + pkg); 18131 } 18132 } 18133 18134 @Override 18135 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 18136 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 18137 } 18138 18139 private Intent getHomeIntent() { 18140 Intent intent = new Intent(Intent.ACTION_MAIN); 18141 intent.addCategory(Intent.CATEGORY_HOME); 18142 intent.addCategory(Intent.CATEGORY_DEFAULT); 18143 return intent; 18144 } 18145 18146 private IntentFilter getHomeFilter() { 18147 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 18148 filter.addCategory(Intent.CATEGORY_HOME); 18149 filter.addCategory(Intent.CATEGORY_DEFAULT); 18150 return filter; 18151 } 18152 18153 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 18154 int userId) { 18155 Intent intent = getHomeIntent(); 18156 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 18157 PackageManager.GET_META_DATA, userId); 18158 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 18159 true, false, false, userId); 18160 18161 allHomeCandidates.clear(); 18162 if (list != null) { 18163 for (ResolveInfo ri : list) { 18164 allHomeCandidates.add(ri); 18165 } 18166 } 18167 return (preferred == null || preferred.activityInfo == null) 18168 ? null 18169 : new ComponentName(preferred.activityInfo.packageName, 18170 preferred.activityInfo.name); 18171 } 18172 18173 @Override 18174 public void setHomeActivity(ComponentName comp, int userId) { 18175 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 18176 getHomeActivitiesAsUser(homeActivities, userId); 18177 18178 boolean found = false; 18179 18180 final int size = homeActivities.size(); 18181 final ComponentName[] set = new ComponentName[size]; 18182 for (int i = 0; i < size; i++) { 18183 final ResolveInfo candidate = homeActivities.get(i); 18184 final ActivityInfo info = candidate.activityInfo; 18185 final ComponentName activityName = new ComponentName(info.packageName, info.name); 18186 set[i] = activityName; 18187 if (!found && activityName.equals(comp)) { 18188 found = true; 18189 } 18190 } 18191 if (!found) { 18192 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 18193 + userId); 18194 } 18195 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 18196 set, comp, userId); 18197 } 18198 18199 private @Nullable String getSetupWizardPackageName() { 18200 final Intent intent = new Intent(Intent.ACTION_MAIN); 18201 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 18202 18203 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18204 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18205 | MATCH_DISABLED_COMPONENTS, 18206 UserHandle.myUserId()); 18207 if (matches.size() == 1) { 18208 return matches.get(0).getComponentInfo().packageName; 18209 } else { 18210 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 18211 + ": matches=" + matches); 18212 return null; 18213 } 18214 } 18215 18216 private @Nullable String getStorageManagerPackageName() { 18217 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 18218 18219 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 18220 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 18221 | MATCH_DISABLED_COMPONENTS, 18222 UserHandle.myUserId()); 18223 if (matches.size() == 1) { 18224 return matches.get(0).getComponentInfo().packageName; 18225 } else { 18226 Slog.e(TAG, "There should probably be exactly one storage manager; found " 18227 + matches.size() + ": matches=" + matches); 18228 return null; 18229 } 18230 } 18231 18232 @Override 18233 public void setApplicationEnabledSetting(String appPackageName, 18234 int newState, int flags, int userId, String callingPackage) { 18235 if (!sUserManager.exists(userId)) return; 18236 if (callingPackage == null) { 18237 callingPackage = Integer.toString(Binder.getCallingUid()); 18238 } 18239 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 18240 } 18241 18242 @Override 18243 public void setComponentEnabledSetting(ComponentName componentName, 18244 int newState, int flags, int userId) { 18245 if (!sUserManager.exists(userId)) return; 18246 setEnabledSetting(componentName.getPackageName(), 18247 componentName.getClassName(), newState, flags, userId, null); 18248 } 18249 18250 private void setEnabledSetting(final String packageName, String className, int newState, 18251 final int flags, int userId, String callingPackage) { 18252 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 18253 || newState == COMPONENT_ENABLED_STATE_ENABLED 18254 || newState == COMPONENT_ENABLED_STATE_DISABLED 18255 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18256 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 18257 throw new IllegalArgumentException("Invalid new component state: " 18258 + newState); 18259 } 18260 PackageSetting pkgSetting; 18261 final int uid = Binder.getCallingUid(); 18262 final int permission; 18263 if (uid == Process.SYSTEM_UID) { 18264 permission = PackageManager.PERMISSION_GRANTED; 18265 } else { 18266 permission = mContext.checkCallingOrSelfPermission( 18267 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18268 } 18269 enforceCrossUserPermission(uid, userId, 18270 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 18271 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18272 boolean sendNow = false; 18273 boolean isApp = (className == null); 18274 String componentName = isApp ? packageName : className; 18275 int packageUid = -1; 18276 ArrayList<String> components; 18277 18278 // writer 18279 synchronized (mPackages) { 18280 pkgSetting = mSettings.mPackages.get(packageName); 18281 if (pkgSetting == null) { 18282 if (className == null) { 18283 throw new IllegalArgumentException("Unknown package: " + packageName); 18284 } 18285 throw new IllegalArgumentException( 18286 "Unknown component: " + packageName + "/" + className); 18287 } 18288 } 18289 18290 // Limit who can change which apps 18291 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 18292 // Don't allow apps that don't have permission to modify other apps 18293 if (!allowedByPermission) { 18294 throw new SecurityException( 18295 "Permission Denial: attempt to change component state from pid=" 18296 + Binder.getCallingPid() 18297 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 18298 } 18299 // Don't allow changing protected packages. 18300 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 18301 throw new SecurityException("Cannot disable a protected package: " + packageName); 18302 } 18303 } 18304 18305 synchronized (mPackages) { 18306 if (uid == Process.SHELL_UID 18307 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 18308 // Shell can only change whole packages between ENABLED and DISABLED_USER states 18309 // unless it is a test package. 18310 int oldState = pkgSetting.getEnabled(userId); 18311 if (className == null 18312 && 18313 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 18314 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 18315 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 18316 && 18317 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 18318 || newState == COMPONENT_ENABLED_STATE_DEFAULT 18319 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 18320 // ok 18321 } else { 18322 throw new SecurityException( 18323 "Shell cannot change component state for " + packageName + "/" 18324 + className + " to " + newState); 18325 } 18326 } 18327 if (className == null) { 18328 // We're dealing with an application/package level state change 18329 if (pkgSetting.getEnabled(userId) == newState) { 18330 // Nothing to do 18331 return; 18332 } 18333 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 18334 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 18335 // Don't care about who enables an app. 18336 callingPackage = null; 18337 } 18338 pkgSetting.setEnabled(newState, userId, callingPackage); 18339 // pkgSetting.pkg.mSetEnabled = newState; 18340 } else { 18341 // We're dealing with a component level state change 18342 // First, verify that this is a valid class name. 18343 PackageParser.Package pkg = pkgSetting.pkg; 18344 if (pkg == null || !pkg.hasComponentClassName(className)) { 18345 if (pkg != null && 18346 pkg.applicationInfo.targetSdkVersion >= 18347 Build.VERSION_CODES.JELLY_BEAN) { 18348 throw new IllegalArgumentException("Component class " + className 18349 + " does not exist in " + packageName); 18350 } else { 18351 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 18352 + className + " does not exist in " + packageName); 18353 } 18354 } 18355 switch (newState) { 18356 case COMPONENT_ENABLED_STATE_ENABLED: 18357 if (!pkgSetting.enableComponentLPw(className, userId)) { 18358 return; 18359 } 18360 break; 18361 case COMPONENT_ENABLED_STATE_DISABLED: 18362 if (!pkgSetting.disableComponentLPw(className, userId)) { 18363 return; 18364 } 18365 break; 18366 case COMPONENT_ENABLED_STATE_DEFAULT: 18367 if (!pkgSetting.restoreComponentLPw(className, userId)) { 18368 return; 18369 } 18370 break; 18371 default: 18372 Slog.e(TAG, "Invalid new component state: " + newState); 18373 return; 18374 } 18375 } 18376 scheduleWritePackageRestrictionsLocked(userId); 18377 components = mPendingBroadcasts.get(userId, packageName); 18378 final boolean newPackage = components == null; 18379 if (newPackage) { 18380 components = new ArrayList<String>(); 18381 } 18382 if (!components.contains(componentName)) { 18383 components.add(componentName); 18384 } 18385 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 18386 sendNow = true; 18387 // Purge entry from pending broadcast list if another one exists already 18388 // since we are sending one right away. 18389 mPendingBroadcasts.remove(userId, packageName); 18390 } else { 18391 if (newPackage) { 18392 mPendingBroadcasts.put(userId, packageName, components); 18393 } 18394 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 18395 // Schedule a message 18396 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 18397 } 18398 } 18399 } 18400 18401 long callingId = Binder.clearCallingIdentity(); 18402 try { 18403 if (sendNow) { 18404 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 18405 sendPackageChangedBroadcast(packageName, 18406 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 18407 } 18408 } finally { 18409 Binder.restoreCallingIdentity(callingId); 18410 } 18411 } 18412 18413 @Override 18414 public void flushPackageRestrictionsAsUser(int userId) { 18415 if (!sUserManager.exists(userId)) { 18416 return; 18417 } 18418 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 18419 false /* checkShell */, "flushPackageRestrictions"); 18420 synchronized (mPackages) { 18421 mSettings.writePackageRestrictionsLPr(userId); 18422 mDirtyUsers.remove(userId); 18423 if (mDirtyUsers.isEmpty()) { 18424 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 18425 } 18426 } 18427 } 18428 18429 private void sendPackageChangedBroadcast(String packageName, 18430 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 18431 if (DEBUG_INSTALL) 18432 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 18433 + componentNames); 18434 Bundle extras = new Bundle(4); 18435 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 18436 String nameList[] = new String[componentNames.size()]; 18437 componentNames.toArray(nameList); 18438 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 18439 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 18440 extras.putInt(Intent.EXTRA_UID, packageUid); 18441 // If this is not reporting a change of the overall package, then only send it 18442 // to registered receivers. We don't want to launch a swath of apps for every 18443 // little component state change. 18444 final int flags = !componentNames.contains(packageName) 18445 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 18446 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 18447 new int[] {UserHandle.getUserId(packageUid)}); 18448 } 18449 18450 @Override 18451 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 18452 if (!sUserManager.exists(userId)) return; 18453 final int uid = Binder.getCallingUid(); 18454 final int permission = mContext.checkCallingOrSelfPermission( 18455 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 18456 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 18457 enforceCrossUserPermission(uid, userId, 18458 true /* requireFullPermission */, true /* checkShell */, "stop package"); 18459 // writer 18460 synchronized (mPackages) { 18461 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 18462 allowedByPermission, uid, userId)) { 18463 scheduleWritePackageRestrictionsLocked(userId); 18464 } 18465 } 18466 } 18467 18468 @Override 18469 public String getInstallerPackageName(String packageName) { 18470 // reader 18471 synchronized (mPackages) { 18472 return mSettings.getInstallerPackageNameLPr(packageName); 18473 } 18474 } 18475 18476 public boolean isOrphaned(String packageName) { 18477 // reader 18478 synchronized (mPackages) { 18479 return mSettings.isOrphaned(packageName); 18480 } 18481 } 18482 18483 @Override 18484 public int getApplicationEnabledSetting(String packageName, int userId) { 18485 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18486 int uid = Binder.getCallingUid(); 18487 enforceCrossUserPermission(uid, userId, 18488 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 18489 // reader 18490 synchronized (mPackages) { 18491 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 18492 } 18493 } 18494 18495 @Override 18496 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 18497 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 18498 int uid = Binder.getCallingUid(); 18499 enforceCrossUserPermission(uid, userId, 18500 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18501 // reader 18502 synchronized (mPackages) { 18503 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18504 } 18505 } 18506 18507 @Override 18508 public void enterSafeMode() { 18509 enforceSystemOrRoot("Only the system can request entering safe mode"); 18510 18511 if (!mSystemReady) { 18512 mSafeMode = true; 18513 } 18514 } 18515 18516 @Override 18517 public void systemReady() { 18518 mSystemReady = true; 18519 18520 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 18521 // disabled after already being started. 18522 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 18523 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 18524 18525 // Read the compatibilty setting when the system is ready. 18526 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18527 mContext.getContentResolver(), 18528 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18529 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18530 if (DEBUG_SETTINGS) { 18531 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18532 } 18533 18534 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18535 18536 synchronized (mPackages) { 18537 // Verify that all of the preferred activity components actually 18538 // exist. It is possible for applications to be updated and at 18539 // that point remove a previously declared activity component that 18540 // had been set as a preferred activity. We try to clean this up 18541 // the next time we encounter that preferred activity, but it is 18542 // possible for the user flow to never be able to return to that 18543 // situation so here we do a sanity check to make sure we haven't 18544 // left any junk around. 18545 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18546 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18547 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18548 removed.clear(); 18549 for (PreferredActivity pa : pir.filterSet()) { 18550 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18551 removed.add(pa); 18552 } 18553 } 18554 if (removed.size() > 0) { 18555 for (int r=0; r<removed.size(); r++) { 18556 PreferredActivity pa = removed.get(r); 18557 Slog.w(TAG, "Removing dangling preferred activity: " 18558 + pa.mPref.mComponent); 18559 pir.removeFilter(pa); 18560 } 18561 mSettings.writePackageRestrictionsLPr( 18562 mSettings.mPreferredActivities.keyAt(i)); 18563 } 18564 } 18565 18566 for (int userId : UserManagerService.getInstance().getUserIds()) { 18567 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18568 grantPermissionsUserIds = ArrayUtils.appendInt( 18569 grantPermissionsUserIds, userId); 18570 } 18571 } 18572 } 18573 sUserManager.systemReady(); 18574 18575 // If we upgraded grant all default permissions before kicking off. 18576 for (int userId : grantPermissionsUserIds) { 18577 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18578 } 18579 18580 // If we did not grant default permissions, we preload from this the 18581 // default permission exceptions lazily to ensure we don't hit the 18582 // disk on a new user creation. 18583 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 18584 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 18585 } 18586 18587 // Kick off any messages waiting for system ready 18588 if (mPostSystemReadyMessages != null) { 18589 for (Message msg : mPostSystemReadyMessages) { 18590 msg.sendToTarget(); 18591 } 18592 mPostSystemReadyMessages = null; 18593 } 18594 18595 // Watch for external volumes that come and go over time 18596 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18597 storage.registerListener(mStorageListener); 18598 18599 mInstallerService.systemReady(); 18600 mPackageDexOptimizer.systemReady(); 18601 18602 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 18603 StorageManagerInternal.class); 18604 StorageManagerInternal.addExternalStoragePolicy( 18605 new StorageManagerInternal.ExternalStorageMountPolicy() { 18606 @Override 18607 public int getMountMode(int uid, String packageName) { 18608 if (Process.isIsolated(uid)) { 18609 return Zygote.MOUNT_EXTERNAL_NONE; 18610 } 18611 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18612 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18613 } 18614 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18615 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18616 } 18617 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18618 return Zygote.MOUNT_EXTERNAL_READ; 18619 } 18620 return Zygote.MOUNT_EXTERNAL_WRITE; 18621 } 18622 18623 @Override 18624 public boolean hasExternalStorage(int uid, String packageName) { 18625 return true; 18626 } 18627 }); 18628 18629 // Now that we're mostly running, clean up stale users and apps 18630 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18631 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18632 } 18633 18634 @Override 18635 public boolean isSafeMode() { 18636 return mSafeMode; 18637 } 18638 18639 @Override 18640 public boolean hasSystemUidErrors() { 18641 return mHasSystemUidErrors; 18642 } 18643 18644 static String arrayToString(int[] array) { 18645 StringBuffer buf = new StringBuffer(128); 18646 buf.append('['); 18647 if (array != null) { 18648 for (int i=0; i<array.length; i++) { 18649 if (i > 0) buf.append(", "); 18650 buf.append(array[i]); 18651 } 18652 } 18653 buf.append(']'); 18654 return buf.toString(); 18655 } 18656 18657 static class DumpState { 18658 public static final int DUMP_LIBS = 1 << 0; 18659 public static final int DUMP_FEATURES = 1 << 1; 18660 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18661 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18662 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18663 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18664 public static final int DUMP_PERMISSIONS = 1 << 6; 18665 public static final int DUMP_PACKAGES = 1 << 7; 18666 public static final int DUMP_SHARED_USERS = 1 << 8; 18667 public static final int DUMP_MESSAGES = 1 << 9; 18668 public static final int DUMP_PROVIDERS = 1 << 10; 18669 public static final int DUMP_VERIFIERS = 1 << 11; 18670 public static final int DUMP_PREFERRED = 1 << 12; 18671 public static final int DUMP_PREFERRED_XML = 1 << 13; 18672 public static final int DUMP_KEYSETS = 1 << 14; 18673 public static final int DUMP_VERSION = 1 << 15; 18674 public static final int DUMP_INSTALLS = 1 << 16; 18675 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18676 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18677 public static final int DUMP_FROZEN = 1 << 19; 18678 public static final int DUMP_DEXOPT = 1 << 20; 18679 public static final int DUMP_COMPILER_STATS = 1 << 21; 18680 18681 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18682 18683 private int mTypes; 18684 18685 private int mOptions; 18686 18687 private boolean mTitlePrinted; 18688 18689 private SharedUserSetting mSharedUser; 18690 18691 public boolean isDumping(int type) { 18692 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18693 return true; 18694 } 18695 18696 return (mTypes & type) != 0; 18697 } 18698 18699 public void setDump(int type) { 18700 mTypes |= type; 18701 } 18702 18703 public boolean isOptionEnabled(int option) { 18704 return (mOptions & option) != 0; 18705 } 18706 18707 public void setOptionEnabled(int option) { 18708 mOptions |= option; 18709 } 18710 18711 public boolean onTitlePrinted() { 18712 final boolean printed = mTitlePrinted; 18713 mTitlePrinted = true; 18714 return printed; 18715 } 18716 18717 public boolean getTitlePrinted() { 18718 return mTitlePrinted; 18719 } 18720 18721 public void setTitlePrinted(boolean enabled) { 18722 mTitlePrinted = enabled; 18723 } 18724 18725 public SharedUserSetting getSharedUser() { 18726 return mSharedUser; 18727 } 18728 18729 public void setSharedUser(SharedUserSetting user) { 18730 mSharedUser = user; 18731 } 18732 } 18733 18734 @Override 18735 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18736 FileDescriptor err, String[] args, ShellCallback callback, 18737 ResultReceiver resultReceiver) { 18738 (new PackageManagerShellCommand(this)).exec( 18739 this, in, out, err, args, callback, resultReceiver); 18740 } 18741 18742 @Override 18743 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18744 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18745 != PackageManager.PERMISSION_GRANTED) { 18746 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18747 + Binder.getCallingPid() 18748 + ", uid=" + Binder.getCallingUid() 18749 + " without permission " 18750 + android.Manifest.permission.DUMP); 18751 return; 18752 } 18753 18754 DumpState dumpState = new DumpState(); 18755 boolean fullPreferred = false; 18756 boolean checkin = false; 18757 18758 String packageName = null; 18759 ArraySet<String> permissionNames = null; 18760 18761 int opti = 0; 18762 while (opti < args.length) { 18763 String opt = args[opti]; 18764 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18765 break; 18766 } 18767 opti++; 18768 18769 if ("-a".equals(opt)) { 18770 // Right now we only know how to print all. 18771 } else if ("-h".equals(opt)) { 18772 pw.println("Package manager dump options:"); 18773 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18774 pw.println(" --checkin: dump for a checkin"); 18775 pw.println(" -f: print details of intent filters"); 18776 pw.println(" -h: print this help"); 18777 pw.println(" cmd may be one of:"); 18778 pw.println(" l[ibraries]: list known shared libraries"); 18779 pw.println(" f[eatures]: list device features"); 18780 pw.println(" k[eysets]: print known keysets"); 18781 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18782 pw.println(" perm[issions]: dump permissions"); 18783 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18784 pw.println(" pref[erred]: print preferred package settings"); 18785 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18786 pw.println(" prov[iders]: dump content providers"); 18787 pw.println(" p[ackages]: dump installed packages"); 18788 pw.println(" s[hared-users]: dump shared user IDs"); 18789 pw.println(" m[essages]: print collected runtime messages"); 18790 pw.println(" v[erifiers]: print package verifier info"); 18791 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18792 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18793 pw.println(" version: print database version info"); 18794 pw.println(" write: write current settings now"); 18795 pw.println(" installs: details about install sessions"); 18796 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18797 pw.println(" dexopt: dump dexopt state"); 18798 pw.println(" compiler-stats: dump compiler statistics"); 18799 pw.println(" <package.name>: info about given package"); 18800 return; 18801 } else if ("--checkin".equals(opt)) { 18802 checkin = true; 18803 } else if ("-f".equals(opt)) { 18804 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18805 } else { 18806 pw.println("Unknown argument: " + opt + "; use -h for help"); 18807 } 18808 } 18809 18810 // Is the caller requesting to dump a particular piece of data? 18811 if (opti < args.length) { 18812 String cmd = args[opti]; 18813 opti++; 18814 // Is this a package name? 18815 if ("android".equals(cmd) || cmd.contains(".")) { 18816 packageName = cmd; 18817 // When dumping a single package, we always dump all of its 18818 // filter information since the amount of data will be reasonable. 18819 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18820 } else if ("check-permission".equals(cmd)) { 18821 if (opti >= args.length) { 18822 pw.println("Error: check-permission missing permission argument"); 18823 return; 18824 } 18825 String perm = args[opti]; 18826 opti++; 18827 if (opti >= args.length) { 18828 pw.println("Error: check-permission missing package argument"); 18829 return; 18830 } 18831 String pkg = args[opti]; 18832 opti++; 18833 int user = UserHandle.getUserId(Binder.getCallingUid()); 18834 if (opti < args.length) { 18835 try { 18836 user = Integer.parseInt(args[opti]); 18837 } catch (NumberFormatException e) { 18838 pw.println("Error: check-permission user argument is not a number: " 18839 + args[opti]); 18840 return; 18841 } 18842 } 18843 pw.println(checkPermission(perm, pkg, user)); 18844 return; 18845 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18846 dumpState.setDump(DumpState.DUMP_LIBS); 18847 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18848 dumpState.setDump(DumpState.DUMP_FEATURES); 18849 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18850 if (opti >= args.length) { 18851 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18852 | DumpState.DUMP_SERVICE_RESOLVERS 18853 | DumpState.DUMP_RECEIVER_RESOLVERS 18854 | DumpState.DUMP_CONTENT_RESOLVERS); 18855 } else { 18856 while (opti < args.length) { 18857 String name = args[opti]; 18858 if ("a".equals(name) || "activity".equals(name)) { 18859 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18860 } else if ("s".equals(name) || "service".equals(name)) { 18861 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18862 } else if ("r".equals(name) || "receiver".equals(name)) { 18863 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18864 } else if ("c".equals(name) || "content".equals(name)) { 18865 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18866 } else { 18867 pw.println("Error: unknown resolver table type: " + name); 18868 return; 18869 } 18870 opti++; 18871 } 18872 } 18873 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18874 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18875 } else if ("permission".equals(cmd)) { 18876 if (opti >= args.length) { 18877 pw.println("Error: permission requires permission name"); 18878 return; 18879 } 18880 permissionNames = new ArraySet<>(); 18881 while (opti < args.length) { 18882 permissionNames.add(args[opti]); 18883 opti++; 18884 } 18885 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18886 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18887 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18888 dumpState.setDump(DumpState.DUMP_PREFERRED); 18889 } else if ("preferred-xml".equals(cmd)) { 18890 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18891 if (opti < args.length && "--full".equals(args[opti])) { 18892 fullPreferred = true; 18893 opti++; 18894 } 18895 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18896 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18897 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18898 dumpState.setDump(DumpState.DUMP_PACKAGES); 18899 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18900 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18901 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18902 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18903 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18904 dumpState.setDump(DumpState.DUMP_MESSAGES); 18905 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18906 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18907 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18908 || "intent-filter-verifiers".equals(cmd)) { 18909 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18910 } else if ("version".equals(cmd)) { 18911 dumpState.setDump(DumpState.DUMP_VERSION); 18912 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18913 dumpState.setDump(DumpState.DUMP_KEYSETS); 18914 } else if ("installs".equals(cmd)) { 18915 dumpState.setDump(DumpState.DUMP_INSTALLS); 18916 } else if ("frozen".equals(cmd)) { 18917 dumpState.setDump(DumpState.DUMP_FROZEN); 18918 } else if ("dexopt".equals(cmd)) { 18919 dumpState.setDump(DumpState.DUMP_DEXOPT); 18920 } else if ("compiler-stats".equals(cmd)) { 18921 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18922 } else if ("write".equals(cmd)) { 18923 synchronized (mPackages) { 18924 mSettings.writeLPr(); 18925 pw.println("Settings written."); 18926 return; 18927 } 18928 } 18929 } 18930 18931 if (checkin) { 18932 pw.println("vers,1"); 18933 } 18934 18935 // reader 18936 synchronized (mPackages) { 18937 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18938 if (!checkin) { 18939 if (dumpState.onTitlePrinted()) 18940 pw.println(); 18941 pw.println("Database versions:"); 18942 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18943 } 18944 } 18945 18946 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18947 if (!checkin) { 18948 if (dumpState.onTitlePrinted()) 18949 pw.println(); 18950 pw.println("Verifiers:"); 18951 pw.print(" Required: "); 18952 pw.print(mRequiredVerifierPackage); 18953 pw.print(" (uid="); 18954 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18955 UserHandle.USER_SYSTEM)); 18956 pw.println(")"); 18957 } else if (mRequiredVerifierPackage != null) { 18958 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18959 pw.print(","); 18960 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18961 UserHandle.USER_SYSTEM)); 18962 } 18963 } 18964 18965 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18966 packageName == null) { 18967 if (mIntentFilterVerifierComponent != null) { 18968 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18969 if (!checkin) { 18970 if (dumpState.onTitlePrinted()) 18971 pw.println(); 18972 pw.println("Intent Filter Verifier:"); 18973 pw.print(" Using: "); 18974 pw.print(verifierPackageName); 18975 pw.print(" (uid="); 18976 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18977 UserHandle.USER_SYSTEM)); 18978 pw.println(")"); 18979 } else if (verifierPackageName != null) { 18980 pw.print("ifv,"); pw.print(verifierPackageName); 18981 pw.print(","); 18982 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18983 UserHandle.USER_SYSTEM)); 18984 } 18985 } else { 18986 pw.println(); 18987 pw.println("No Intent Filter Verifier available!"); 18988 } 18989 } 18990 18991 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18992 boolean printedHeader = false; 18993 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18994 while (it.hasNext()) { 18995 String name = it.next(); 18996 SharedLibraryEntry ent = mSharedLibraries.get(name); 18997 if (!checkin) { 18998 if (!printedHeader) { 18999 if (dumpState.onTitlePrinted()) 19000 pw.println(); 19001 pw.println("Libraries:"); 19002 printedHeader = true; 19003 } 19004 pw.print(" "); 19005 } else { 19006 pw.print("lib,"); 19007 } 19008 pw.print(name); 19009 if (!checkin) { 19010 pw.print(" -> "); 19011 } 19012 if (ent.path != null) { 19013 if (!checkin) { 19014 pw.print("(jar) "); 19015 pw.print(ent.path); 19016 } else { 19017 pw.print(",jar,"); 19018 pw.print(ent.path); 19019 } 19020 } else { 19021 if (!checkin) { 19022 pw.print("(apk) "); 19023 pw.print(ent.apk); 19024 } else { 19025 pw.print(",apk,"); 19026 pw.print(ent.apk); 19027 } 19028 } 19029 pw.println(); 19030 } 19031 } 19032 19033 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 19034 if (dumpState.onTitlePrinted()) 19035 pw.println(); 19036 if (!checkin) { 19037 pw.println("Features:"); 19038 } 19039 19040 for (FeatureInfo feat : mAvailableFeatures.values()) { 19041 if (checkin) { 19042 pw.print("feat,"); 19043 pw.print(feat.name); 19044 pw.print(","); 19045 pw.println(feat.version); 19046 } else { 19047 pw.print(" "); 19048 pw.print(feat.name); 19049 if (feat.version > 0) { 19050 pw.print(" version="); 19051 pw.print(feat.version); 19052 } 19053 pw.println(); 19054 } 19055 } 19056 } 19057 19058 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 19059 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 19060 : "Activity Resolver Table:", " ", packageName, 19061 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19062 dumpState.setTitlePrinted(true); 19063 } 19064 } 19065 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 19066 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 19067 : "Receiver Resolver Table:", " ", packageName, 19068 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19069 dumpState.setTitlePrinted(true); 19070 } 19071 } 19072 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 19073 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 19074 : "Service Resolver Table:", " ", packageName, 19075 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19076 dumpState.setTitlePrinted(true); 19077 } 19078 } 19079 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 19080 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 19081 : "Provider Resolver Table:", " ", packageName, 19082 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 19083 dumpState.setTitlePrinted(true); 19084 } 19085 } 19086 19087 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 19088 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19089 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19090 int user = mSettings.mPreferredActivities.keyAt(i); 19091 if (pir.dump(pw, 19092 dumpState.getTitlePrinted() 19093 ? "\nPreferred Activities User " + user + ":" 19094 : "Preferred Activities User " + user + ":", " ", 19095 packageName, true, false)) { 19096 dumpState.setTitlePrinted(true); 19097 } 19098 } 19099 } 19100 19101 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 19102 pw.flush(); 19103 FileOutputStream fout = new FileOutputStream(fd); 19104 BufferedOutputStream str = new BufferedOutputStream(fout); 19105 XmlSerializer serializer = new FastXmlSerializer(); 19106 try { 19107 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 19108 serializer.startDocument(null, true); 19109 serializer.setFeature( 19110 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 19111 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 19112 serializer.endDocument(); 19113 serializer.flush(); 19114 } catch (IllegalArgumentException e) { 19115 pw.println("Failed writing: " + e); 19116 } catch (IllegalStateException e) { 19117 pw.println("Failed writing: " + e); 19118 } catch (IOException e) { 19119 pw.println("Failed writing: " + e); 19120 } 19121 } 19122 19123 if (!checkin 19124 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 19125 && packageName == null) { 19126 pw.println(); 19127 int count = mSettings.mPackages.size(); 19128 if (count == 0) { 19129 pw.println("No applications!"); 19130 pw.println(); 19131 } else { 19132 final String prefix = " "; 19133 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 19134 if (allPackageSettings.size() == 0) { 19135 pw.println("No domain preferred apps!"); 19136 pw.println(); 19137 } else { 19138 pw.println("App verification status:"); 19139 pw.println(); 19140 count = 0; 19141 for (PackageSetting ps : allPackageSettings) { 19142 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 19143 if (ivi == null || ivi.getPackageName() == null) continue; 19144 pw.println(prefix + "Package: " + ivi.getPackageName()); 19145 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 19146 pw.println(prefix + "Status: " + ivi.getStatusString()); 19147 pw.println(); 19148 count++; 19149 } 19150 if (count == 0) { 19151 pw.println(prefix + "No app verification established."); 19152 pw.println(); 19153 } 19154 for (int userId : sUserManager.getUserIds()) { 19155 pw.println("App linkages for user " + userId + ":"); 19156 pw.println(); 19157 count = 0; 19158 for (PackageSetting ps : allPackageSettings) { 19159 final long status = ps.getDomainVerificationStatusForUser(userId); 19160 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 19161 continue; 19162 } 19163 pw.println(prefix + "Package: " + ps.name); 19164 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 19165 String statusStr = IntentFilterVerificationInfo. 19166 getStatusStringFromValue(status); 19167 pw.println(prefix + "Status: " + statusStr); 19168 pw.println(); 19169 count++; 19170 } 19171 if (count == 0) { 19172 pw.println(prefix + "No configured app linkages."); 19173 pw.println(); 19174 } 19175 } 19176 } 19177 } 19178 } 19179 19180 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 19181 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 19182 if (packageName == null && permissionNames == null) { 19183 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 19184 if (iperm == 0) { 19185 if (dumpState.onTitlePrinted()) 19186 pw.println(); 19187 pw.println("AppOp Permissions:"); 19188 } 19189 pw.print(" AppOp Permission "); 19190 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 19191 pw.println(":"); 19192 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 19193 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 19194 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 19195 } 19196 } 19197 } 19198 } 19199 19200 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 19201 boolean printedSomething = false; 19202 for (PackageParser.Provider p : mProviders.mProviders.values()) { 19203 if (packageName != null && !packageName.equals(p.info.packageName)) { 19204 continue; 19205 } 19206 if (!printedSomething) { 19207 if (dumpState.onTitlePrinted()) 19208 pw.println(); 19209 pw.println("Registered ContentProviders:"); 19210 printedSomething = true; 19211 } 19212 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 19213 pw.print(" "); pw.println(p.toString()); 19214 } 19215 printedSomething = false; 19216 for (Map.Entry<String, PackageParser.Provider> entry : 19217 mProvidersByAuthority.entrySet()) { 19218 PackageParser.Provider p = entry.getValue(); 19219 if (packageName != null && !packageName.equals(p.info.packageName)) { 19220 continue; 19221 } 19222 if (!printedSomething) { 19223 if (dumpState.onTitlePrinted()) 19224 pw.println(); 19225 pw.println("ContentProvider Authorities:"); 19226 printedSomething = true; 19227 } 19228 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 19229 pw.print(" "); pw.println(p.toString()); 19230 if (p.info != null && p.info.applicationInfo != null) { 19231 final String appInfo = p.info.applicationInfo.toString(); 19232 pw.print(" applicationInfo="); pw.println(appInfo); 19233 } 19234 } 19235 } 19236 19237 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 19238 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 19239 } 19240 19241 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 19242 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 19243 } 19244 19245 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 19246 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 19247 } 19248 19249 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 19250 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 19251 } 19252 19253 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 19254 // XXX should handle packageName != null by dumping only install data that 19255 // the given package is involved with. 19256 if (dumpState.onTitlePrinted()) pw.println(); 19257 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 19258 } 19259 19260 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 19261 // XXX should handle packageName != null by dumping only install data that 19262 // the given package is involved with. 19263 if (dumpState.onTitlePrinted()) pw.println(); 19264 19265 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19266 ipw.println(); 19267 ipw.println("Frozen packages:"); 19268 ipw.increaseIndent(); 19269 if (mFrozenPackages.size() == 0) { 19270 ipw.println("(none)"); 19271 } else { 19272 for (int i = 0; i < mFrozenPackages.size(); i++) { 19273 ipw.println(mFrozenPackages.valueAt(i)); 19274 } 19275 } 19276 ipw.decreaseIndent(); 19277 } 19278 19279 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 19280 if (dumpState.onTitlePrinted()) pw.println(); 19281 dumpDexoptStateLPr(pw, packageName); 19282 } 19283 19284 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 19285 if (dumpState.onTitlePrinted()) pw.println(); 19286 dumpCompilerStatsLPr(pw, packageName); 19287 } 19288 19289 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 19290 if (dumpState.onTitlePrinted()) pw.println(); 19291 mSettings.dumpReadMessagesLPr(pw, dumpState); 19292 19293 pw.println(); 19294 pw.println("Package warning messages:"); 19295 BufferedReader in = null; 19296 String line = null; 19297 try { 19298 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19299 while ((line = in.readLine()) != null) { 19300 if (line.contains("ignored: updated version")) continue; 19301 pw.println(line); 19302 } 19303 } catch (IOException ignored) { 19304 } finally { 19305 IoUtils.closeQuietly(in); 19306 } 19307 } 19308 19309 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 19310 BufferedReader in = null; 19311 String line = null; 19312 try { 19313 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 19314 while ((line = in.readLine()) != null) { 19315 if (line.contains("ignored: updated version")) continue; 19316 pw.print("msg,"); 19317 pw.println(line); 19318 } 19319 } catch (IOException ignored) { 19320 } finally { 19321 IoUtils.closeQuietly(in); 19322 } 19323 } 19324 } 19325 } 19326 19327 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 19328 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19329 ipw.println(); 19330 ipw.println("Dexopt state:"); 19331 ipw.increaseIndent(); 19332 Collection<PackageParser.Package> packages = null; 19333 if (packageName != null) { 19334 PackageParser.Package targetPackage = mPackages.get(packageName); 19335 if (targetPackage != null) { 19336 packages = Collections.singletonList(targetPackage); 19337 } else { 19338 ipw.println("Unable to find package: " + packageName); 19339 return; 19340 } 19341 } else { 19342 packages = mPackages.values(); 19343 } 19344 19345 for (PackageParser.Package pkg : packages) { 19346 ipw.println("[" + pkg.packageName + "]"); 19347 ipw.increaseIndent(); 19348 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 19349 ipw.decreaseIndent(); 19350 } 19351 } 19352 19353 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 19354 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 19355 ipw.println(); 19356 ipw.println("Compiler stats:"); 19357 ipw.increaseIndent(); 19358 Collection<PackageParser.Package> packages = null; 19359 if (packageName != null) { 19360 PackageParser.Package targetPackage = mPackages.get(packageName); 19361 if (targetPackage != null) { 19362 packages = Collections.singletonList(targetPackage); 19363 } else { 19364 ipw.println("Unable to find package: " + packageName); 19365 return; 19366 } 19367 } else { 19368 packages = mPackages.values(); 19369 } 19370 19371 for (PackageParser.Package pkg : packages) { 19372 ipw.println("[" + pkg.packageName + "]"); 19373 ipw.increaseIndent(); 19374 19375 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 19376 if (stats == null) { 19377 ipw.println("(No recorded stats)"); 19378 } else { 19379 stats.dump(ipw); 19380 } 19381 ipw.decreaseIndent(); 19382 } 19383 } 19384 19385 private String dumpDomainString(String packageName) { 19386 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 19387 .getList(); 19388 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 19389 19390 ArraySet<String> result = new ArraySet<>(); 19391 if (iviList.size() > 0) { 19392 for (IntentFilterVerificationInfo ivi : iviList) { 19393 for (String host : ivi.getDomains()) { 19394 result.add(host); 19395 } 19396 } 19397 } 19398 if (filters != null && filters.size() > 0) { 19399 for (IntentFilter filter : filters) { 19400 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 19401 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 19402 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 19403 result.addAll(filter.getHostsList()); 19404 } 19405 } 19406 } 19407 19408 StringBuilder sb = new StringBuilder(result.size() * 16); 19409 for (String domain : result) { 19410 if (sb.length() > 0) sb.append(" "); 19411 sb.append(domain); 19412 } 19413 return sb.toString(); 19414 } 19415 19416 // ------- apps on sdcard specific code ------- 19417 static final boolean DEBUG_SD_INSTALL = false; 19418 19419 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 19420 19421 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 19422 19423 private boolean mMediaMounted = false; 19424 19425 static String getEncryptKey() { 19426 try { 19427 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 19428 SD_ENCRYPTION_KEYSTORE_NAME); 19429 if (sdEncKey == null) { 19430 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 19431 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 19432 if (sdEncKey == null) { 19433 Slog.e(TAG, "Failed to create encryption keys"); 19434 return null; 19435 } 19436 } 19437 return sdEncKey; 19438 } catch (NoSuchAlgorithmException nsae) { 19439 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 19440 return null; 19441 } catch (IOException ioe) { 19442 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 19443 return null; 19444 } 19445 } 19446 19447 /* 19448 * Update media status on PackageManager. 19449 */ 19450 @Override 19451 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 19452 int callingUid = Binder.getCallingUid(); 19453 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 19454 throw new SecurityException("Media status can only be updated by the system"); 19455 } 19456 // reader; this apparently protects mMediaMounted, but should probably 19457 // be a different lock in that case. 19458 synchronized (mPackages) { 19459 Log.i(TAG, "Updating external media status from " 19460 + (mMediaMounted ? "mounted" : "unmounted") + " to " 19461 + (mediaStatus ? "mounted" : "unmounted")); 19462 if (DEBUG_SD_INSTALL) 19463 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 19464 + ", mMediaMounted=" + mMediaMounted); 19465 if (mediaStatus == mMediaMounted) { 19466 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 19467 : 0, -1); 19468 mHandler.sendMessage(msg); 19469 return; 19470 } 19471 mMediaMounted = mediaStatus; 19472 } 19473 // Queue up an async operation since the package installation may take a 19474 // little while. 19475 mHandler.post(new Runnable() { 19476 public void run() { 19477 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 19478 } 19479 }); 19480 } 19481 19482 /** 19483 * Called by StorageManagerService when the initial ASECs to scan are available. 19484 * Should block until all the ASEC containers are finished being scanned. 19485 */ 19486 public void scanAvailableAsecs() { 19487 updateExternalMediaStatusInner(true, false, false); 19488 } 19489 19490 /* 19491 * Collect information of applications on external media, map them against 19492 * existing containers and update information based on current mount status. 19493 * Please note that we always have to report status if reportStatus has been 19494 * set to true especially when unloading packages. 19495 */ 19496 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 19497 boolean externalStorage) { 19498 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 19499 int[] uidArr = EmptyArray.INT; 19500 19501 final String[] list = PackageHelper.getSecureContainerList(); 19502 if (ArrayUtils.isEmpty(list)) { 19503 Log.i(TAG, "No secure containers found"); 19504 } else { 19505 // Process list of secure containers and categorize them 19506 // as active or stale based on their package internal state. 19507 19508 // reader 19509 synchronized (mPackages) { 19510 for (String cid : list) { 19511 // Leave stages untouched for now; installer service owns them 19512 if (PackageInstallerService.isStageName(cid)) continue; 19513 19514 if (DEBUG_SD_INSTALL) 19515 Log.i(TAG, "Processing container " + cid); 19516 String pkgName = getAsecPackageName(cid); 19517 if (pkgName == null) { 19518 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 19519 continue; 19520 } 19521 if (DEBUG_SD_INSTALL) 19522 Log.i(TAG, "Looking for pkg : " + pkgName); 19523 19524 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19525 if (ps == null) { 19526 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 19527 continue; 19528 } 19529 19530 /* 19531 * Skip packages that are not external if we're unmounting 19532 * external storage. 19533 */ 19534 if (externalStorage && !isMounted && !isExternal(ps)) { 19535 continue; 19536 } 19537 19538 final AsecInstallArgs args = new AsecInstallArgs(cid, 19539 getAppDexInstructionSets(ps), ps.isForwardLocked()); 19540 // The package status is changed only if the code path 19541 // matches between settings and the container id. 19542 if (ps.codePathString != null 19543 && ps.codePathString.startsWith(args.getCodePath())) { 19544 if (DEBUG_SD_INSTALL) { 19545 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 19546 + " at code path: " + ps.codePathString); 19547 } 19548 19549 // We do have a valid package installed on sdcard 19550 processCids.put(args, ps.codePathString); 19551 final int uid = ps.appId; 19552 if (uid != -1) { 19553 uidArr = ArrayUtils.appendInt(uidArr, uid); 19554 } 19555 } else { 19556 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19557 + ps.codePathString); 19558 } 19559 } 19560 } 19561 19562 Arrays.sort(uidArr); 19563 } 19564 19565 // Process packages with valid entries. 19566 if (isMounted) { 19567 if (DEBUG_SD_INSTALL) 19568 Log.i(TAG, "Loading packages"); 19569 loadMediaPackages(processCids, uidArr, externalStorage); 19570 startCleaningPackages(); 19571 mInstallerService.onSecureContainersAvailable(); 19572 } else { 19573 if (DEBUG_SD_INSTALL) 19574 Log.i(TAG, "Unloading packages"); 19575 unloadMediaPackages(processCids, uidArr, reportStatus); 19576 } 19577 } 19578 19579 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19580 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19581 final int size = infos.size(); 19582 final String[] packageNames = new String[size]; 19583 final int[] packageUids = new int[size]; 19584 for (int i = 0; i < size; i++) { 19585 final ApplicationInfo info = infos.get(i); 19586 packageNames[i] = info.packageName; 19587 packageUids[i] = info.uid; 19588 } 19589 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19590 finishedReceiver); 19591 } 19592 19593 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19594 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19595 sendResourcesChangedBroadcast(mediaStatus, replacing, 19596 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19597 } 19598 19599 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19600 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19601 int size = pkgList.length; 19602 if (size > 0) { 19603 // Send broadcasts here 19604 Bundle extras = new Bundle(); 19605 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19606 if (uidArr != null) { 19607 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19608 } 19609 if (replacing) { 19610 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19611 } 19612 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19613 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19614 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19615 } 19616 } 19617 19618 /* 19619 * Look at potentially valid container ids from processCids If package 19620 * information doesn't match the one on record or package scanning fails, 19621 * the cid is added to list of removeCids. We currently don't delete stale 19622 * containers. 19623 */ 19624 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19625 boolean externalStorage) { 19626 ArrayList<String> pkgList = new ArrayList<String>(); 19627 Set<AsecInstallArgs> keys = processCids.keySet(); 19628 19629 for (AsecInstallArgs args : keys) { 19630 String codePath = processCids.get(args); 19631 if (DEBUG_SD_INSTALL) 19632 Log.i(TAG, "Loading container : " + args.cid); 19633 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19634 try { 19635 // Make sure there are no container errors first. 19636 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19637 Slog.e(TAG, "Failed to mount cid : " + args.cid 19638 + " when installing from sdcard"); 19639 continue; 19640 } 19641 // Check code path here. 19642 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19643 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19644 + " does not match one in settings " + codePath); 19645 continue; 19646 } 19647 // Parse package 19648 int parseFlags = mDefParseFlags; 19649 if (args.isExternalAsec()) { 19650 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19651 } 19652 if (args.isFwdLocked()) { 19653 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19654 } 19655 19656 synchronized (mInstallLock) { 19657 PackageParser.Package pkg = null; 19658 try { 19659 // Sadly we don't know the package name yet to freeze it 19660 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19661 SCAN_IGNORE_FROZEN, 0, null); 19662 } catch (PackageManagerException e) { 19663 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19664 } 19665 // Scan the package 19666 if (pkg != null) { 19667 /* 19668 * TODO why is the lock being held? doPostInstall is 19669 * called in other places without the lock. This needs 19670 * to be straightened out. 19671 */ 19672 // writer 19673 synchronized (mPackages) { 19674 retCode = PackageManager.INSTALL_SUCCEEDED; 19675 pkgList.add(pkg.packageName); 19676 // Post process args 19677 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19678 pkg.applicationInfo.uid); 19679 } 19680 } else { 19681 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19682 } 19683 } 19684 19685 } finally { 19686 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19687 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19688 } 19689 } 19690 } 19691 // writer 19692 synchronized (mPackages) { 19693 // If the platform SDK has changed since the last time we booted, 19694 // we need to re-grant app permission to catch any new ones that 19695 // appear. This is really a hack, and means that apps can in some 19696 // cases get permissions that the user didn't initially explicitly 19697 // allow... it would be nice to have some better way to handle 19698 // this situation. 19699 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19700 : mSettings.getInternalVersion(); 19701 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19702 : StorageManager.UUID_PRIVATE_INTERNAL; 19703 19704 int updateFlags = UPDATE_PERMISSIONS_ALL; 19705 if (ver.sdkVersion != mSdkVersion) { 19706 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19707 + mSdkVersion + "; regranting permissions for external"); 19708 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19709 } 19710 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19711 19712 // Yay, everything is now upgraded 19713 ver.forceCurrent(); 19714 19715 // can downgrade to reader 19716 // Persist settings 19717 mSettings.writeLPr(); 19718 } 19719 // Send a broadcast to let everyone know we are done processing 19720 if (pkgList.size() > 0) { 19721 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19722 } 19723 } 19724 19725 /* 19726 * Utility method to unload a list of specified containers 19727 */ 19728 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19729 // Just unmount all valid containers. 19730 for (AsecInstallArgs arg : cidArgs) { 19731 synchronized (mInstallLock) { 19732 arg.doPostDeleteLI(false); 19733 } 19734 } 19735 } 19736 19737 /* 19738 * Unload packages mounted on external media. This involves deleting package 19739 * data from internal structures, sending broadcasts about disabled packages, 19740 * gc'ing to free up references, unmounting all secure containers 19741 * corresponding to packages on external media, and posting a 19742 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19743 * that we always have to post this message if status has been requested no 19744 * matter what. 19745 */ 19746 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19747 final boolean reportStatus) { 19748 if (DEBUG_SD_INSTALL) 19749 Log.i(TAG, "unloading media packages"); 19750 ArrayList<String> pkgList = new ArrayList<String>(); 19751 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19752 final Set<AsecInstallArgs> keys = processCids.keySet(); 19753 for (AsecInstallArgs args : keys) { 19754 String pkgName = args.getPackageName(); 19755 if (DEBUG_SD_INSTALL) 19756 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19757 // Delete package internally 19758 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19759 synchronized (mInstallLock) { 19760 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19761 final boolean res; 19762 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19763 "unloadMediaPackages")) { 19764 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19765 null); 19766 } 19767 if (res) { 19768 pkgList.add(pkgName); 19769 } else { 19770 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19771 failedList.add(args); 19772 } 19773 } 19774 } 19775 19776 // reader 19777 synchronized (mPackages) { 19778 // We didn't update the settings after removing each package; 19779 // write them now for all packages. 19780 mSettings.writeLPr(); 19781 } 19782 19783 // We have to absolutely send UPDATED_MEDIA_STATUS only 19784 // after confirming that all the receivers processed the ordered 19785 // broadcast when packages get disabled, force a gc to clean things up. 19786 // and unload all the containers. 19787 if (pkgList.size() > 0) { 19788 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19789 new IIntentReceiver.Stub() { 19790 public void performReceive(Intent intent, int resultCode, String data, 19791 Bundle extras, boolean ordered, boolean sticky, 19792 int sendingUser) throws RemoteException { 19793 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19794 reportStatus ? 1 : 0, 1, keys); 19795 mHandler.sendMessage(msg); 19796 } 19797 }); 19798 } else { 19799 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19800 keys); 19801 mHandler.sendMessage(msg); 19802 } 19803 } 19804 19805 private void loadPrivatePackages(final VolumeInfo vol) { 19806 mHandler.post(new Runnable() { 19807 @Override 19808 public void run() { 19809 loadPrivatePackagesInner(vol); 19810 } 19811 }); 19812 } 19813 19814 private void loadPrivatePackagesInner(VolumeInfo vol) { 19815 final String volumeUuid = vol.fsUuid; 19816 if (TextUtils.isEmpty(volumeUuid)) { 19817 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19818 return; 19819 } 19820 19821 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19822 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19823 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19824 19825 final VersionInfo ver; 19826 final List<PackageSetting> packages; 19827 synchronized (mPackages) { 19828 ver = mSettings.findOrCreateVersion(volumeUuid); 19829 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19830 } 19831 19832 for (PackageSetting ps : packages) { 19833 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19834 synchronized (mInstallLock) { 19835 final PackageParser.Package pkg; 19836 try { 19837 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19838 loaded.add(pkg.applicationInfo); 19839 19840 } catch (PackageManagerException e) { 19841 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19842 } 19843 19844 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19845 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19846 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19847 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19848 } 19849 } 19850 } 19851 19852 // Reconcile app data for all started/unlocked users 19853 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19854 final UserManager um = mContext.getSystemService(UserManager.class); 19855 UserManagerInternal umInternal = getUserManagerInternal(); 19856 for (UserInfo user : um.getUsers()) { 19857 final int flags; 19858 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19859 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19860 } else if (umInternal.isUserRunning(user.id)) { 19861 flags = StorageManager.FLAG_STORAGE_DE; 19862 } else { 19863 continue; 19864 } 19865 19866 try { 19867 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19868 synchronized (mInstallLock) { 19869 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 19870 } 19871 } catch (IllegalStateException e) { 19872 // Device was probably ejected, and we'll process that event momentarily 19873 Slog.w(TAG, "Failed to prepare storage: " + e); 19874 } 19875 } 19876 19877 synchronized (mPackages) { 19878 int updateFlags = UPDATE_PERMISSIONS_ALL; 19879 if (ver.sdkVersion != mSdkVersion) { 19880 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19881 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19882 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19883 } 19884 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19885 19886 // Yay, everything is now upgraded 19887 ver.forceCurrent(); 19888 19889 mSettings.writeLPr(); 19890 } 19891 19892 for (PackageFreezer freezer : freezers) { 19893 freezer.close(); 19894 } 19895 19896 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19897 sendResourcesChangedBroadcast(true, false, loaded, null); 19898 } 19899 19900 private void unloadPrivatePackages(final VolumeInfo vol) { 19901 mHandler.post(new Runnable() { 19902 @Override 19903 public void run() { 19904 unloadPrivatePackagesInner(vol); 19905 } 19906 }); 19907 } 19908 19909 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19910 final String volumeUuid = vol.fsUuid; 19911 if (TextUtils.isEmpty(volumeUuid)) { 19912 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19913 return; 19914 } 19915 19916 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19917 synchronized (mInstallLock) { 19918 synchronized (mPackages) { 19919 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19920 for (PackageSetting ps : packages) { 19921 if (ps.pkg == null) continue; 19922 19923 final ApplicationInfo info = ps.pkg.applicationInfo; 19924 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19925 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19926 19927 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19928 "unloadPrivatePackagesInner")) { 19929 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19930 false, null)) { 19931 unloaded.add(info); 19932 } else { 19933 Slog.w(TAG, "Failed to unload " + ps.codePath); 19934 } 19935 } 19936 19937 // Try very hard to release any references to this package 19938 // so we don't risk the system server being killed due to 19939 // open FDs 19940 AttributeCache.instance().removePackage(ps.name); 19941 } 19942 19943 mSettings.writeLPr(); 19944 } 19945 } 19946 19947 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19948 sendResourcesChangedBroadcast(false, false, unloaded, null); 19949 19950 // Try very hard to release any references to this path so we don't risk 19951 // the system server being killed due to open FDs 19952 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19953 19954 for (int i = 0; i < 3; i++) { 19955 System.gc(); 19956 System.runFinalization(); 19957 } 19958 } 19959 19960 /** 19961 * Prepare storage areas for given user on all mounted devices. 19962 */ 19963 void prepareUserData(int userId, int userSerial, int flags) { 19964 synchronized (mInstallLock) { 19965 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19966 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19967 final String volumeUuid = vol.getFsUuid(); 19968 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19969 } 19970 } 19971 } 19972 19973 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19974 boolean allowRecover) { 19975 // Prepare storage and verify that serial numbers are consistent; if 19976 // there's a mismatch we need to destroy to avoid leaking data 19977 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19978 try { 19979 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19980 19981 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19982 UserManagerService.enforceSerialNumber( 19983 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19984 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19985 UserManagerService.enforceSerialNumber( 19986 Environment.getDataSystemDeDirectory(userId), userSerial); 19987 } 19988 } 19989 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19990 UserManagerService.enforceSerialNumber( 19991 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19992 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19993 UserManagerService.enforceSerialNumber( 19994 Environment.getDataSystemCeDirectory(userId), userSerial); 19995 } 19996 } 19997 19998 synchronized (mInstallLock) { 19999 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 20000 } 20001 } catch (Exception e) { 20002 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 20003 + " because we failed to prepare: " + e); 20004 destroyUserDataLI(volumeUuid, userId, 20005 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20006 20007 if (allowRecover) { 20008 // Try one last time; if we fail again we're really in trouble 20009 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 20010 } 20011 } 20012 } 20013 20014 /** 20015 * Destroy storage areas for given user on all mounted devices. 20016 */ 20017 void destroyUserData(int userId, int flags) { 20018 synchronized (mInstallLock) { 20019 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20020 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20021 final String volumeUuid = vol.getFsUuid(); 20022 destroyUserDataLI(volumeUuid, userId, flags); 20023 } 20024 } 20025 } 20026 20027 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 20028 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20029 try { 20030 // Clean up app data, profile data, and media data 20031 mInstaller.destroyUserData(volumeUuid, userId, flags); 20032 20033 // Clean up system data 20034 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 20035 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20036 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 20037 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 20038 } 20039 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20040 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 20041 } 20042 } 20043 20044 // Data with special labels is now gone, so finish the job 20045 storage.destroyUserStorage(volumeUuid, userId, flags); 20046 20047 } catch (Exception e) { 20048 logCriticalInfo(Log.WARN, 20049 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 20050 } 20051 } 20052 20053 /** 20054 * Examine all users present on given mounted volume, and destroy data 20055 * belonging to users that are no longer valid, or whose user ID has been 20056 * recycled. 20057 */ 20058 private void reconcileUsers(String volumeUuid) { 20059 final List<File> files = new ArrayList<>(); 20060 Collections.addAll(files, FileUtils 20061 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 20062 Collections.addAll(files, FileUtils 20063 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 20064 Collections.addAll(files, FileUtils 20065 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 20066 Collections.addAll(files, FileUtils 20067 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 20068 for (File file : files) { 20069 if (!file.isDirectory()) continue; 20070 20071 final int userId; 20072 final UserInfo info; 20073 try { 20074 userId = Integer.parseInt(file.getName()); 20075 info = sUserManager.getUserInfo(userId); 20076 } catch (NumberFormatException e) { 20077 Slog.w(TAG, "Invalid user directory " + file); 20078 continue; 20079 } 20080 20081 boolean destroyUser = false; 20082 if (info == null) { 20083 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20084 + " because no matching user was found"); 20085 destroyUser = true; 20086 } else if (!mOnlyCore) { 20087 try { 20088 UserManagerService.enforceSerialNumber(file, info.serialNumber); 20089 } catch (IOException e) { 20090 logCriticalInfo(Log.WARN, "Destroying user directory " + file 20091 + " because we failed to enforce serial number: " + e); 20092 destroyUser = true; 20093 } 20094 } 20095 20096 if (destroyUser) { 20097 synchronized (mInstallLock) { 20098 destroyUserDataLI(volumeUuid, userId, 20099 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 20100 } 20101 } 20102 } 20103 } 20104 20105 private void assertPackageKnown(String volumeUuid, String packageName) 20106 throws PackageManagerException { 20107 synchronized (mPackages) { 20108 final PackageSetting ps = mSettings.mPackages.get(packageName); 20109 if (ps == null) { 20110 throw new PackageManagerException("Package " + packageName + " is unknown"); 20111 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20112 throw new PackageManagerException( 20113 "Package " + packageName + " found on unknown volume " + volumeUuid 20114 + "; expected volume " + ps.volumeUuid); 20115 } 20116 } 20117 } 20118 20119 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 20120 throws PackageManagerException { 20121 synchronized (mPackages) { 20122 final PackageSetting ps = mSettings.mPackages.get(packageName); 20123 if (ps == null) { 20124 throw new PackageManagerException("Package " + packageName + " is unknown"); 20125 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 20126 throw new PackageManagerException( 20127 "Package " + packageName + " found on unknown volume " + volumeUuid 20128 + "; expected volume " + ps.volumeUuid); 20129 } else if (!ps.getInstalled(userId)) { 20130 throw new PackageManagerException( 20131 "Package " + packageName + " not installed for user " + userId); 20132 } 20133 } 20134 } 20135 20136 /** 20137 * Examine all apps present on given mounted volume, and destroy apps that 20138 * aren't expected, either due to uninstallation or reinstallation on 20139 * another volume. 20140 */ 20141 private void reconcileApps(String volumeUuid) { 20142 final File[] files = FileUtils 20143 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 20144 for (File file : files) { 20145 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 20146 && !PackageInstallerService.isStageName(file.getName()); 20147 if (!isPackage) { 20148 // Ignore entries which are not packages 20149 continue; 20150 } 20151 20152 try { 20153 final PackageLite pkg = PackageParser.parsePackageLite(file, 20154 PackageParser.PARSE_MUST_BE_APK); 20155 assertPackageKnown(volumeUuid, pkg.packageName); 20156 20157 } catch (PackageParserException | PackageManagerException e) { 20158 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20159 synchronized (mInstallLock) { 20160 removeCodePathLI(file); 20161 } 20162 } 20163 } 20164 } 20165 20166 /** 20167 * Reconcile all app data for the given user. 20168 * <p> 20169 * Verifies that directories exist and that ownership and labeling is 20170 * correct for all installed apps on all mounted volumes. 20171 */ 20172 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 20173 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20174 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 20175 final String volumeUuid = vol.getFsUuid(); 20176 synchronized (mInstallLock) { 20177 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 20178 } 20179 } 20180 } 20181 20182 /** 20183 * Reconcile all app data on given mounted volume. 20184 * <p> 20185 * Destroys app data that isn't expected, either due to uninstallation or 20186 * reinstallation on another volume. 20187 * <p> 20188 * Verifies that directories exist and that ownership and labeling is 20189 * correct for all installed apps. 20190 */ 20191 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 20192 boolean migrateAppData) { 20193 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 20194 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 20195 20196 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 20197 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 20198 20199 // First look for stale data that doesn't belong, and check if things 20200 // have changed since we did our last restorecon 20201 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20202 if (StorageManager.isFileEncryptedNativeOrEmulated() 20203 && !StorageManager.isUserKeyUnlocked(userId)) { 20204 throw new RuntimeException( 20205 "Yikes, someone asked us to reconcile CE storage while " + userId 20206 + " was still locked; this would have caused massive data loss!"); 20207 } 20208 20209 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 20210 for (File file : files) { 20211 final String packageName = file.getName(); 20212 try { 20213 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20214 } catch (PackageManagerException e) { 20215 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20216 try { 20217 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20218 StorageManager.FLAG_STORAGE_CE, 0); 20219 } catch (InstallerException e2) { 20220 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20221 } 20222 } 20223 } 20224 } 20225 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 20226 final File[] files = FileUtils.listFilesOrEmpty(deDir); 20227 for (File file : files) { 20228 final String packageName = file.getName(); 20229 try { 20230 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 20231 } catch (PackageManagerException e) { 20232 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 20233 try { 20234 mInstaller.destroyAppData(volumeUuid, packageName, userId, 20235 StorageManager.FLAG_STORAGE_DE, 0); 20236 } catch (InstallerException e2) { 20237 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 20238 } 20239 } 20240 } 20241 } 20242 20243 // Ensure that data directories are ready to roll for all packages 20244 // installed for this volume and user 20245 final List<PackageSetting> packages; 20246 synchronized (mPackages) { 20247 packages = mSettings.getVolumePackagesLPr(volumeUuid); 20248 } 20249 int preparedCount = 0; 20250 for (PackageSetting ps : packages) { 20251 final String packageName = ps.name; 20252 if (ps.pkg == null) { 20253 Slog.w(TAG, "Odd, missing scanned package " + packageName); 20254 // TODO: might be due to legacy ASEC apps; we should circle back 20255 // and reconcile again once they're scanned 20256 continue; 20257 } 20258 20259 if (ps.getInstalled(userId)) { 20260 prepareAppDataLIF(ps.pkg, userId, flags); 20261 20262 if (migrateAppData && maybeMigrateAppDataLIF(ps.pkg, userId)) { 20263 // We may have just shuffled around app data directories, so 20264 // prepare them one more time 20265 prepareAppDataLIF(ps.pkg, userId, flags); 20266 } 20267 20268 preparedCount++; 20269 } 20270 } 20271 20272 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 20273 } 20274 20275 /** 20276 * Prepare app data for the given app just after it was installed or 20277 * upgraded. This method carefully only touches users that it's installed 20278 * for, and it forces a restorecon to handle any seinfo changes. 20279 * <p> 20280 * Verifies that directories exist and that ownership and labeling is 20281 * correct for all installed apps. If there is an ownership mismatch, it 20282 * will try recovering system apps by wiping data; third-party app data is 20283 * left intact. 20284 * <p> 20285 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 20286 */ 20287 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 20288 final PackageSetting ps; 20289 synchronized (mPackages) { 20290 ps = mSettings.mPackages.get(pkg.packageName); 20291 mSettings.writeKernelMappingLPr(ps); 20292 } 20293 20294 final UserManager um = mContext.getSystemService(UserManager.class); 20295 UserManagerInternal umInternal = getUserManagerInternal(); 20296 for (UserInfo user : um.getUsers()) { 20297 final int flags; 20298 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 20299 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 20300 } else if (umInternal.isUserRunning(user.id)) { 20301 flags = StorageManager.FLAG_STORAGE_DE; 20302 } else { 20303 continue; 20304 } 20305 20306 if (ps.getInstalled(user.id)) { 20307 // TODO: when user data is locked, mark that we're still dirty 20308 prepareAppDataLIF(pkg, user.id, flags); 20309 } 20310 } 20311 } 20312 20313 /** 20314 * Prepare app data for the given app. 20315 * <p> 20316 * Verifies that directories exist and that ownership and labeling is 20317 * correct for all installed apps. If there is an ownership mismatch, this 20318 * will try recovering system apps by wiping data; third-party app data is 20319 * left intact. 20320 */ 20321 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 20322 if (pkg == null) { 20323 Slog.wtf(TAG, "Package was null!", new Throwable()); 20324 return; 20325 } 20326 prepareAppDataLeafLIF(pkg, userId, flags); 20327 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20328 for (int i = 0; i < childCount; i++) { 20329 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 20330 } 20331 } 20332 20333 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20334 if (DEBUG_APP_DATA) { 20335 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 20336 + Integer.toHexString(flags)); 20337 } 20338 20339 final String volumeUuid = pkg.volumeUuid; 20340 final String packageName = pkg.packageName; 20341 final ApplicationInfo app = pkg.applicationInfo; 20342 final int appId = UserHandle.getAppId(app.uid); 20343 20344 Preconditions.checkNotNull(app.seinfo); 20345 20346 try { 20347 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20348 appId, app.seinfo, app.targetSdkVersion); 20349 } catch (InstallerException e) { 20350 if (app.isSystemApp()) { 20351 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 20352 + ", but trying to recover: " + e); 20353 destroyAppDataLeafLIF(pkg, userId, flags); 20354 try { 20355 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 20356 appId, app.seinfo, app.targetSdkVersion); 20357 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 20358 } catch (InstallerException e2) { 20359 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 20360 } 20361 } else { 20362 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 20363 } 20364 } 20365 20366 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20367 try { 20368 // CE storage is unlocked right now, so read out the inode and 20369 // remember for use later when it's locked 20370 // TODO: mark this structure as dirty so we persist it! 20371 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 20372 StorageManager.FLAG_STORAGE_CE); 20373 synchronized (mPackages) { 20374 final PackageSetting ps = mSettings.mPackages.get(packageName); 20375 if (ps != null) { 20376 ps.setCeDataInode(ceDataInode, userId); 20377 } 20378 } 20379 } catch (InstallerException e) { 20380 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 20381 } 20382 } 20383 20384 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20385 } 20386 20387 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 20388 if (pkg == null) { 20389 Slog.wtf(TAG, "Package was null!", new Throwable()); 20390 return; 20391 } 20392 prepareAppDataContentsLeafLIF(pkg, userId, flags); 20393 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 20394 for (int i = 0; i < childCount; i++) { 20395 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 20396 } 20397 } 20398 20399 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 20400 final String volumeUuid = pkg.volumeUuid; 20401 final String packageName = pkg.packageName; 20402 final ApplicationInfo app = pkg.applicationInfo; 20403 20404 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 20405 // Create a native library symlink only if we have native libraries 20406 // and if the native libraries are 32 bit libraries. We do not provide 20407 // this symlink for 64 bit libraries. 20408 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 20409 final String nativeLibPath = app.nativeLibraryDir; 20410 try { 20411 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 20412 nativeLibPath, userId); 20413 } catch (InstallerException e) { 20414 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 20415 } 20416 } 20417 } 20418 } 20419 20420 /** 20421 * For system apps on non-FBE devices, this method migrates any existing 20422 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 20423 * requested by the app. 20424 */ 20425 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 20426 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 20427 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 20428 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 20429 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 20430 try { 20431 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 20432 storageTarget); 20433 } catch (InstallerException e) { 20434 logCriticalInfo(Log.WARN, 20435 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 20436 } 20437 return true; 20438 } else { 20439 return false; 20440 } 20441 } 20442 20443 public PackageFreezer freezePackage(String packageName, String killReason) { 20444 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 20445 } 20446 20447 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 20448 return new PackageFreezer(packageName, userId, killReason); 20449 } 20450 20451 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 20452 String killReason) { 20453 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 20454 } 20455 20456 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 20457 String killReason) { 20458 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 20459 return new PackageFreezer(); 20460 } else { 20461 return freezePackage(packageName, userId, killReason); 20462 } 20463 } 20464 20465 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 20466 String killReason) { 20467 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 20468 } 20469 20470 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 20471 String killReason) { 20472 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 20473 return new PackageFreezer(); 20474 } else { 20475 return freezePackage(packageName, userId, killReason); 20476 } 20477 } 20478 20479 /** 20480 * Class that freezes and kills the given package upon creation, and 20481 * unfreezes it upon closing. This is typically used when doing surgery on 20482 * app code/data to prevent the app from running while you're working. 20483 */ 20484 private class PackageFreezer implements AutoCloseable { 20485 private final String mPackageName; 20486 private final PackageFreezer[] mChildren; 20487 20488 private final boolean mWeFroze; 20489 20490 private final AtomicBoolean mClosed = new AtomicBoolean(); 20491 private final CloseGuard mCloseGuard = CloseGuard.get(); 20492 20493 /** 20494 * Create and return a stub freezer that doesn't actually do anything, 20495 * typically used when someone requested 20496 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 20497 * {@link PackageManager#DELETE_DONT_KILL_APP}. 20498 */ 20499 public PackageFreezer() { 20500 mPackageName = null; 20501 mChildren = null; 20502 mWeFroze = false; 20503 mCloseGuard.open("close"); 20504 } 20505 20506 public PackageFreezer(String packageName, int userId, String killReason) { 20507 synchronized (mPackages) { 20508 mPackageName = packageName; 20509 mWeFroze = mFrozenPackages.add(mPackageName); 20510 20511 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 20512 if (ps != null) { 20513 killApplication(ps.name, ps.appId, userId, killReason); 20514 } 20515 20516 final PackageParser.Package p = mPackages.get(packageName); 20517 if (p != null && p.childPackages != null) { 20518 final int N = p.childPackages.size(); 20519 mChildren = new PackageFreezer[N]; 20520 for (int i = 0; i < N; i++) { 20521 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 20522 userId, killReason); 20523 } 20524 } else { 20525 mChildren = null; 20526 } 20527 } 20528 mCloseGuard.open("close"); 20529 } 20530 20531 @Override 20532 protected void finalize() throws Throwable { 20533 try { 20534 mCloseGuard.warnIfOpen(); 20535 close(); 20536 } finally { 20537 super.finalize(); 20538 } 20539 } 20540 20541 @Override 20542 public void close() { 20543 mCloseGuard.close(); 20544 if (mClosed.compareAndSet(false, true)) { 20545 synchronized (mPackages) { 20546 if (mWeFroze) { 20547 mFrozenPackages.remove(mPackageName); 20548 } 20549 20550 if (mChildren != null) { 20551 for (PackageFreezer freezer : mChildren) { 20552 freezer.close(); 20553 } 20554 } 20555 } 20556 } 20557 } 20558 } 20559 20560 /** 20561 * Verify that given package is currently frozen. 20562 */ 20563 private void checkPackageFrozen(String packageName) { 20564 synchronized (mPackages) { 20565 if (!mFrozenPackages.contains(packageName)) { 20566 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20567 } 20568 } 20569 } 20570 20571 @Override 20572 public int movePackage(final String packageName, final String volumeUuid) { 20573 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20574 20575 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20576 final int moveId = mNextMoveId.getAndIncrement(); 20577 mHandler.post(new Runnable() { 20578 @Override 20579 public void run() { 20580 try { 20581 movePackageInternal(packageName, volumeUuid, moveId, user); 20582 } catch (PackageManagerException e) { 20583 Slog.w(TAG, "Failed to move " + packageName, e); 20584 mMoveCallbacks.notifyStatusChanged(moveId, 20585 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20586 } 20587 } 20588 }); 20589 return moveId; 20590 } 20591 20592 private void movePackageInternal(final String packageName, final String volumeUuid, 20593 final int moveId, UserHandle user) throws PackageManagerException { 20594 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20595 final PackageManager pm = mContext.getPackageManager(); 20596 20597 final boolean currentAsec; 20598 final String currentVolumeUuid; 20599 final File codeFile; 20600 final String installerPackageName; 20601 final String packageAbiOverride; 20602 final int appId; 20603 final String seinfo; 20604 final String label; 20605 final int targetSdkVersion; 20606 final PackageFreezer freezer; 20607 final int[] installedUserIds; 20608 20609 // reader 20610 synchronized (mPackages) { 20611 final PackageParser.Package pkg = mPackages.get(packageName); 20612 final PackageSetting ps = mSettings.mPackages.get(packageName); 20613 if (pkg == null || ps == null) { 20614 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20615 } 20616 20617 if (pkg.applicationInfo.isSystemApp()) { 20618 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20619 "Cannot move system application"); 20620 } 20621 20622 if (pkg.applicationInfo.isExternalAsec()) { 20623 currentAsec = true; 20624 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20625 } else if (pkg.applicationInfo.isForwardLocked()) { 20626 currentAsec = true; 20627 currentVolumeUuid = "forward_locked"; 20628 } else { 20629 currentAsec = false; 20630 currentVolumeUuid = ps.volumeUuid; 20631 20632 final File probe = new File(pkg.codePath); 20633 final File probeOat = new File(probe, "oat"); 20634 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20635 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20636 "Move only supported for modern cluster style installs"); 20637 } 20638 } 20639 20640 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20641 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20642 "Package already moved to " + volumeUuid); 20643 } 20644 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20645 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20646 "Device admin cannot be moved"); 20647 } 20648 20649 if (mFrozenPackages.contains(packageName)) { 20650 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20651 "Failed to move already frozen package"); 20652 } 20653 20654 codeFile = new File(pkg.codePath); 20655 installerPackageName = ps.installerPackageName; 20656 packageAbiOverride = ps.cpuAbiOverrideString; 20657 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20658 seinfo = pkg.applicationInfo.seinfo; 20659 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20660 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20661 freezer = freezePackage(packageName, "movePackageInternal"); 20662 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20663 } 20664 20665 final Bundle extras = new Bundle(); 20666 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20667 extras.putString(Intent.EXTRA_TITLE, label); 20668 mMoveCallbacks.notifyCreated(moveId, extras); 20669 20670 int installFlags; 20671 final boolean moveCompleteApp; 20672 final File measurePath; 20673 20674 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20675 installFlags = INSTALL_INTERNAL; 20676 moveCompleteApp = !currentAsec; 20677 measurePath = Environment.getDataAppDirectory(volumeUuid); 20678 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20679 installFlags = INSTALL_EXTERNAL; 20680 moveCompleteApp = false; 20681 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20682 } else { 20683 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20684 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20685 || !volume.isMountedWritable()) { 20686 freezer.close(); 20687 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20688 "Move location not mounted private volume"); 20689 } 20690 20691 Preconditions.checkState(!currentAsec); 20692 20693 installFlags = INSTALL_INTERNAL; 20694 moveCompleteApp = true; 20695 measurePath = Environment.getDataAppDirectory(volumeUuid); 20696 } 20697 20698 final PackageStats stats = new PackageStats(null, -1); 20699 synchronized (mInstaller) { 20700 for (int userId : installedUserIds) { 20701 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20702 freezer.close(); 20703 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20704 "Failed to measure package size"); 20705 } 20706 } 20707 } 20708 20709 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20710 + stats.dataSize); 20711 20712 final long startFreeBytes = measurePath.getFreeSpace(); 20713 final long sizeBytes; 20714 if (moveCompleteApp) { 20715 sizeBytes = stats.codeSize + stats.dataSize; 20716 } else { 20717 sizeBytes = stats.codeSize; 20718 } 20719 20720 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20721 freezer.close(); 20722 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20723 "Not enough free space to move"); 20724 } 20725 20726 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20727 20728 final CountDownLatch installedLatch = new CountDownLatch(1); 20729 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20730 @Override 20731 public void onUserActionRequired(Intent intent) throws RemoteException { 20732 throw new IllegalStateException(); 20733 } 20734 20735 @Override 20736 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20737 Bundle extras) throws RemoteException { 20738 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20739 + PackageManager.installStatusToString(returnCode, msg)); 20740 20741 installedLatch.countDown(); 20742 freezer.close(); 20743 20744 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20745 switch (status) { 20746 case PackageInstaller.STATUS_SUCCESS: 20747 mMoveCallbacks.notifyStatusChanged(moveId, 20748 PackageManager.MOVE_SUCCEEDED); 20749 break; 20750 case PackageInstaller.STATUS_FAILURE_STORAGE: 20751 mMoveCallbacks.notifyStatusChanged(moveId, 20752 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20753 break; 20754 default: 20755 mMoveCallbacks.notifyStatusChanged(moveId, 20756 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20757 break; 20758 } 20759 } 20760 }; 20761 20762 final MoveInfo move; 20763 if (moveCompleteApp) { 20764 // Kick off a thread to report progress estimates 20765 new Thread() { 20766 @Override 20767 public void run() { 20768 while (true) { 20769 try { 20770 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20771 break; 20772 } 20773 } catch (InterruptedException ignored) { 20774 } 20775 20776 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20777 final int progress = 10 + (int) MathUtils.constrain( 20778 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20779 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20780 } 20781 } 20782 }.start(); 20783 20784 final String dataAppName = codeFile.getName(); 20785 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20786 dataAppName, appId, seinfo, targetSdkVersion); 20787 } else { 20788 move = null; 20789 } 20790 20791 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20792 20793 final Message msg = mHandler.obtainMessage(INIT_COPY); 20794 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20795 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20796 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20797 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20798 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20799 msg.obj = params; 20800 20801 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20802 System.identityHashCode(msg.obj)); 20803 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20804 System.identityHashCode(msg.obj)); 20805 20806 mHandler.sendMessage(msg); 20807 } 20808 20809 @Override 20810 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20811 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20812 20813 final int realMoveId = mNextMoveId.getAndIncrement(); 20814 final Bundle extras = new Bundle(); 20815 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20816 mMoveCallbacks.notifyCreated(realMoveId, extras); 20817 20818 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20819 @Override 20820 public void onCreated(int moveId, Bundle extras) { 20821 // Ignored 20822 } 20823 20824 @Override 20825 public void onStatusChanged(int moveId, int status, long estMillis) { 20826 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20827 } 20828 }; 20829 20830 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20831 storage.setPrimaryStorageUuid(volumeUuid, callback); 20832 return realMoveId; 20833 } 20834 20835 @Override 20836 public int getMoveStatus(int moveId) { 20837 mContext.enforceCallingOrSelfPermission( 20838 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20839 return mMoveCallbacks.mLastStatus.get(moveId); 20840 } 20841 20842 @Override 20843 public void registerMoveCallback(IPackageMoveObserver callback) { 20844 mContext.enforceCallingOrSelfPermission( 20845 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20846 mMoveCallbacks.register(callback); 20847 } 20848 20849 @Override 20850 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20851 mContext.enforceCallingOrSelfPermission( 20852 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20853 mMoveCallbacks.unregister(callback); 20854 } 20855 20856 @Override 20857 public boolean setInstallLocation(int loc) { 20858 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20859 null); 20860 if (getInstallLocation() == loc) { 20861 return true; 20862 } 20863 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20864 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20865 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20866 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20867 return true; 20868 } 20869 return false; 20870 } 20871 20872 @Override 20873 public int getInstallLocation() { 20874 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20875 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20876 PackageHelper.APP_INSTALL_AUTO); 20877 } 20878 20879 /** Called by UserManagerService */ 20880 void cleanUpUser(UserManagerService userManager, int userHandle) { 20881 synchronized (mPackages) { 20882 mDirtyUsers.remove(userHandle); 20883 mUserNeedsBadging.delete(userHandle); 20884 mSettings.removeUserLPw(userHandle); 20885 mPendingBroadcasts.remove(userHandle); 20886 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20887 removeUnusedPackagesLPw(userManager, userHandle); 20888 } 20889 } 20890 20891 /** 20892 * We're removing userHandle and would like to remove any downloaded packages 20893 * that are no longer in use by any other user. 20894 * @param userHandle the user being removed 20895 */ 20896 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20897 final boolean DEBUG_CLEAN_APKS = false; 20898 int [] users = userManager.getUserIds(); 20899 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20900 while (psit.hasNext()) { 20901 PackageSetting ps = psit.next(); 20902 if (ps.pkg == null) { 20903 continue; 20904 } 20905 final String packageName = ps.pkg.packageName; 20906 // Skip over if system app 20907 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20908 continue; 20909 } 20910 if (DEBUG_CLEAN_APKS) { 20911 Slog.i(TAG, "Checking package " + packageName); 20912 } 20913 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20914 if (keep) { 20915 if (DEBUG_CLEAN_APKS) { 20916 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20917 } 20918 } else { 20919 for (int i = 0; i < users.length; i++) { 20920 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20921 keep = true; 20922 if (DEBUG_CLEAN_APKS) { 20923 Slog.i(TAG, " Keeping package " + packageName + " for user " 20924 + users[i]); 20925 } 20926 break; 20927 } 20928 } 20929 } 20930 if (!keep) { 20931 if (DEBUG_CLEAN_APKS) { 20932 Slog.i(TAG, " Removing package " + packageName); 20933 } 20934 mHandler.post(new Runnable() { 20935 public void run() { 20936 deletePackageX(packageName, userHandle, 0); 20937 } //end run 20938 }); 20939 } 20940 } 20941 } 20942 20943 /** Called by UserManagerService */ 20944 void createNewUser(int userId, String[] disallowedPackages) { 20945 synchronized (mInstallLock) { 20946 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 20947 } 20948 synchronized (mPackages) { 20949 scheduleWritePackageRestrictionsLocked(userId); 20950 scheduleWritePackageListLocked(userId); 20951 applyFactoryDefaultBrowserLPw(userId); 20952 primeDomainVerificationsLPw(userId); 20953 } 20954 } 20955 20956 void onNewUserCreated(final int userId) { 20957 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20958 // If permission review for legacy apps is required, we represent 20959 // dagerous permissions for such apps as always granted runtime 20960 // permissions to keep per user flag state whether review is needed. 20961 // Hence, if a new user is added we have to propagate dangerous 20962 // permission grants for these legacy apps. 20963 if (mPermissionReviewRequired) { 20964 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20965 | UPDATE_PERMISSIONS_REPLACE_ALL); 20966 } 20967 } 20968 20969 @Override 20970 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20971 mContext.enforceCallingOrSelfPermission( 20972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20973 "Only package verification agents can read the verifier device identity"); 20974 20975 synchronized (mPackages) { 20976 return mSettings.getVerifierDeviceIdentityLPw(); 20977 } 20978 } 20979 20980 @Override 20981 public void setPermissionEnforced(String permission, boolean enforced) { 20982 // TODO: Now that we no longer change GID for storage, this should to away. 20983 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20984 "setPermissionEnforced"); 20985 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20986 synchronized (mPackages) { 20987 if (mSettings.mReadExternalStorageEnforced == null 20988 || mSettings.mReadExternalStorageEnforced != enforced) { 20989 mSettings.mReadExternalStorageEnforced = enforced; 20990 mSettings.writeLPr(); 20991 } 20992 } 20993 // kill any non-foreground processes so we restart them and 20994 // grant/revoke the GID. 20995 final IActivityManager am = ActivityManager.getService(); 20996 if (am != null) { 20997 final long token = Binder.clearCallingIdentity(); 20998 try { 20999 am.killProcessesBelowForeground("setPermissionEnforcement"); 21000 } catch (RemoteException e) { 21001 } finally { 21002 Binder.restoreCallingIdentity(token); 21003 } 21004 } 21005 } else { 21006 throw new IllegalArgumentException("No selective enforcement for " + permission); 21007 } 21008 } 21009 21010 @Override 21011 @Deprecated 21012 public boolean isPermissionEnforced(String permission) { 21013 return true; 21014 } 21015 21016 @Override 21017 public boolean isStorageLow() { 21018 final long token = Binder.clearCallingIdentity(); 21019 try { 21020 final DeviceStorageMonitorInternal 21021 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 21022 if (dsm != null) { 21023 return dsm.isMemoryLow(); 21024 } else { 21025 return false; 21026 } 21027 } finally { 21028 Binder.restoreCallingIdentity(token); 21029 } 21030 } 21031 21032 @Override 21033 public IPackageInstaller getPackageInstaller() { 21034 return mInstallerService; 21035 } 21036 21037 private boolean userNeedsBadging(int userId) { 21038 int index = mUserNeedsBadging.indexOfKey(userId); 21039 if (index < 0) { 21040 final UserInfo userInfo; 21041 final long token = Binder.clearCallingIdentity(); 21042 try { 21043 userInfo = sUserManager.getUserInfo(userId); 21044 } finally { 21045 Binder.restoreCallingIdentity(token); 21046 } 21047 final boolean b; 21048 if (userInfo != null && userInfo.isManagedProfile()) { 21049 b = true; 21050 } else { 21051 b = false; 21052 } 21053 mUserNeedsBadging.put(userId, b); 21054 return b; 21055 } 21056 return mUserNeedsBadging.valueAt(index); 21057 } 21058 21059 @Override 21060 public KeySet getKeySetByAlias(String packageName, String alias) { 21061 if (packageName == null || alias == null) { 21062 return null; 21063 } 21064 synchronized(mPackages) { 21065 final PackageParser.Package pkg = mPackages.get(packageName); 21066 if (pkg == null) { 21067 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21068 throw new IllegalArgumentException("Unknown package: " + packageName); 21069 } 21070 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21071 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 21072 } 21073 } 21074 21075 @Override 21076 public KeySet getSigningKeySet(String packageName) { 21077 if (packageName == null) { 21078 return null; 21079 } 21080 synchronized(mPackages) { 21081 final PackageParser.Package pkg = mPackages.get(packageName); 21082 if (pkg == null) { 21083 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21084 throw new IllegalArgumentException("Unknown package: " + packageName); 21085 } 21086 if (pkg.applicationInfo.uid != Binder.getCallingUid() 21087 && Process.SYSTEM_UID != Binder.getCallingUid()) { 21088 throw new SecurityException("May not access signing KeySet of other apps."); 21089 } 21090 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21091 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 21092 } 21093 } 21094 21095 @Override 21096 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 21097 if (packageName == null || ks == null) { 21098 return false; 21099 } 21100 synchronized(mPackages) { 21101 final PackageParser.Package pkg = mPackages.get(packageName); 21102 if (pkg == null) { 21103 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21104 throw new IllegalArgumentException("Unknown package: " + packageName); 21105 } 21106 IBinder ksh = ks.getToken(); 21107 if (ksh instanceof KeySetHandle) { 21108 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21109 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 21110 } 21111 return false; 21112 } 21113 } 21114 21115 @Override 21116 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 21117 if (packageName == null || ks == null) { 21118 return false; 21119 } 21120 synchronized(mPackages) { 21121 final PackageParser.Package pkg = mPackages.get(packageName); 21122 if (pkg == null) { 21123 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 21124 throw new IllegalArgumentException("Unknown package: " + packageName); 21125 } 21126 IBinder ksh = ks.getToken(); 21127 if (ksh instanceof KeySetHandle) { 21128 KeySetManagerService ksms = mSettings.mKeySetManagerService; 21129 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 21130 } 21131 return false; 21132 } 21133 } 21134 21135 private void deletePackageIfUnusedLPr(final String packageName) { 21136 PackageSetting ps = mSettings.mPackages.get(packageName); 21137 if (ps == null) { 21138 return; 21139 } 21140 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 21141 // TODO Implement atomic delete if package is unused 21142 // It is currently possible that the package will be deleted even if it is installed 21143 // after this method returns. 21144 mHandler.post(new Runnable() { 21145 public void run() { 21146 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 21147 } 21148 }); 21149 } 21150 } 21151 21152 /** 21153 * Check and throw if the given before/after packages would be considered a 21154 * downgrade. 21155 */ 21156 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 21157 throws PackageManagerException { 21158 if (after.versionCode < before.mVersionCode) { 21159 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21160 "Update version code " + after.versionCode + " is older than current " 21161 + before.mVersionCode); 21162 } else if (after.versionCode == before.mVersionCode) { 21163 if (after.baseRevisionCode < before.baseRevisionCode) { 21164 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21165 "Update base revision code " + after.baseRevisionCode 21166 + " is older than current " + before.baseRevisionCode); 21167 } 21168 21169 if (!ArrayUtils.isEmpty(after.splitNames)) { 21170 for (int i = 0; i < after.splitNames.length; i++) { 21171 final String splitName = after.splitNames[i]; 21172 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 21173 if (j != -1) { 21174 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 21175 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 21176 "Update split " + splitName + " revision code " 21177 + after.splitRevisionCodes[i] + " is older than current " 21178 + before.splitRevisionCodes[j]); 21179 } 21180 } 21181 } 21182 } 21183 } 21184 } 21185 21186 private static class MoveCallbacks extends Handler { 21187 private static final int MSG_CREATED = 1; 21188 private static final int MSG_STATUS_CHANGED = 2; 21189 21190 private final RemoteCallbackList<IPackageMoveObserver> 21191 mCallbacks = new RemoteCallbackList<>(); 21192 21193 private final SparseIntArray mLastStatus = new SparseIntArray(); 21194 21195 public MoveCallbacks(Looper looper) { 21196 super(looper); 21197 } 21198 21199 public void register(IPackageMoveObserver callback) { 21200 mCallbacks.register(callback); 21201 } 21202 21203 public void unregister(IPackageMoveObserver callback) { 21204 mCallbacks.unregister(callback); 21205 } 21206 21207 @Override 21208 public void handleMessage(Message msg) { 21209 final SomeArgs args = (SomeArgs) msg.obj; 21210 final int n = mCallbacks.beginBroadcast(); 21211 for (int i = 0; i < n; i++) { 21212 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 21213 try { 21214 invokeCallback(callback, msg.what, args); 21215 } catch (RemoteException ignored) { 21216 } 21217 } 21218 mCallbacks.finishBroadcast(); 21219 args.recycle(); 21220 } 21221 21222 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 21223 throws RemoteException { 21224 switch (what) { 21225 case MSG_CREATED: { 21226 callback.onCreated(args.argi1, (Bundle) args.arg2); 21227 break; 21228 } 21229 case MSG_STATUS_CHANGED: { 21230 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 21231 break; 21232 } 21233 } 21234 } 21235 21236 private void notifyCreated(int moveId, Bundle extras) { 21237 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 21238 21239 final SomeArgs args = SomeArgs.obtain(); 21240 args.argi1 = moveId; 21241 args.arg2 = extras; 21242 obtainMessage(MSG_CREATED, args).sendToTarget(); 21243 } 21244 21245 private void notifyStatusChanged(int moveId, int status) { 21246 notifyStatusChanged(moveId, status, -1); 21247 } 21248 21249 private void notifyStatusChanged(int moveId, int status, long estMillis) { 21250 Slog.v(TAG, "Move " + moveId + " status " + status); 21251 21252 final SomeArgs args = SomeArgs.obtain(); 21253 args.argi1 = moveId; 21254 args.argi2 = status; 21255 args.arg3 = estMillis; 21256 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 21257 21258 synchronized (mLastStatus) { 21259 mLastStatus.put(moveId, status); 21260 } 21261 } 21262 } 21263 21264 private final static class OnPermissionChangeListeners extends Handler { 21265 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 21266 21267 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 21268 new RemoteCallbackList<>(); 21269 21270 public OnPermissionChangeListeners(Looper looper) { 21271 super(looper); 21272 } 21273 21274 @Override 21275 public void handleMessage(Message msg) { 21276 switch (msg.what) { 21277 case MSG_ON_PERMISSIONS_CHANGED: { 21278 final int uid = msg.arg1; 21279 handleOnPermissionsChanged(uid); 21280 } break; 21281 } 21282 } 21283 21284 public void addListenerLocked(IOnPermissionsChangeListener listener) { 21285 mPermissionListeners.register(listener); 21286 21287 } 21288 21289 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 21290 mPermissionListeners.unregister(listener); 21291 } 21292 21293 public void onPermissionsChanged(int uid) { 21294 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 21295 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 21296 } 21297 } 21298 21299 private void handleOnPermissionsChanged(int uid) { 21300 final int count = mPermissionListeners.beginBroadcast(); 21301 try { 21302 for (int i = 0; i < count; i++) { 21303 IOnPermissionsChangeListener callback = mPermissionListeners 21304 .getBroadcastItem(i); 21305 try { 21306 callback.onPermissionsChanged(uid); 21307 } catch (RemoteException e) { 21308 Log.e(TAG, "Permission listener is dead", e); 21309 } 21310 } 21311 } finally { 21312 mPermissionListeners.finishBroadcast(); 21313 } 21314 } 21315 } 21316 21317 private class PackageManagerInternalImpl extends PackageManagerInternal { 21318 @Override 21319 public void setLocationPackagesProvider(PackagesProvider provider) { 21320 synchronized (mPackages) { 21321 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 21322 } 21323 } 21324 21325 @Override 21326 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 21327 synchronized (mPackages) { 21328 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 21329 } 21330 } 21331 21332 @Override 21333 public void setSmsAppPackagesProvider(PackagesProvider provider) { 21334 synchronized (mPackages) { 21335 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 21336 } 21337 } 21338 21339 @Override 21340 public void setDialerAppPackagesProvider(PackagesProvider provider) { 21341 synchronized (mPackages) { 21342 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 21343 } 21344 } 21345 21346 @Override 21347 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 21348 synchronized (mPackages) { 21349 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 21350 } 21351 } 21352 21353 @Override 21354 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 21355 synchronized (mPackages) { 21356 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 21357 } 21358 } 21359 21360 @Override 21361 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 21362 synchronized (mPackages) { 21363 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 21364 packageName, userId); 21365 } 21366 } 21367 21368 @Override 21369 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 21370 synchronized (mPackages) { 21371 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 21372 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 21373 packageName, userId); 21374 } 21375 } 21376 21377 @Override 21378 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 21379 synchronized (mPackages) { 21380 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 21381 packageName, userId); 21382 } 21383 } 21384 21385 @Override 21386 public void setKeepUninstalledPackages(final List<String> packageList) { 21387 Preconditions.checkNotNull(packageList); 21388 List<String> removedFromList = null; 21389 synchronized (mPackages) { 21390 if (mKeepUninstalledPackages != null) { 21391 final int packagesCount = mKeepUninstalledPackages.size(); 21392 for (int i = 0; i < packagesCount; i++) { 21393 String oldPackage = mKeepUninstalledPackages.get(i); 21394 if (packageList != null && packageList.contains(oldPackage)) { 21395 continue; 21396 } 21397 if (removedFromList == null) { 21398 removedFromList = new ArrayList<>(); 21399 } 21400 removedFromList.add(oldPackage); 21401 } 21402 } 21403 mKeepUninstalledPackages = new ArrayList<>(packageList); 21404 if (removedFromList != null) { 21405 final int removedCount = removedFromList.size(); 21406 for (int i = 0; i < removedCount; i++) { 21407 deletePackageIfUnusedLPr(removedFromList.get(i)); 21408 } 21409 } 21410 } 21411 } 21412 21413 @Override 21414 public boolean isPermissionsReviewRequired(String packageName, int userId) { 21415 synchronized (mPackages) { 21416 // If we do not support permission review, done. 21417 if (!mPermissionReviewRequired) { 21418 return false; 21419 } 21420 21421 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 21422 if (packageSetting == null) { 21423 return false; 21424 } 21425 21426 // Permission review applies only to apps not supporting the new permission model. 21427 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 21428 return false; 21429 } 21430 21431 // Legacy apps have the permission and get user consent on launch. 21432 PermissionsState permissionsState = packageSetting.getPermissionsState(); 21433 return permissionsState.isPermissionReviewRequired(userId); 21434 } 21435 } 21436 21437 @Override 21438 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 21439 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 21440 } 21441 21442 @Override 21443 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 21444 int userId) { 21445 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 21446 } 21447 21448 @Override 21449 public void setDeviceAndProfileOwnerPackages( 21450 int deviceOwnerUserId, String deviceOwnerPackage, 21451 SparseArray<String> profileOwnerPackages) { 21452 mProtectedPackages.setDeviceAndProfileOwnerPackages( 21453 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 21454 } 21455 21456 @Override 21457 public boolean isPackageDataProtected(int userId, String packageName) { 21458 return mProtectedPackages.isPackageDataProtected(userId, packageName); 21459 } 21460 21461 @Override 21462 public boolean isPackageEphemeral(int userId, String packageName) { 21463 synchronized (mPackages) { 21464 PackageParser.Package p = mPackages.get(packageName); 21465 return p != null ? p.applicationInfo.isEphemeralApp() : false; 21466 } 21467 } 21468 21469 @Override 21470 public boolean wasPackageEverLaunched(String packageName, int userId) { 21471 synchronized (mPackages) { 21472 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 21473 } 21474 } 21475 21476 @Override 21477 public void grantRuntimePermission(String packageName, String name, int userId, 21478 boolean overridePolicy) { 21479 PackageManagerService.this.grantRuntimePermission(packageName, name, userId, 21480 overridePolicy); 21481 } 21482 21483 @Override 21484 public void revokeRuntimePermission(String packageName, String name, int userId, 21485 boolean overridePolicy) { 21486 PackageManagerService.this.revokeRuntimePermission(packageName, name, userId, 21487 overridePolicy); 21488 } 21489 21490 @Override 21491 public String getNameForUid(int uid) { 21492 return PackageManagerService.this.getNameForUid(uid); 21493 } 21494 21495 @Override 21496 public void requestEphemeralResolutionPhaseTwo(EphemeralResponse responseObj, 21497 Intent origIntent, String resolvedType, Intent launchIntent, 21498 String callingPackage, int userId) { 21499 PackageManagerService.this.requestEphemeralResolutionPhaseTwo( 21500 responseObj, origIntent, resolvedType, launchIntent, callingPackage, userId); 21501 } 21502 } 21503 21504 @Override 21505 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 21506 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 21507 synchronized (mPackages) { 21508 final long identity = Binder.clearCallingIdentity(); 21509 try { 21510 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 21511 packageNames, userId); 21512 } finally { 21513 Binder.restoreCallingIdentity(identity); 21514 } 21515 } 21516 } 21517 21518 private static void enforceSystemOrPhoneCaller(String tag) { 21519 int callingUid = Binder.getCallingUid(); 21520 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 21521 throw new SecurityException( 21522 "Cannot call " + tag + " from UID " + callingUid); 21523 } 21524 } 21525 21526 boolean isHistoricalPackageUsageAvailable() { 21527 return mPackageUsage.isHistoricalPackageUsageAvailable(); 21528 } 21529 21530 /** 21531 * Return a <b>copy</b> of the collection of packages known to the package manager. 21532 * @return A copy of the values of mPackages. 21533 */ 21534 Collection<PackageParser.Package> getPackages() { 21535 synchronized (mPackages) { 21536 return new ArrayList<>(mPackages.values()); 21537 } 21538 } 21539 21540 /** 21541 * Logs process start information (including base APK hash) to the security log. 21542 * @hide 21543 */ 21544 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 21545 String apkFile, int pid) { 21546 if (!SecurityLog.isLoggingEnabled()) { 21547 return; 21548 } 21549 Bundle data = new Bundle(); 21550 data.putLong("startTimestamp", System.currentTimeMillis()); 21551 data.putString("processName", processName); 21552 data.putInt("uid", uid); 21553 data.putString("seinfo", seinfo); 21554 data.putString("apkFile", apkFile); 21555 data.putInt("pid", pid); 21556 Message msg = mProcessLoggingHandler.obtainMessage( 21557 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 21558 msg.setData(data); 21559 mProcessLoggingHandler.sendMessage(msg); 21560 } 21561 21562 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 21563 return mCompilerStats.getPackageStats(pkgName); 21564 } 21565 21566 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 21567 return getOrCreateCompilerPackageStats(pkg.packageName); 21568 } 21569 21570 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 21571 return mCompilerStats.getOrCreatePackageStats(pkgName); 21572 } 21573 21574 public void deleteCompilerPackageStats(String pkgName) { 21575 mCompilerStats.deletePackageStats(pkgName); 21576 } 21577} 21578