PackageManagerService.java revision 24b9d960071ecf24f1b7edf799f6a4edf20f2b95
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_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 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_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 80import static android.system.OsConstants.O_CREAT; 81import static android.system.OsConstants.O_RDWR; 82 83import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 84import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 85import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 86import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 87import static com.android.internal.util.ArrayUtils.appendInt; 88import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 89import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 90import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 91import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 92import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 93import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 94import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 95import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getNonProfileGuidedCompilerFilter; 97import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 100 101import android.Manifest; 102import android.annotation.NonNull; 103import android.annotation.Nullable; 104import android.annotation.UserIdInt; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.ResourcesManager; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralDigest; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.provider.Settings.Global; 201import android.security.KeyStore; 202import android.security.SystemKeyStore; 203import android.system.ErrnoException; 204import android.system.Os; 205import android.text.TextUtils; 206import android.text.format.DateUtils; 207import android.util.ArrayMap; 208import android.util.ArraySet; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305 306/** 307 * Keep track of all those APKs everywhere. 308 * <p> 309 * Internally there are two important locks: 310 * <ul> 311 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 312 * and other related state. It is a fine-grained lock that should only be held 313 * momentarily, as it's one of the most contended locks in the system. 314 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 315 * operations typically involve heavy lifting of application data on disk. Since 316 * {@code installd} is single-threaded, and it's operations can often be slow, 317 * this lock should never be acquired while already holding {@link #mPackages}. 318 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 319 * holding {@link #mInstallLock}. 320 * </ul> 321 * Many internal methods rely on the caller to hold the appropriate locks, and 322 * this contract is expressed through method name suffixes: 323 * <ul> 324 * <li>fooLI(): the caller must hold {@link #mInstallLock} 325 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 326 * being modified must be frozen 327 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 328 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 329 * </ul> 330 * <p> 331 * Because this class is very central to the platform's security; please run all 332 * CTS and unit tests whenever making modifications: 333 * 334 * <pre> 335 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 336 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 337 * </pre> 338 */ 339public class PackageManagerService extends IPackageManager.Stub { 340 static final String TAG = "PackageManager"; 341 static final boolean DEBUG_SETTINGS = false; 342 static final boolean DEBUG_PREFERRED = false; 343 static final boolean DEBUG_UPGRADE = false; 344 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 345 private static final boolean DEBUG_BACKUP = false; 346 private static final boolean DEBUG_INSTALL = false; 347 private static final boolean DEBUG_REMOVE = false; 348 private static final boolean DEBUG_BROADCASTS = false; 349 private static final boolean DEBUG_SHOW_INFO = false; 350 private static final boolean DEBUG_PACKAGE_INFO = false; 351 private static final boolean DEBUG_INTENT_MATCHING = false; 352 private static final boolean DEBUG_PACKAGE_SCANNING = false; 353 private static final boolean DEBUG_VERIFY = false; 354 private static final boolean DEBUG_FILTERS = false; 355 356 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 357 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 358 // user, but by default initialize to this. 359 static final boolean DEBUG_DEXOPT = false; 360 361 private static final boolean DEBUG_ABI_SELECTION = false; 362 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 363 private static final boolean DEBUG_TRIAGED_MISSING = false; 364 private static final boolean DEBUG_APP_DATA = false; 365 366 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 367 368 private static final boolean DISABLE_EPHEMERAL_APPS = !Build.IS_DEBUGGABLE; 369 370 private static final int RADIO_UID = Process.PHONE_UID; 371 private static final int LOG_UID = Process.LOG_UID; 372 private static final int NFC_UID = Process.NFC_UID; 373 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 374 private static final int SHELL_UID = Process.SHELL_UID; 375 376 // Cap the size of permission trees that 3rd party apps can define 377 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 378 379 // Suffix used during package installation when copying/moving 380 // package apks to install directory. 381 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 382 383 static final int SCAN_NO_DEX = 1<<1; 384 static final int SCAN_FORCE_DEX = 1<<2; 385 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 386 static final int SCAN_NEW_INSTALL = 1<<4; 387 static final int SCAN_NO_PATHS = 1<<5; 388 static final int SCAN_UPDATE_TIME = 1<<6; 389 static final int SCAN_DEFER_DEX = 1<<7; 390 static final int SCAN_BOOTING = 1<<8; 391 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 392 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 393 static final int SCAN_REPLACING = 1<<11; 394 static final int SCAN_REQUIRE_KNOWN = 1<<12; 395 static final int SCAN_MOVE = 1<<13; 396 static final int SCAN_INITIAL = 1<<14; 397 static final int SCAN_CHECK_ONLY = 1<<15; 398 static final int SCAN_DONT_KILL_APP = 1<<17; 399 static final int SCAN_IGNORE_FROZEN = 1<<18; 400 401 static final int REMOVE_CHATTY = 1<<16; 402 403 private static final int[] EMPTY_INT_ARRAY = new int[0]; 404 405 /** 406 * Timeout (in milliseconds) after which the watchdog should declare that 407 * our handler thread is wedged. The usual default for such things is one 408 * minute but we sometimes do very lengthy I/O operations on this thread, 409 * such as installing multi-gigabyte applications, so ours needs to be longer. 410 */ 411 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 412 413 /** 414 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 415 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 416 * settings entry if available, otherwise we use the hardcoded default. If it's been 417 * more than this long since the last fstrim, we force one during the boot sequence. 418 * 419 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 420 * one gets run at the next available charging+idle time. This final mandatory 421 * no-fstrim check kicks in only of the other scheduling criteria is never met. 422 */ 423 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 424 425 /** 426 * Whether verification is enabled by default. 427 */ 428 private static final boolean DEFAULT_VERIFY_ENABLE = true; 429 430 /** 431 * The default maximum time to wait for the verification agent to return in 432 * milliseconds. 433 */ 434 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 435 436 /** 437 * The default response for package verification timeout. 438 * 439 * This can be either PackageManager.VERIFICATION_ALLOW or 440 * PackageManager.VERIFICATION_REJECT. 441 */ 442 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 443 444 static final String PLATFORM_PACKAGE_NAME = "android"; 445 446 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 447 448 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 449 DEFAULT_CONTAINER_PACKAGE, 450 "com.android.defcontainer.DefaultContainerService"); 451 452 private static final String KILL_APP_REASON_GIDS_CHANGED = 453 "permission grant or revoke changed gids"; 454 455 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 456 "permissions revoked"; 457 458 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 459 460 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 461 462 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_MASK = 0xFFFFF000; 463 private static int DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT = 5; 464 465 /** Permission grant: not grant the permission. */ 466 private static final int GRANT_DENIED = 1; 467 468 /** Permission grant: grant the permission as an install permission. */ 469 private static final int GRANT_INSTALL = 2; 470 471 /** Permission grant: grant the permission as a runtime one. */ 472 private static final int GRANT_RUNTIME = 3; 473 474 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 475 private static final int GRANT_UPGRADE = 4; 476 477 /** Canonical intent used to identify what counts as a "web browser" app */ 478 private static final Intent sBrowserIntent; 479 static { 480 sBrowserIntent = new Intent(); 481 sBrowserIntent.setAction(Intent.ACTION_VIEW); 482 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 483 sBrowserIntent.setData(Uri.parse("http:")); 484 } 485 486 /** 487 * The set of all protected actions [i.e. those actions for which a high priority 488 * intent filter is disallowed]. 489 */ 490 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 491 static { 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 495 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 496 } 497 498 // Compilation reasons. 499 public static final int REASON_FIRST_BOOT = 0; 500 public static final int REASON_BOOT = 1; 501 public static final int REASON_INSTALL = 2; 502 public static final int REASON_BACKGROUND_DEXOPT = 3; 503 public static final int REASON_AB_OTA = 4; 504 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 505 public static final int REASON_SHARED_APK = 6; 506 public static final int REASON_FORCED_DEXOPT = 7; 507 public static final int REASON_CORE_APP = 8; 508 509 public static final int REASON_LAST = REASON_CORE_APP; 510 511 /** Special library name that skips shared libraries check during compilation. */ 512 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 513 514 final ServiceThread mHandlerThread; 515 516 final PackageHandler mHandler; 517 518 private final ProcessLoggingHandler mProcessLoggingHandler; 519 520 /** 521 * Messages for {@link #mHandler} that need to wait for system ready before 522 * being dispatched. 523 */ 524 private ArrayList<Message> mPostSystemReadyMessages; 525 526 final int mSdkVersion = Build.VERSION.SDK_INT; 527 528 final Context mContext; 529 final boolean mFactoryTest; 530 final boolean mOnlyCore; 531 final DisplayMetrics mMetrics; 532 final int mDefParseFlags; 533 final String[] mSeparateProcesses; 534 final boolean mIsUpgrade; 535 final boolean mIsPreNUpgrade; 536 537 /** The location for ASEC container files on internal storage. */ 538 final String mAsecInternalPath; 539 540 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 541 // LOCK HELD. Can be called with mInstallLock held. 542 @GuardedBy("mInstallLock") 543 final Installer mInstaller; 544 545 /** Directory where installed third-party apps stored */ 546 final File mAppInstallDir; 547 final File mEphemeralInstallDir; 548 549 /** 550 * Directory to which applications installed internally have their 551 * 32 bit native libraries copied. 552 */ 553 private File mAppLib32InstallDir; 554 555 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 556 // apps. 557 final File mDrmAppPrivateInstallDir; 558 559 // ---------------------------------------------------------------- 560 561 // Lock for state used when installing and doing other long running 562 // operations. Methods that must be called with this lock held have 563 // the suffix "LI". 564 final Object mInstallLock = new Object(); 565 566 // ---------------------------------------------------------------- 567 568 // Keys are String (package name), values are Package. This also serves 569 // as the lock for the global state. Methods that must be called with 570 // this lock held have the prefix "LP". 571 @GuardedBy("mPackages") 572 final ArrayMap<String, PackageParser.Package> mPackages = 573 new ArrayMap<String, PackageParser.Package>(); 574 575 final ArrayMap<String, Set<String>> mKnownCodebase = 576 new ArrayMap<String, Set<String>>(); 577 578 // Tracks available target package names -> overlay package paths. 579 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 580 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 581 582 /** 583 * Tracks new system packages [received in an OTA] that we expect to 584 * find updated user-installed versions. Keys are package name, values 585 * are package location. 586 */ 587 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 588 /** 589 * Tracks high priority intent filters for protected actions. During boot, certain 590 * filter actions are protected and should never be allowed to have a high priority 591 * intent filter for them. However, there is one, and only one exception -- the 592 * setup wizard. It must be able to define a high priority intent filter for these 593 * actions to ensure there are no escapes from the wizard. We need to delay processing 594 * of these during boot as we need to look at all of the system packages in order 595 * to know which component is the setup wizard. 596 */ 597 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 598 /** 599 * Whether or not processing protected filters should be deferred. 600 */ 601 private boolean mDeferProtectedFilters = true; 602 603 /** 604 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 605 */ 606 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 607 /** 608 * Whether or not system app permissions should be promoted from install to runtime. 609 */ 610 boolean mPromoteSystemApps; 611 612 @GuardedBy("mPackages") 613 final Settings mSettings; 614 615 /** 616 * Set of package names that are currently "frozen", which means active 617 * surgery is being done on the code/data for that package. The platform 618 * will refuse to launch frozen packages to avoid race conditions. 619 * 620 * @see PackageFreezer 621 */ 622 @GuardedBy("mPackages") 623 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 624 625 final ProtectedPackages mProtectedPackages; 626 627 boolean mFirstBoot; 628 629 // System configuration read by SystemConfig. 630 final int[] mGlobalGids; 631 final SparseArray<ArraySet<String>> mSystemPermissions; 632 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 633 634 // If mac_permissions.xml was found for seinfo labeling. 635 boolean mFoundPolicyFile; 636 637 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 638 639 public static final class SharedLibraryEntry { 640 public final String path; 641 public final String apk; 642 643 SharedLibraryEntry(String _path, String _apk) { 644 path = _path; 645 apk = _apk; 646 } 647 } 648 649 // Currently known shared libraries. 650 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 651 new ArrayMap<String, SharedLibraryEntry>(); 652 653 // All available activities, for your resolving pleasure. 654 final ActivityIntentResolver mActivities = 655 new ActivityIntentResolver(); 656 657 // All available receivers, for your resolving pleasure. 658 final ActivityIntentResolver mReceivers = 659 new ActivityIntentResolver(); 660 661 // All available services, for your resolving pleasure. 662 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 663 664 // All available providers, for your resolving pleasure. 665 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 666 667 // Mapping from provider base names (first directory in content URI codePath) 668 // to the provider information. 669 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 670 new ArrayMap<String, PackageParser.Provider>(); 671 672 // Mapping from instrumentation class names to info about them. 673 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 674 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 675 676 // Mapping from permission names to info about them. 677 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 678 new ArrayMap<String, PackageParser.PermissionGroup>(); 679 680 // Packages whose data we have transfered into another package, thus 681 // should no longer exist. 682 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 683 684 // Broadcast actions that are only available to the system. 685 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 686 687 /** List of packages waiting for verification. */ 688 final SparseArray<PackageVerificationState> mPendingVerification 689 = new SparseArray<PackageVerificationState>(); 690 691 /** Set of packages associated with each app op permission. */ 692 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 693 694 final PackageInstallerService mInstallerService; 695 696 private final PackageDexOptimizer mPackageDexOptimizer; 697 698 private AtomicInteger mNextMoveId = new AtomicInteger(); 699 private final MoveCallbacks mMoveCallbacks; 700 701 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 702 703 // Cache of users who need badging. 704 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 705 706 /** Token for keys in mPendingVerification. */ 707 private int mPendingVerificationToken = 0; 708 709 volatile boolean mSystemReady; 710 volatile boolean mSafeMode; 711 volatile boolean mHasSystemUidErrors; 712 713 ApplicationInfo mAndroidApplication; 714 final ActivityInfo mResolveActivity = new ActivityInfo(); 715 final ResolveInfo mResolveInfo = new ResolveInfo(); 716 ComponentName mResolveComponentName; 717 PackageParser.Package mPlatformPackage; 718 ComponentName mCustomResolverComponentName; 719 720 boolean mResolverReplaced = false; 721 722 private final @Nullable ComponentName mIntentFilterVerifierComponent; 723 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 724 725 private int mIntentFilterVerificationToken = 0; 726 727 /** Component that knows whether or not an ephemeral application exists */ 728 final ComponentName mEphemeralResolverComponent; 729 /** The service connection to the ephemeral resolver */ 730 final EphemeralResolverConnection mEphemeralResolverConnection; 731 732 /** Component used to install ephemeral applications */ 733 final ComponentName mEphemeralInstallerComponent; 734 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 735 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 736 737 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 738 = new SparseArray<IntentFilterVerificationState>(); 739 740 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 741 new DefaultPermissionGrantPolicy(this); 742 743 // List of packages names to keep cached, even if they are uninstalled for all users 744 private List<String> mKeepUninstalledPackages; 745 746 private UserManagerInternal mUserManagerInternal; 747 748 private static class IFVerificationParams { 749 PackageParser.Package pkg; 750 boolean replacing; 751 int userId; 752 int verifierUid; 753 754 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 755 int _userId, int _verifierUid) { 756 pkg = _pkg; 757 replacing = _replacing; 758 userId = _userId; 759 replacing = _replacing; 760 verifierUid = _verifierUid; 761 } 762 } 763 764 private interface IntentFilterVerifier<T extends IntentFilter> { 765 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 766 T filter, String packageName); 767 void startVerifications(int userId); 768 void receiveVerificationResponse(int verificationId); 769 } 770 771 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 772 private Context mContext; 773 private ComponentName mIntentFilterVerifierComponent; 774 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 775 776 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 777 mContext = context; 778 mIntentFilterVerifierComponent = verifierComponent; 779 } 780 781 private String getDefaultScheme() { 782 return IntentFilter.SCHEME_HTTPS; 783 } 784 785 @Override 786 public void startVerifications(int userId) { 787 // Launch verifications requests 788 int count = mCurrentIntentFilterVerifications.size(); 789 for (int n=0; n<count; n++) { 790 int verificationId = mCurrentIntentFilterVerifications.get(n); 791 final IntentFilterVerificationState ivs = 792 mIntentFilterVerificationStates.get(verificationId); 793 794 String packageName = ivs.getPackageName(); 795 796 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 797 final int filterCount = filters.size(); 798 ArraySet<String> domainsSet = new ArraySet<>(); 799 for (int m=0; m<filterCount; m++) { 800 PackageParser.ActivityIntentInfo filter = filters.get(m); 801 domainsSet.addAll(filter.getHostsList()); 802 } 803 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 804 synchronized (mPackages) { 805 if (mSettings.createIntentFilterVerificationIfNeededLPw( 806 packageName, domainsList) != null) { 807 scheduleWriteSettingsLocked(); 808 } 809 } 810 sendVerificationRequest(userId, verificationId, ivs); 811 } 812 mCurrentIntentFilterVerifications.clear(); 813 } 814 815 private void sendVerificationRequest(int userId, int verificationId, 816 IntentFilterVerificationState ivs) { 817 818 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 821 verificationId); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 824 getDefaultScheme()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 827 ivs.getHostsString()); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 830 ivs.getPackageName()); 831 verificationIntent.setComponent(mIntentFilterVerifierComponent); 832 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 833 834 UserHandle user = new UserHandle(userId); 835 mContext.sendBroadcastAsUser(verificationIntent, user); 836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 837 "Sending IntentFilter verification broadcast"); 838 } 839 840 public void receiveVerificationResponse(int verificationId) { 841 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 842 843 final boolean verified = ivs.isVerified(); 844 845 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 846 final int count = filters.size(); 847 if (DEBUG_DOMAIN_VERIFICATION) { 848 Slog.i(TAG, "Received verification response " + verificationId 849 + " for " + count + " filters, verified=" + verified); 850 } 851 for (int n=0; n<count; n++) { 852 PackageParser.ActivityIntentInfo filter = filters.get(n); 853 filter.setVerified(verified); 854 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 856 + " verified with result:" + verified + " and hosts:" 857 + ivs.getHostsString()); 858 } 859 860 mIntentFilterVerificationStates.remove(verificationId); 861 862 final String packageName = ivs.getPackageName(); 863 IntentFilterVerificationInfo ivi = null; 864 865 synchronized (mPackages) { 866 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 867 } 868 if (ivi == null) { 869 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 870 + verificationId + " packageName:" + packageName); 871 return; 872 } 873 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 874 "Updating IntentFilterVerificationInfo for package " + packageName 875 +" verificationId:" + verificationId); 876 877 synchronized (mPackages) { 878 if (verified) { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 880 } else { 881 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 882 } 883 scheduleWriteSettingsLocked(); 884 885 final int userId = ivs.getUserId(); 886 if (userId != UserHandle.USER_ALL) { 887 final int userStatus = 888 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 889 890 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 891 boolean needUpdate = false; 892 893 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 894 // already been set by the User thru the Disambiguation dialog 895 switch (userStatus) { 896 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 897 if (verified) { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 899 } else { 900 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 901 } 902 needUpdate = true; 903 break; 904 905 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 906 if (verified) { 907 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 908 needUpdate = true; 909 } 910 break; 911 912 default: 913 // Nothing to do 914 } 915 916 if (needUpdate) { 917 mSettings.updateIntentFilterVerificationStatusLPw( 918 packageName, updatedStatus, userId); 919 scheduleWritePackageRestrictionsLocked(userId); 920 } 921 } 922 } 923 } 924 925 @Override 926 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 927 ActivityIntentInfo filter, String packageName) { 928 if (!hasValidDomains(filter)) { 929 return false; 930 } 931 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 932 if (ivs == null) { 933 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 934 packageName); 935 } 936 if (DEBUG_DOMAIN_VERIFICATION) { 937 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 938 } 939 ivs.addFilter(filter); 940 return true; 941 } 942 943 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 944 int userId, int verificationId, String packageName) { 945 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 946 verifierUid, userId, packageName); 947 ivs.setPendingState(); 948 synchronized (mPackages) { 949 mIntentFilterVerificationStates.append(verificationId, ivs); 950 mCurrentIntentFilterVerifications.add(verificationId); 951 } 952 return ivs; 953 } 954 } 955 956 private static boolean hasValidDomains(ActivityIntentInfo filter) { 957 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 958 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 959 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 960 } 961 962 // Set of pending broadcasts for aggregating enable/disable of components. 963 static class PendingPackageBroadcasts { 964 // for each user id, a map of <package name -> components within that package> 965 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 966 967 public PendingPackageBroadcasts() { 968 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 969 } 970 971 public ArrayList<String> get(int userId, String packageName) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 return packages.get(packageName); 974 } 975 976 public void put(int userId, String packageName, ArrayList<String> components) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 packages.put(packageName, components); 979 } 980 981 public void remove(int userId, String packageName) { 982 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 983 if (packages != null) { 984 packages.remove(packageName); 985 } 986 } 987 988 public void remove(int userId) { 989 mUidMap.remove(userId); 990 } 991 992 public int userIdCount() { 993 return mUidMap.size(); 994 } 995 996 public int userIdAt(int n) { 997 return mUidMap.keyAt(n); 998 } 999 1000 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1001 return mUidMap.get(userId); 1002 } 1003 1004 public int size() { 1005 // total number of pending broadcast entries across all userIds 1006 int num = 0; 1007 for (int i = 0; i< mUidMap.size(); i++) { 1008 num += mUidMap.valueAt(i).size(); 1009 } 1010 return num; 1011 } 1012 1013 public void clear() { 1014 mUidMap.clear(); 1015 } 1016 1017 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1018 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1019 if (map == null) { 1020 map = new ArrayMap<String, ArrayList<String>>(); 1021 mUidMap.put(userId, map); 1022 } 1023 return map; 1024 } 1025 } 1026 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1027 1028 // Service Connection to remote media container service to copy 1029 // package uri's from external media onto secure containers 1030 // or internal storage. 1031 private IMediaContainerService mContainerService = null; 1032 1033 static final int SEND_PENDING_BROADCAST = 1; 1034 static final int MCS_BOUND = 3; 1035 static final int END_COPY = 4; 1036 static final int INIT_COPY = 5; 1037 static final int MCS_UNBIND = 6; 1038 static final int START_CLEANING_PACKAGE = 7; 1039 static final int FIND_INSTALL_LOC = 8; 1040 static final int POST_INSTALL = 9; 1041 static final int MCS_RECONNECT = 10; 1042 static final int MCS_GIVE_UP = 11; 1043 static final int UPDATED_MEDIA_STATUS = 12; 1044 static final int WRITE_SETTINGS = 13; 1045 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1046 static final int PACKAGE_VERIFIED = 15; 1047 static final int CHECK_PENDING_VERIFICATION = 16; 1048 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1049 static final int INTENT_FILTER_VERIFIED = 18; 1050 static final int WRITE_PACKAGE_LIST = 19; 1051 1052 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1053 1054 // Delay time in millisecs 1055 static final int BROADCAST_DELAY = 10 * 1000; 1056 1057 static UserManagerService sUserManager; 1058 1059 // Stores a list of users whose package restrictions file needs to be updated 1060 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1061 1062 final private DefaultContainerConnection mDefContainerConn = 1063 new DefaultContainerConnection(); 1064 class DefaultContainerConnection implements ServiceConnection { 1065 public void onServiceConnected(ComponentName name, IBinder service) { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1067 IMediaContainerService imcs = 1068 IMediaContainerService.Stub.asInterface(service); 1069 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1070 } 1071 1072 public void onServiceDisconnected(ComponentName name) { 1073 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1074 } 1075 } 1076 1077 // Recordkeeping of restore-after-install operations that are currently in flight 1078 // between the Package Manager and the Backup Manager 1079 static class PostInstallData { 1080 public InstallArgs args; 1081 public PackageInstalledInfo res; 1082 1083 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1084 args = _a; 1085 res = _r; 1086 } 1087 } 1088 1089 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1090 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1091 1092 // XML tags for backup/restore of various bits of state 1093 private static final String TAG_PREFERRED_BACKUP = "pa"; 1094 private static final String TAG_DEFAULT_APPS = "da"; 1095 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1096 1097 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1098 private static final String TAG_ALL_GRANTS = "rt-grants"; 1099 private static final String TAG_GRANT = "grant"; 1100 private static final String ATTR_PACKAGE_NAME = "pkg"; 1101 1102 private static final String TAG_PERMISSION = "perm"; 1103 private static final String ATTR_PERMISSION_NAME = "name"; 1104 private static final String ATTR_IS_GRANTED = "g"; 1105 private static final String ATTR_USER_SET = "set"; 1106 private static final String ATTR_USER_FIXED = "fixed"; 1107 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1108 1109 // System/policy permission grants are not backed up 1110 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1111 FLAG_PERMISSION_POLICY_FIXED 1112 | FLAG_PERMISSION_SYSTEM_FIXED 1113 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1114 1115 // And we back up these user-adjusted states 1116 private static final int USER_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_USER_SET 1118 | FLAG_PERMISSION_USER_FIXED 1119 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1120 1121 final @Nullable String mRequiredVerifierPackage; 1122 final @NonNull String mRequiredInstallerPackage; 1123 final @Nullable String mSetupWizardPackage; 1124 final @NonNull String mServicesSystemSharedLibraryPackageName; 1125 final @NonNull String mSharedSystemSharedLibraryPackageName; 1126 1127 private final PackageUsage mPackageUsage = new PackageUsage(); 1128 private final CompilerStats mCompilerStats = new CompilerStats(); 1129 1130 class PackageHandler extends Handler { 1131 private boolean mBound = false; 1132 final ArrayList<HandlerParams> mPendingInstalls = 1133 new ArrayList<HandlerParams>(); 1134 1135 private boolean connectToService() { 1136 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1137 " DefaultContainerService"); 1138 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1139 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1140 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1141 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1142 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1143 mBound = true; 1144 return true; 1145 } 1146 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1147 return false; 1148 } 1149 1150 private void disconnectService() { 1151 mContainerService = null; 1152 mBound = false; 1153 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1154 mContext.unbindService(mDefContainerConn); 1155 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1156 } 1157 1158 PackageHandler(Looper looper) { 1159 super(looper); 1160 } 1161 1162 public void handleMessage(Message msg) { 1163 try { 1164 doHandleMessage(msg); 1165 } finally { 1166 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1167 } 1168 } 1169 1170 void doHandleMessage(Message msg) { 1171 switch (msg.what) { 1172 case INIT_COPY: { 1173 HandlerParams params = (HandlerParams) msg.obj; 1174 int idx = mPendingInstalls.size(); 1175 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1176 // If a bind was already initiated we dont really 1177 // need to do anything. The pending install 1178 // will be processed later on. 1179 if (!mBound) { 1180 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1181 System.identityHashCode(mHandler)); 1182 // If this is the only one pending we might 1183 // have to bind to the service again. 1184 if (!connectToService()) { 1185 Slog.e(TAG, "Failed to bind to media container service"); 1186 params.serviceError(); 1187 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1188 System.identityHashCode(mHandler)); 1189 if (params.traceMethod != null) { 1190 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1191 params.traceCookie); 1192 } 1193 return; 1194 } else { 1195 // Once we bind to the service, the first 1196 // pending request will be processed. 1197 mPendingInstalls.add(idx, params); 1198 } 1199 } else { 1200 mPendingInstalls.add(idx, params); 1201 // Already bound to the service. Just make 1202 // sure we trigger off processing the first request. 1203 if (idx == 0) { 1204 mHandler.sendEmptyMessage(MCS_BOUND); 1205 } 1206 } 1207 break; 1208 } 1209 case MCS_BOUND: { 1210 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1211 if (msg.obj != null) { 1212 mContainerService = (IMediaContainerService) msg.obj; 1213 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1214 System.identityHashCode(mHandler)); 1215 } 1216 if (mContainerService == null) { 1217 if (!mBound) { 1218 // Something seriously wrong since we are not bound and we are not 1219 // waiting for connection. Bail out. 1220 Slog.e(TAG, "Cannot bind to media container service"); 1221 for (HandlerParams params : mPendingInstalls) { 1222 // Indicate service bind error 1223 params.serviceError(); 1224 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1225 System.identityHashCode(params)); 1226 if (params.traceMethod != null) { 1227 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1228 params.traceMethod, params.traceCookie); 1229 } 1230 return; 1231 } 1232 mPendingInstalls.clear(); 1233 } else { 1234 Slog.w(TAG, "Waiting to connect to media container service"); 1235 } 1236 } else if (mPendingInstalls.size() > 0) { 1237 HandlerParams params = mPendingInstalls.get(0); 1238 if (params != null) { 1239 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1240 System.identityHashCode(params)); 1241 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1242 if (params.startCopy()) { 1243 // We are done... look for more work or to 1244 // go idle. 1245 if (DEBUG_SD_INSTALL) Log.i(TAG, 1246 "Checking for more work or unbind..."); 1247 // Delete pending install 1248 if (mPendingInstalls.size() > 0) { 1249 mPendingInstalls.remove(0); 1250 } 1251 if (mPendingInstalls.size() == 0) { 1252 if (mBound) { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, 1254 "Posting delayed MCS_UNBIND"); 1255 removeMessages(MCS_UNBIND); 1256 Message ubmsg = obtainMessage(MCS_UNBIND); 1257 // Unbind after a little delay, to avoid 1258 // continual thrashing. 1259 sendMessageDelayed(ubmsg, 10000); 1260 } 1261 } else { 1262 // There are more pending requests in queue. 1263 // Just post MCS_BOUND message to trigger processing 1264 // of next pending install. 1265 if (DEBUG_SD_INSTALL) Log.i(TAG, 1266 "Posting MCS_BOUND for next work"); 1267 mHandler.sendEmptyMessage(MCS_BOUND); 1268 } 1269 } 1270 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1271 } 1272 } else { 1273 // Should never happen ideally. 1274 Slog.w(TAG, "Empty queue"); 1275 } 1276 break; 1277 } 1278 case MCS_RECONNECT: { 1279 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1280 if (mPendingInstalls.size() > 0) { 1281 if (mBound) { 1282 disconnectService(); 1283 } 1284 if (!connectToService()) { 1285 Slog.e(TAG, "Failed to bind to media container service"); 1286 for (HandlerParams params : mPendingInstalls) { 1287 // Indicate service bind error 1288 params.serviceError(); 1289 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1290 System.identityHashCode(params)); 1291 } 1292 mPendingInstalls.clear(); 1293 } 1294 } 1295 break; 1296 } 1297 case MCS_UNBIND: { 1298 // If there is no actual work left, then time to unbind. 1299 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1300 1301 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1302 if (mBound) { 1303 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1304 1305 disconnectService(); 1306 } 1307 } else if (mPendingInstalls.size() > 0) { 1308 // There are more pending requests in queue. 1309 // Just post MCS_BOUND message to trigger processing 1310 // of next pending install. 1311 mHandler.sendEmptyMessage(MCS_BOUND); 1312 } 1313 1314 break; 1315 } 1316 case MCS_GIVE_UP: { 1317 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1318 HandlerParams params = mPendingInstalls.remove(0); 1319 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1320 System.identityHashCode(params)); 1321 break; 1322 } 1323 case SEND_PENDING_BROADCAST: { 1324 String packages[]; 1325 ArrayList<String> components[]; 1326 int size = 0; 1327 int uids[]; 1328 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1329 synchronized (mPackages) { 1330 if (mPendingBroadcasts == null) { 1331 return; 1332 } 1333 size = mPendingBroadcasts.size(); 1334 if (size <= 0) { 1335 // Nothing to be done. Just return 1336 return; 1337 } 1338 packages = new String[size]; 1339 components = new ArrayList[size]; 1340 uids = new int[size]; 1341 int i = 0; // filling out the above arrays 1342 1343 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1344 int packageUserId = mPendingBroadcasts.userIdAt(n); 1345 Iterator<Map.Entry<String, ArrayList<String>>> it 1346 = mPendingBroadcasts.packagesForUserId(packageUserId) 1347 .entrySet().iterator(); 1348 while (it.hasNext() && i < size) { 1349 Map.Entry<String, ArrayList<String>> ent = it.next(); 1350 packages[i] = ent.getKey(); 1351 components[i] = ent.getValue(); 1352 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1353 uids[i] = (ps != null) 1354 ? UserHandle.getUid(packageUserId, ps.appId) 1355 : -1; 1356 i++; 1357 } 1358 } 1359 size = i; 1360 mPendingBroadcasts.clear(); 1361 } 1362 // Send broadcasts 1363 for (int i = 0; i < size; i++) { 1364 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1365 } 1366 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1367 break; 1368 } 1369 case START_CLEANING_PACKAGE: { 1370 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1371 final String packageName = (String)msg.obj; 1372 final int userId = msg.arg1; 1373 final boolean andCode = msg.arg2 != 0; 1374 synchronized (mPackages) { 1375 if (userId == UserHandle.USER_ALL) { 1376 int[] users = sUserManager.getUserIds(); 1377 for (int user : users) { 1378 mSettings.addPackageToCleanLPw( 1379 new PackageCleanItem(user, packageName, andCode)); 1380 } 1381 } else { 1382 mSettings.addPackageToCleanLPw( 1383 new PackageCleanItem(userId, packageName, andCode)); 1384 } 1385 } 1386 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1387 startCleaningPackages(); 1388 } break; 1389 case POST_INSTALL: { 1390 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1391 1392 PostInstallData data = mRunningInstalls.get(msg.arg1); 1393 final boolean didRestore = (msg.arg2 != 0); 1394 mRunningInstalls.delete(msg.arg1); 1395 1396 if (data != null) { 1397 InstallArgs args = data.args; 1398 PackageInstalledInfo parentRes = data.res; 1399 1400 final boolean grantPermissions = (args.installFlags 1401 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1402 final boolean killApp = (args.installFlags 1403 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1404 final String[] grantedPermissions = args.installGrantPermissions; 1405 1406 // Handle the parent package 1407 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1408 grantedPermissions, didRestore, args.installerPackageName, 1409 args.observer); 1410 1411 // Handle the child packages 1412 final int childCount = (parentRes.addedChildPackages != null) 1413 ? parentRes.addedChildPackages.size() : 0; 1414 for (int i = 0; i < childCount; i++) { 1415 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1416 handlePackagePostInstall(childRes, grantPermissions, killApp, 1417 grantedPermissions, false, args.installerPackageName, 1418 args.observer); 1419 } 1420 1421 // Log tracing if needed 1422 if (args.traceMethod != null) { 1423 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1424 args.traceCookie); 1425 } 1426 } else { 1427 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1428 } 1429 1430 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1431 } break; 1432 case UPDATED_MEDIA_STATUS: { 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1434 boolean reportStatus = msg.arg1 == 1; 1435 boolean doGc = msg.arg2 == 1; 1436 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1437 if (doGc) { 1438 // Force a gc to clear up stale containers. 1439 Runtime.getRuntime().gc(); 1440 } 1441 if (msg.obj != null) { 1442 @SuppressWarnings("unchecked") 1443 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1444 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1445 // Unload containers 1446 unloadAllContainers(args); 1447 } 1448 if (reportStatus) { 1449 try { 1450 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1451 PackageHelper.getMountService().finishMediaUpdate(); 1452 } catch (RemoteException e) { 1453 Log.e(TAG, "MountService not running?"); 1454 } 1455 } 1456 } break; 1457 case WRITE_SETTINGS: { 1458 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1459 synchronized (mPackages) { 1460 removeMessages(WRITE_SETTINGS); 1461 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1462 mSettings.writeLPr(); 1463 mDirtyUsers.clear(); 1464 } 1465 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1466 } break; 1467 case WRITE_PACKAGE_RESTRICTIONS: { 1468 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1469 synchronized (mPackages) { 1470 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1471 for (int userId : mDirtyUsers) { 1472 mSettings.writePackageRestrictionsLPr(userId); 1473 } 1474 mDirtyUsers.clear(); 1475 } 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1477 } break; 1478 case WRITE_PACKAGE_LIST: { 1479 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1480 synchronized (mPackages) { 1481 removeMessages(WRITE_PACKAGE_LIST); 1482 mSettings.writePackageListLPr(msg.arg1); 1483 } 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1485 } break; 1486 case CHECK_PENDING_VERIFICATION: { 1487 final int verificationId = msg.arg1; 1488 final PackageVerificationState state = mPendingVerification.get(verificationId); 1489 1490 if ((state != null) && !state.timeoutExtended()) { 1491 final InstallArgs args = state.getInstallArgs(); 1492 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1493 1494 Slog.i(TAG, "Verification timed out for " + originUri); 1495 mPendingVerification.remove(verificationId); 1496 1497 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1498 1499 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1500 Slog.i(TAG, "Continuing with installation of " + originUri); 1501 state.setVerifierResponse(Binder.getCallingUid(), 1502 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1503 broadcastPackageVerified(verificationId, originUri, 1504 PackageManager.VERIFICATION_ALLOW, 1505 state.getInstallArgs().getUser()); 1506 try { 1507 ret = args.copyApk(mContainerService, true); 1508 } catch (RemoteException e) { 1509 Slog.e(TAG, "Could not contact the ContainerService"); 1510 } 1511 } else { 1512 broadcastPackageVerified(verificationId, originUri, 1513 PackageManager.VERIFICATION_REJECT, 1514 state.getInstallArgs().getUser()); 1515 } 1516 1517 Trace.asyncTraceEnd( 1518 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1519 1520 processPendingInstall(args, ret); 1521 mHandler.sendEmptyMessage(MCS_UNBIND); 1522 } 1523 break; 1524 } 1525 case PACKAGE_VERIFIED: { 1526 final int verificationId = msg.arg1; 1527 1528 final PackageVerificationState state = mPendingVerification.get(verificationId); 1529 if (state == null) { 1530 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1531 break; 1532 } 1533 1534 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1535 1536 state.setVerifierResponse(response.callerUid, response.code); 1537 1538 if (state.isVerificationComplete()) { 1539 mPendingVerification.remove(verificationId); 1540 1541 final InstallArgs args = state.getInstallArgs(); 1542 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1543 1544 int ret; 1545 if (state.isInstallAllowed()) { 1546 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1547 broadcastPackageVerified(verificationId, originUri, 1548 response.code, state.getInstallArgs().getUser()); 1549 try { 1550 ret = args.copyApk(mContainerService, true); 1551 } catch (RemoteException e) { 1552 Slog.e(TAG, "Could not contact the ContainerService"); 1553 } 1554 } else { 1555 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1556 } 1557 1558 Trace.asyncTraceEnd( 1559 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1560 1561 processPendingInstall(args, ret); 1562 mHandler.sendEmptyMessage(MCS_UNBIND); 1563 } 1564 1565 break; 1566 } 1567 case START_INTENT_FILTER_VERIFICATIONS: { 1568 IFVerificationParams params = (IFVerificationParams) msg.obj; 1569 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1570 params.replacing, params.pkg); 1571 break; 1572 } 1573 case INTENT_FILTER_VERIFIED: { 1574 final int verificationId = msg.arg1; 1575 1576 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1577 verificationId); 1578 if (state == null) { 1579 Slog.w(TAG, "Invalid IntentFilter verification token " 1580 + verificationId + " received"); 1581 break; 1582 } 1583 1584 final int userId = state.getUserId(); 1585 1586 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1587 "Processing IntentFilter verification with token:" 1588 + verificationId + " and userId:" + userId); 1589 1590 final IntentFilterVerificationResponse response = 1591 (IntentFilterVerificationResponse) msg.obj; 1592 1593 state.setVerifierResponse(response.callerUid, response.code); 1594 1595 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1596 "IntentFilter verification with token:" + verificationId 1597 + " and userId:" + userId 1598 + " is settings verifier response with response code:" 1599 + response.code); 1600 1601 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1602 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1603 + response.getFailedDomainsString()); 1604 } 1605 1606 if (state.isVerificationComplete()) { 1607 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1608 } else { 1609 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1610 "IntentFilter verification with token:" + verificationId 1611 + " was not said to be complete"); 1612 } 1613 1614 break; 1615 } 1616 } 1617 } 1618 } 1619 1620 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1621 boolean killApp, String[] grantedPermissions, 1622 boolean launchedForRestore, String installerPackage, 1623 IPackageInstallObserver2 installObserver) { 1624 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1625 // Send the removed broadcasts 1626 if (res.removedInfo != null) { 1627 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1628 } 1629 1630 // Now that we successfully installed the package, grant runtime 1631 // permissions if requested before broadcasting the install. 1632 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1633 >= Build.VERSION_CODES.M) { 1634 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1635 } 1636 1637 final boolean update = res.removedInfo != null 1638 && res.removedInfo.removedPackage != null; 1639 1640 // If this is the first time we have child packages for a disabled privileged 1641 // app that had no children, we grant requested runtime permissions to the new 1642 // children if the parent on the system image had them already granted. 1643 if (res.pkg.parentPackage != null) { 1644 synchronized (mPackages) { 1645 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1646 } 1647 } 1648 1649 synchronized (mPackages) { 1650 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1651 } 1652 1653 final String packageName = res.pkg.applicationInfo.packageName; 1654 Bundle extras = new Bundle(1); 1655 extras.putInt(Intent.EXTRA_UID, res.uid); 1656 1657 // Determine the set of users who are adding this package for 1658 // the first time vs. those who are seeing an update. 1659 int[] firstUsers = EMPTY_INT_ARRAY; 1660 int[] updateUsers = EMPTY_INT_ARRAY; 1661 if (res.origUsers == null || res.origUsers.length == 0) { 1662 firstUsers = res.newUsers; 1663 } else { 1664 for (int newUser : res.newUsers) { 1665 boolean isNew = true; 1666 for (int origUser : res.origUsers) { 1667 if (origUser == newUser) { 1668 isNew = false; 1669 break; 1670 } 1671 } 1672 if (isNew) { 1673 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1674 } else { 1675 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1676 } 1677 } 1678 } 1679 1680 // Send installed broadcasts if the install/update is not ephemeral 1681 if (!isEphemeral(res.pkg)) { 1682 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1683 1684 // Send added for users that see the package for the first time 1685 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1686 extras, 0 /*flags*/, null /*targetPackage*/, 1687 null /*finishedReceiver*/, firstUsers); 1688 1689 // Send added for users that don't see the package for the first time 1690 if (update) { 1691 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1692 } 1693 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1694 extras, 0 /*flags*/, null /*targetPackage*/, 1695 null /*finishedReceiver*/, updateUsers); 1696 1697 // Send replaced for users that don't see the package for the first time 1698 if (update) { 1699 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1700 packageName, extras, 0 /*flags*/, 1701 null /*targetPackage*/, null /*finishedReceiver*/, 1702 updateUsers); 1703 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1704 null /*package*/, null /*extras*/, 0 /*flags*/, 1705 packageName /*targetPackage*/, 1706 null /*finishedReceiver*/, updateUsers); 1707 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1708 // First-install and we did a restore, so we're responsible for the 1709 // first-launch broadcast. 1710 if (DEBUG_BACKUP) { 1711 Slog.i(TAG, "Post-restore of " + packageName 1712 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1713 } 1714 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1715 } 1716 1717 // Send broadcast package appeared if forward locked/external for all users 1718 // treat asec-hosted packages like removable media on upgrade 1719 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1720 if (DEBUG_INSTALL) { 1721 Slog.i(TAG, "upgrading pkg " + res.pkg 1722 + " is ASEC-hosted -> AVAILABLE"); 1723 } 1724 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1725 ArrayList<String> pkgList = new ArrayList<>(1); 1726 pkgList.add(packageName); 1727 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1728 } 1729 } 1730 1731 // Work that needs to happen on first install within each user 1732 if (firstUsers != null && firstUsers.length > 0) { 1733 synchronized (mPackages) { 1734 for (int userId : firstUsers) { 1735 // If this app is a browser and it's newly-installed for some 1736 // users, clear any default-browser state in those users. The 1737 // app's nature doesn't depend on the user, so we can just check 1738 // its browser nature in any user and generalize. 1739 if (packageIsBrowser(packageName, userId)) { 1740 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1741 } 1742 1743 // We may also need to apply pending (restored) runtime 1744 // permission grants within these users. 1745 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1746 } 1747 } 1748 } 1749 1750 // Log current value of "unknown sources" setting 1751 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1752 getUnknownSourcesSettings()); 1753 1754 // Force a gc to clear up things 1755 Runtime.getRuntime().gc(); 1756 1757 // Remove the replaced package's older resources safely now 1758 // We delete after a gc for applications on sdcard. 1759 if (res.removedInfo != null && res.removedInfo.args != null) { 1760 synchronized (mInstallLock) { 1761 res.removedInfo.args.doPostDeleteLI(true); 1762 } 1763 } 1764 } 1765 1766 // If someone is watching installs - notify them 1767 if (installObserver != null) { 1768 try { 1769 Bundle extras = extrasForInstallResult(res); 1770 installObserver.onPackageInstalled(res.name, res.returnCode, 1771 res.returnMsg, extras); 1772 } catch (RemoteException e) { 1773 Slog.i(TAG, "Observer no longer exists."); 1774 } 1775 } 1776 } 1777 1778 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1779 PackageParser.Package pkg) { 1780 if (pkg.parentPackage == null) { 1781 return; 1782 } 1783 if (pkg.requestedPermissions == null) { 1784 return; 1785 } 1786 final PackageSetting disabledSysParentPs = mSettings 1787 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1788 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1789 || !disabledSysParentPs.isPrivileged() 1790 || (disabledSysParentPs.childPackageNames != null 1791 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1792 return; 1793 } 1794 final int[] allUserIds = sUserManager.getUserIds(); 1795 final int permCount = pkg.requestedPermissions.size(); 1796 for (int i = 0; i < permCount; i++) { 1797 String permission = pkg.requestedPermissions.get(i); 1798 BasePermission bp = mSettings.mPermissions.get(permission); 1799 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1800 continue; 1801 } 1802 for (int userId : allUserIds) { 1803 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1804 permission, userId)) { 1805 grantRuntimePermission(pkg.packageName, permission, userId); 1806 } 1807 } 1808 } 1809 } 1810 1811 private StorageEventListener mStorageListener = new StorageEventListener() { 1812 @Override 1813 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1814 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1815 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1816 final String volumeUuid = vol.getFsUuid(); 1817 1818 // Clean up any users or apps that were removed or recreated 1819 // while this volume was missing 1820 reconcileUsers(volumeUuid); 1821 reconcileApps(volumeUuid); 1822 1823 // Clean up any install sessions that expired or were 1824 // cancelled while this volume was missing 1825 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1826 1827 loadPrivatePackages(vol); 1828 1829 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1830 unloadPrivatePackages(vol); 1831 } 1832 } 1833 1834 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1835 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1836 updateExternalMediaStatus(true, false); 1837 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1838 updateExternalMediaStatus(false, false); 1839 } 1840 } 1841 } 1842 1843 @Override 1844 public void onVolumeForgotten(String fsUuid) { 1845 if (TextUtils.isEmpty(fsUuid)) { 1846 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1847 return; 1848 } 1849 1850 // Remove any apps installed on the forgotten volume 1851 synchronized (mPackages) { 1852 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1853 for (PackageSetting ps : packages) { 1854 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1855 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1856 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1857 } 1858 1859 mSettings.onVolumeForgotten(fsUuid); 1860 mSettings.writeLPr(); 1861 } 1862 } 1863 }; 1864 1865 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1866 String[] grantedPermissions) { 1867 for (int userId : userIds) { 1868 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1869 } 1870 1871 // We could have touched GID membership, so flush out packages.list 1872 synchronized (mPackages) { 1873 mSettings.writePackageListLPr(); 1874 } 1875 } 1876 1877 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1878 String[] grantedPermissions) { 1879 SettingBase sb = (SettingBase) pkg.mExtras; 1880 if (sb == null) { 1881 return; 1882 } 1883 1884 PermissionsState permissionsState = sb.getPermissionsState(); 1885 1886 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1887 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1888 1889 for (String permission : pkg.requestedPermissions) { 1890 final BasePermission bp; 1891 synchronized (mPackages) { 1892 bp = mSettings.mPermissions.get(permission); 1893 } 1894 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1895 && (grantedPermissions == null 1896 || ArrayUtils.contains(grantedPermissions, permission))) { 1897 final int flags = permissionsState.getPermissionFlags(permission, userId); 1898 // Installer cannot change immutable permissions. 1899 if ((flags & immutableFlags) == 0) { 1900 grantRuntimePermission(pkg.packageName, permission, userId); 1901 } 1902 } 1903 } 1904 } 1905 1906 Bundle extrasForInstallResult(PackageInstalledInfo res) { 1907 Bundle extras = null; 1908 switch (res.returnCode) { 1909 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1910 extras = new Bundle(); 1911 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1912 res.origPermission); 1913 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1914 res.origPackage); 1915 break; 1916 } 1917 case PackageManager.INSTALL_SUCCEEDED: { 1918 extras = new Bundle(); 1919 extras.putBoolean(Intent.EXTRA_REPLACING, 1920 res.removedInfo != null && res.removedInfo.removedPackage != null); 1921 break; 1922 } 1923 } 1924 return extras; 1925 } 1926 1927 void scheduleWriteSettingsLocked() { 1928 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1929 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1930 } 1931 } 1932 1933 void scheduleWritePackageListLocked(int userId) { 1934 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1935 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1936 msg.arg1 = userId; 1937 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1938 } 1939 } 1940 1941 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 1942 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1943 scheduleWritePackageRestrictionsLocked(userId); 1944 } 1945 1946 void scheduleWritePackageRestrictionsLocked(int userId) { 1947 final int[] userIds = (userId == UserHandle.USER_ALL) 1948 ? sUserManager.getUserIds() : new int[]{userId}; 1949 for (int nextUserId : userIds) { 1950 if (!sUserManager.exists(nextUserId)) return; 1951 mDirtyUsers.add(nextUserId); 1952 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 1953 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 1954 } 1955 } 1956 } 1957 1958 public static PackageManagerService main(Context context, Installer installer, 1959 boolean factoryTest, boolean onlyCore) { 1960 // Self-check for initial settings. 1961 PackageManagerServiceCompilerMapping.checkProperties(); 1962 1963 PackageManagerService m = new PackageManagerService(context, installer, 1964 factoryTest, onlyCore); 1965 m.enableSystemUserPackages(); 1966 ServiceManager.addService("package", m); 1967 return m; 1968 } 1969 1970 private void enableSystemUserPackages() { 1971 if (!UserManager.isSplitSystemUser()) { 1972 return; 1973 } 1974 // For system user, enable apps based on the following conditions: 1975 // - app is whitelisted or belong to one of these groups: 1976 // -- system app which has no launcher icons 1977 // -- system app which has INTERACT_ACROSS_USERS permission 1978 // -- system IME app 1979 // - app is not in the blacklist 1980 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 1981 Set<String> enableApps = new ArraySet<>(); 1982 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 1983 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 1984 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 1985 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 1986 enableApps.addAll(wlApps); 1987 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 1988 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 1989 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 1990 enableApps.removeAll(blApps); 1991 Log.i(TAG, "Applications installed for system user: " + enableApps); 1992 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 1993 UserHandle.SYSTEM); 1994 final int allAppsSize = allAps.size(); 1995 synchronized (mPackages) { 1996 for (int i = 0; i < allAppsSize; i++) { 1997 String pName = allAps.get(i); 1998 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 1999 // Should not happen, but we shouldn't be failing if it does 2000 if (pkgSetting == null) { 2001 continue; 2002 } 2003 boolean install = enableApps.contains(pName); 2004 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2005 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2006 + " for system user"); 2007 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2008 } 2009 } 2010 } 2011 } 2012 2013 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2014 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2015 Context.DISPLAY_SERVICE); 2016 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2017 } 2018 2019 /** 2020 * Requests that files preopted on a secondary system partition be copied to the data partition 2021 * if possible. Note that the actual copying of the files is accomplished by init for security 2022 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2023 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2024 */ 2025 private static void requestCopyPreoptedFiles() { 2026 final int WAIT_TIME_MS = 100; 2027 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2028 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2029 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2030 // We will wait for up to 100 seconds. 2031 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2032 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2033 try { 2034 Thread.sleep(WAIT_TIME_MS); 2035 } catch (InterruptedException e) { 2036 // Do nothing 2037 } 2038 if (SystemClock.uptimeMillis() > timeEnd) { 2039 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2040 Slog.wtf(TAG, "cppreopt did not finish!"); 2041 break; 2042 } 2043 } 2044 } 2045 } 2046 2047 public PackageManagerService(Context context, Installer installer, 2048 boolean factoryTest, boolean onlyCore) { 2049 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2050 SystemClock.uptimeMillis()); 2051 2052 if (mSdkVersion <= 0) { 2053 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2054 } 2055 2056 mContext = context; 2057 mFactoryTest = factoryTest; 2058 mOnlyCore = onlyCore; 2059 mMetrics = new DisplayMetrics(); 2060 mSettings = new Settings(mPackages); 2061 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2062 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2063 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2064 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2065 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2066 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2067 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2068 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2069 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2070 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2071 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2072 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2073 2074 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2075 if (separateProcesses != null && separateProcesses.length() > 0) { 2076 if ("*".equals(separateProcesses)) { 2077 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2078 mSeparateProcesses = null; 2079 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2080 } else { 2081 mDefParseFlags = 0; 2082 mSeparateProcesses = separateProcesses.split(","); 2083 Slog.w(TAG, "Running with debug.separate_processes: " 2084 + separateProcesses); 2085 } 2086 } else { 2087 mDefParseFlags = 0; 2088 mSeparateProcesses = null; 2089 } 2090 2091 mInstaller = installer; 2092 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2093 "*dexopt*"); 2094 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2095 2096 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2097 FgThread.get().getLooper()); 2098 2099 getDefaultDisplayMetrics(context, mMetrics); 2100 2101 SystemConfig systemConfig = SystemConfig.getInstance(); 2102 mGlobalGids = systemConfig.getGlobalGids(); 2103 mSystemPermissions = systemConfig.getSystemPermissions(); 2104 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2105 2106 mProtectedPackages = new ProtectedPackages(mContext); 2107 2108 synchronized (mInstallLock) { 2109 // writer 2110 synchronized (mPackages) { 2111 mHandlerThread = new ServiceThread(TAG, 2112 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2113 mHandlerThread.start(); 2114 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2115 mProcessLoggingHandler = new ProcessLoggingHandler(); 2116 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2117 2118 File dataDir = Environment.getDataDirectory(); 2119 mAppInstallDir = new File(dataDir, "app"); 2120 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2121 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2122 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2123 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2124 2125 sUserManager = new UserManagerService(context, this, mPackages); 2126 2127 // Propagate permission configuration in to package manager. 2128 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2129 = systemConfig.getPermissions(); 2130 for (int i=0; i<permConfig.size(); i++) { 2131 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2132 BasePermission bp = mSettings.mPermissions.get(perm.name); 2133 if (bp == null) { 2134 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2135 mSettings.mPermissions.put(perm.name, bp); 2136 } 2137 if (perm.gids != null) { 2138 bp.setGids(perm.gids, perm.perUser); 2139 } 2140 } 2141 2142 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2143 for (int i=0; i<libConfig.size(); i++) { 2144 mSharedLibraries.put(libConfig.keyAt(i), 2145 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2146 } 2147 2148 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2149 2150 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2151 2152 if (mFirstBoot) { 2153 requestCopyPreoptedFiles(); 2154 } 2155 2156 String customResolverActivity = Resources.getSystem().getString( 2157 R.string.config_customResolverActivity); 2158 if (TextUtils.isEmpty(customResolverActivity)) { 2159 customResolverActivity = null; 2160 } else { 2161 mCustomResolverComponentName = ComponentName.unflattenFromString( 2162 customResolverActivity); 2163 } 2164 2165 long startTime = SystemClock.uptimeMillis(); 2166 2167 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2168 startTime); 2169 2170 // Set flag to monitor and not change apk file paths when 2171 // scanning install directories. 2172 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2173 2174 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2175 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2176 2177 if (bootClassPath == null) { 2178 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2179 } 2180 2181 if (systemServerClassPath == null) { 2182 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2183 } 2184 2185 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2186 final String[] dexCodeInstructionSets = 2187 getDexCodeInstructionSets( 2188 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2189 2190 /** 2191 * Ensure all external libraries have had dexopt run on them. 2192 */ 2193 if (mSharedLibraries.size() > 0) { 2194 // NOTE: For now, we're compiling these system "shared libraries" 2195 // (and framework jars) into all available architectures. It's possible 2196 // to compile them only when we come across an app that uses them (there's 2197 // already logic for that in scanPackageLI) but that adds some complexity. 2198 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2199 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2200 final String lib = libEntry.path; 2201 if (lib == null) { 2202 continue; 2203 } 2204 2205 try { 2206 // Shared libraries do not have profiles so we perform a full 2207 // AOT compilation (if needed). 2208 int dexoptNeeded = DexFile.getDexOptNeeded( 2209 lib, dexCodeInstructionSet, 2210 getCompilerFilterForReason(REASON_SHARED_APK), 2211 false /* newProfile */); 2212 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2213 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2214 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2215 getCompilerFilterForReason(REASON_SHARED_APK), 2216 StorageManager.UUID_PRIVATE_INTERNAL, 2217 SKIP_SHARED_LIBRARY_CHECK); 2218 } 2219 } catch (FileNotFoundException e) { 2220 Slog.w(TAG, "Library not found: " + lib); 2221 } catch (IOException | InstallerException e) { 2222 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2223 + e.getMessage()); 2224 } 2225 } 2226 } 2227 } 2228 2229 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2230 2231 final VersionInfo ver = mSettings.getInternalVersion(); 2232 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2233 2234 // when upgrading from pre-M, promote system app permissions from install to runtime 2235 mPromoteSystemApps = 2236 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2237 2238 // When upgrading from pre-N, we need to handle package extraction like first boot, 2239 // as there is no profiling data available. 2240 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2241 2242 // save off the names of pre-existing system packages prior to scanning; we don't 2243 // want to automatically grant runtime permissions for new system apps 2244 if (mPromoteSystemApps) { 2245 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2246 while (pkgSettingIter.hasNext()) { 2247 PackageSetting ps = pkgSettingIter.next(); 2248 if (isSystemApp(ps)) { 2249 mExistingSystemPackages.add(ps.name); 2250 } 2251 } 2252 } 2253 2254 // Collect vendor overlay packages. 2255 // (Do this before scanning any apps.) 2256 // For security and version matching reason, only consider 2257 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2258 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2259 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2260 | PackageParser.PARSE_IS_SYSTEM 2261 | PackageParser.PARSE_IS_SYSTEM_DIR 2262 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2263 2264 // Find base frameworks (resource packages without code). 2265 scanDirTracedLI(frameworkDir, mDefParseFlags 2266 | PackageParser.PARSE_IS_SYSTEM 2267 | PackageParser.PARSE_IS_SYSTEM_DIR 2268 | PackageParser.PARSE_IS_PRIVILEGED, 2269 scanFlags | SCAN_NO_DEX, 0); 2270 2271 // Collected privileged system packages. 2272 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2273 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2274 | PackageParser.PARSE_IS_SYSTEM 2275 | PackageParser.PARSE_IS_SYSTEM_DIR 2276 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2277 2278 // Collect ordinary system packages. 2279 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2280 scanDirTracedLI(systemAppDir, mDefParseFlags 2281 | PackageParser.PARSE_IS_SYSTEM 2282 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2283 2284 // Collect all vendor packages. 2285 File vendorAppDir = new File("/vendor/app"); 2286 try { 2287 vendorAppDir = vendorAppDir.getCanonicalFile(); 2288 } catch (IOException e) { 2289 // failed to look up canonical path, continue with original one 2290 } 2291 scanDirTracedLI(vendorAppDir, mDefParseFlags 2292 | PackageParser.PARSE_IS_SYSTEM 2293 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2294 2295 // Collect all OEM packages. 2296 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2297 scanDirTracedLI(oemAppDir, mDefParseFlags 2298 | PackageParser.PARSE_IS_SYSTEM 2299 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2300 2301 // Prune any system packages that no longer exist. 2302 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2303 if (!mOnlyCore) { 2304 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2305 while (psit.hasNext()) { 2306 PackageSetting ps = psit.next(); 2307 2308 /* 2309 * If this is not a system app, it can't be a 2310 * disable system app. 2311 */ 2312 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2313 continue; 2314 } 2315 2316 /* 2317 * If the package is scanned, it's not erased. 2318 */ 2319 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2320 if (scannedPkg != null) { 2321 /* 2322 * If the system app is both scanned and in the 2323 * disabled packages list, then it must have been 2324 * added via OTA. Remove it from the currently 2325 * scanned package so the previously user-installed 2326 * application can be scanned. 2327 */ 2328 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2329 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2330 + ps.name + "; removing system app. Last known codePath=" 2331 + ps.codePathString + ", installStatus=" + ps.installStatus 2332 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2333 + scannedPkg.mVersionCode); 2334 removePackageLI(scannedPkg, true); 2335 mExpectingBetter.put(ps.name, ps.codePath); 2336 } 2337 2338 continue; 2339 } 2340 2341 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2342 psit.remove(); 2343 logCriticalInfo(Log.WARN, "System package " + ps.name 2344 + " no longer exists; it's data will be wiped"); 2345 // Actual deletion of code and data will be handled by later 2346 // reconciliation step 2347 } else { 2348 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2349 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2350 possiblyDeletedUpdatedSystemApps.add(ps.name); 2351 } 2352 } 2353 } 2354 } 2355 2356 //look for any incomplete package installations 2357 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2358 for (int i = 0; i < deletePkgsList.size(); i++) { 2359 // Actual deletion of code and data will be handled by later 2360 // reconciliation step 2361 final String packageName = deletePkgsList.get(i).name; 2362 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2363 synchronized (mPackages) { 2364 mSettings.removePackageLPw(packageName); 2365 } 2366 } 2367 2368 //delete tmp files 2369 deleteTempPackageFiles(); 2370 2371 // Remove any shared userIDs that have no associated packages 2372 mSettings.pruneSharedUsersLPw(); 2373 2374 if (!mOnlyCore) { 2375 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2376 SystemClock.uptimeMillis()); 2377 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2378 2379 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2380 | PackageParser.PARSE_FORWARD_LOCK, 2381 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2382 2383 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2384 | PackageParser.PARSE_IS_EPHEMERAL, 2385 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2386 2387 /** 2388 * Remove disable package settings for any updated system 2389 * apps that were removed via an OTA. If they're not a 2390 * previously-updated app, remove them completely. 2391 * Otherwise, just revoke their system-level permissions. 2392 */ 2393 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2394 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2395 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2396 2397 String msg; 2398 if (deletedPkg == null) { 2399 msg = "Updated system package " + deletedAppName 2400 + " no longer exists; it's data will be wiped"; 2401 // Actual deletion of code and data will be handled by later 2402 // reconciliation step 2403 } else { 2404 msg = "Updated system app + " + deletedAppName 2405 + " no longer present; removing system privileges for " 2406 + deletedAppName; 2407 2408 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2409 2410 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2411 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2412 } 2413 logCriticalInfo(Log.WARN, msg); 2414 } 2415 2416 /** 2417 * Make sure all system apps that we expected to appear on 2418 * the userdata partition actually showed up. If they never 2419 * appeared, crawl back and revive the system version. 2420 */ 2421 for (int i = 0; i < mExpectingBetter.size(); i++) { 2422 final String packageName = mExpectingBetter.keyAt(i); 2423 if (!mPackages.containsKey(packageName)) { 2424 final File scanFile = mExpectingBetter.valueAt(i); 2425 2426 logCriticalInfo(Log.WARN, "Expected better " + packageName 2427 + " but never showed up; reverting to system"); 2428 2429 int reparseFlags = mDefParseFlags; 2430 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2431 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR 2433 | PackageParser.PARSE_IS_PRIVILEGED; 2434 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2435 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR; 2437 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2438 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2439 | PackageParser.PARSE_IS_SYSTEM_DIR; 2440 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2441 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2442 | PackageParser.PARSE_IS_SYSTEM_DIR; 2443 } else { 2444 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2445 continue; 2446 } 2447 2448 mSettings.enableSystemPackageLPw(packageName); 2449 2450 try { 2451 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2452 } catch (PackageManagerException e) { 2453 Slog.e(TAG, "Failed to parse original system package: " 2454 + e.getMessage()); 2455 } 2456 } 2457 } 2458 } 2459 mExpectingBetter.clear(); 2460 2461 // Resolve protected action filters. Only the setup wizard is allowed to 2462 // have a high priority filter for these actions. 2463 mSetupWizardPackage = getSetupWizardPackageName(); 2464 if (mProtectedFilters.size() > 0) { 2465 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2466 Slog.i(TAG, "No setup wizard;" 2467 + " All protected intents capped to priority 0"); 2468 } 2469 for (ActivityIntentInfo filter : mProtectedFilters) { 2470 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2471 if (DEBUG_FILTERS) { 2472 Slog.i(TAG, "Found setup wizard;" 2473 + " allow priority " + filter.getPriority() + ";" 2474 + " package: " + filter.activity.info.packageName 2475 + " activity: " + filter.activity.className 2476 + " priority: " + filter.getPriority()); 2477 } 2478 // skip setup wizard; allow it to keep the high priority filter 2479 continue; 2480 } 2481 Slog.w(TAG, "Protected action; cap priority to 0;" 2482 + " package: " + filter.activity.info.packageName 2483 + " activity: " + filter.activity.className 2484 + " origPrio: " + filter.getPriority()); 2485 filter.setPriority(0); 2486 } 2487 } 2488 mDeferProtectedFilters = false; 2489 mProtectedFilters.clear(); 2490 2491 // Now that we know all of the shared libraries, update all clients to have 2492 // the correct library paths. 2493 updateAllSharedLibrariesLPw(); 2494 2495 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2496 // NOTE: We ignore potential failures here during a system scan (like 2497 // the rest of the commands above) because there's precious little we 2498 // can do about it. A settings error is reported, though. 2499 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2500 false /* boot complete */); 2501 } 2502 2503 // Now that we know all the packages we are keeping, 2504 // read and update their last usage times. 2505 mPackageUsage.read(mPackages); 2506 mCompilerStats.read(); 2507 2508 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2509 SystemClock.uptimeMillis()); 2510 Slog.i(TAG, "Time to scan packages: " 2511 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2512 + " seconds"); 2513 2514 // If the platform SDK has changed since the last time we booted, 2515 // we need to re-grant app permission to catch any new ones that 2516 // appear. This is really a hack, and means that apps can in some 2517 // cases get permissions that the user didn't initially explicitly 2518 // allow... it would be nice to have some better way to handle 2519 // this situation. 2520 int updateFlags = UPDATE_PERMISSIONS_ALL; 2521 if (ver.sdkVersion != mSdkVersion) { 2522 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2523 + mSdkVersion + "; regranting permissions for internal storage"); 2524 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2525 } 2526 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2527 ver.sdkVersion = mSdkVersion; 2528 2529 // If this is the first boot or an update from pre-M, and it is a normal 2530 // boot, then we need to initialize the default preferred apps across 2531 // all defined users. 2532 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2533 for (UserInfo user : sUserManager.getUsers(true)) { 2534 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2535 applyFactoryDefaultBrowserLPw(user.id); 2536 primeDomainVerificationsLPw(user.id); 2537 } 2538 } 2539 2540 // Prepare storage for system user really early during boot, 2541 // since core system apps like SettingsProvider and SystemUI 2542 // can't wait for user to start 2543 final int storageFlags; 2544 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2545 storageFlags = StorageManager.FLAG_STORAGE_DE; 2546 } else { 2547 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2548 } 2549 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2550 storageFlags); 2551 2552 // If this is first boot after an OTA, and a normal boot, then 2553 // we need to clear code cache directories. 2554 // Note that we do *not* clear the application profiles. These remain valid 2555 // across OTAs and are used to drive profile verification (post OTA) and 2556 // profile compilation (without waiting to collect a fresh set of profiles). 2557 if (mIsUpgrade && !onlyCore) { 2558 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2559 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2560 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2561 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2562 // No apps are running this early, so no need to freeze 2563 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2564 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2565 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2566 } 2567 } 2568 ver.fingerprint = Build.FINGERPRINT; 2569 } 2570 2571 checkDefaultBrowser(); 2572 2573 // clear only after permissions and other defaults have been updated 2574 mExistingSystemPackages.clear(); 2575 mPromoteSystemApps = false; 2576 2577 // All the changes are done during package scanning. 2578 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2579 2580 // can downgrade to reader 2581 mSettings.writeLPr(); 2582 2583 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2584 // early on (before the package manager declares itself as early) because other 2585 // components in the system server might ask for package contexts for these apps. 2586 // 2587 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2588 // (i.e, that the data partition is unavailable). 2589 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2590 long start = System.nanoTime(); 2591 List<PackageParser.Package> coreApps = new ArrayList<>(); 2592 for (PackageParser.Package pkg : mPackages.values()) { 2593 if (pkg.coreApp) { 2594 coreApps.add(pkg); 2595 } 2596 } 2597 2598 int[] stats = performDexOptUpgrade(coreApps, false, 2599 getCompilerFilterForReason(REASON_CORE_APP)); 2600 2601 final int elapsedTimeSeconds = 2602 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2603 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2604 2605 if (DEBUG_DEXOPT) { 2606 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2607 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2608 } 2609 2610 2611 // TODO: Should we log these stats to tron too ? 2612 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2613 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2614 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2615 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2616 } 2617 2618 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2619 SystemClock.uptimeMillis()); 2620 2621 if (!mOnlyCore) { 2622 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2623 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2624 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2625 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2626 mIntentFilterVerifierComponent); 2627 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2628 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2629 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2630 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2631 } else { 2632 mRequiredVerifierPackage = null; 2633 mRequiredInstallerPackage = null; 2634 mIntentFilterVerifierComponent = null; 2635 mIntentFilterVerifier = null; 2636 mServicesSystemSharedLibraryPackageName = null; 2637 mSharedSystemSharedLibraryPackageName = null; 2638 } 2639 2640 mInstallerService = new PackageInstallerService(context, this); 2641 2642 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2643 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2644 // both the installer and resolver must be present to enable ephemeral 2645 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2646 if (DEBUG_EPHEMERAL) { 2647 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2648 + " installer:" + ephemeralInstallerComponent); 2649 } 2650 mEphemeralResolverComponent = ephemeralResolverComponent; 2651 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2652 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2653 mEphemeralResolverConnection = 2654 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2655 } else { 2656 if (DEBUG_EPHEMERAL) { 2657 final String missingComponent = 2658 (ephemeralResolverComponent == null) 2659 ? (ephemeralInstallerComponent == null) 2660 ? "resolver and installer" 2661 : "resolver" 2662 : "installer"; 2663 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2664 } 2665 mEphemeralResolverComponent = null; 2666 mEphemeralInstallerComponent = null; 2667 mEphemeralResolverConnection = null; 2668 } 2669 2670 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2671 } // synchronized (mPackages) 2672 } // synchronized (mInstallLock) 2673 2674 // Now after opening every single application zip, make sure they 2675 // are all flushed. Not really needed, but keeps things nice and 2676 // tidy. 2677 Runtime.getRuntime().gc(); 2678 2679 // The initial scanning above does many calls into installd while 2680 // holding the mPackages lock, but we're mostly interested in yelling 2681 // once we have a booted system. 2682 mInstaller.setWarnIfHeld(mPackages); 2683 2684 // Expose private service for system components to use. 2685 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2686 } 2687 2688 @Override 2689 public boolean isFirstBoot() { 2690 return mFirstBoot; 2691 } 2692 2693 @Override 2694 public boolean isOnlyCoreApps() { 2695 return mOnlyCore; 2696 } 2697 2698 @Override 2699 public boolean isUpgrade() { 2700 return mIsUpgrade; 2701 } 2702 2703 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2704 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2705 2706 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2707 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2708 UserHandle.USER_SYSTEM); 2709 if (matches.size() == 1) { 2710 return matches.get(0).getComponentInfo().packageName; 2711 } else { 2712 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2713 return null; 2714 } 2715 } 2716 2717 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2718 synchronized (mPackages) { 2719 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2720 if (libraryEntry == null) { 2721 throw new IllegalStateException("Missing required shared library:" + libraryName); 2722 } 2723 return libraryEntry.apk; 2724 } 2725 } 2726 2727 private @NonNull String getRequiredInstallerLPr() { 2728 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2729 intent.addCategory(Intent.CATEGORY_DEFAULT); 2730 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2731 2732 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2733 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2734 UserHandle.USER_SYSTEM); 2735 if (matches.size() == 1) { 2736 ResolveInfo resolveInfo = matches.get(0); 2737 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2738 throw new RuntimeException("The installer must be a privileged app"); 2739 } 2740 return matches.get(0).getComponentInfo().packageName; 2741 } else { 2742 throw new RuntimeException("There must be exactly one installer; found " + matches); 2743 } 2744 } 2745 2746 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2747 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2748 2749 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2750 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2751 UserHandle.USER_SYSTEM); 2752 ResolveInfo best = null; 2753 final int N = matches.size(); 2754 for (int i = 0; i < N; i++) { 2755 final ResolveInfo cur = matches.get(i); 2756 final String packageName = cur.getComponentInfo().packageName; 2757 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2758 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2759 continue; 2760 } 2761 2762 if (best == null || cur.priority > best.priority) { 2763 best = cur; 2764 } 2765 } 2766 2767 if (best != null) { 2768 return best.getComponentInfo().getComponentName(); 2769 } else { 2770 throw new RuntimeException("There must be at least one intent filter verifier"); 2771 } 2772 } 2773 2774 private @Nullable ComponentName getEphemeralResolverLPr() { 2775 final String[] packageArray = 2776 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2777 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2778 if (DEBUG_EPHEMERAL) { 2779 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2780 } 2781 return null; 2782 } 2783 2784 final int resolveFlags = 2785 MATCH_DIRECT_BOOT_AWARE 2786 | MATCH_DIRECT_BOOT_UNAWARE 2787 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2788 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2789 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2790 resolveFlags, UserHandle.USER_SYSTEM); 2791 2792 final int N = resolvers.size(); 2793 if (N == 0) { 2794 if (DEBUG_EPHEMERAL) { 2795 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2796 } 2797 return null; 2798 } 2799 2800 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2801 for (int i = 0; i < N; i++) { 2802 final ResolveInfo info = resolvers.get(i); 2803 2804 if (info.serviceInfo == null) { 2805 continue; 2806 } 2807 2808 final String packageName = info.serviceInfo.packageName; 2809 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2810 if (DEBUG_EPHEMERAL) { 2811 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2812 + " pkg: " + packageName + ", info:" + info); 2813 } 2814 continue; 2815 } 2816 2817 if (DEBUG_EPHEMERAL) { 2818 Slog.v(TAG, "Ephemeral resolver found;" 2819 + " pkg: " + packageName + ", info:" + info); 2820 } 2821 return new ComponentName(packageName, info.serviceInfo.name); 2822 } 2823 if (DEBUG_EPHEMERAL) { 2824 Slog.v(TAG, "Ephemeral resolver NOT found"); 2825 } 2826 return null; 2827 } 2828 2829 private @Nullable ComponentName getEphemeralInstallerLPr() { 2830 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2831 intent.addCategory(Intent.CATEGORY_DEFAULT); 2832 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2833 2834 final int resolveFlags = 2835 MATCH_DIRECT_BOOT_AWARE 2836 | MATCH_DIRECT_BOOT_UNAWARE 2837 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2838 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2839 resolveFlags, UserHandle.USER_SYSTEM); 2840 if (matches.size() == 0) { 2841 return null; 2842 } else if (matches.size() == 1) { 2843 return matches.get(0).getComponentInfo().getComponentName(); 2844 } else { 2845 throw new RuntimeException( 2846 "There must be at most one ephemeral installer; found " + matches); 2847 } 2848 } 2849 2850 private void primeDomainVerificationsLPw(int userId) { 2851 if (DEBUG_DOMAIN_VERIFICATION) { 2852 Slog.d(TAG, "Priming domain verifications in user " + userId); 2853 } 2854 2855 SystemConfig systemConfig = SystemConfig.getInstance(); 2856 ArraySet<String> packages = systemConfig.getLinkedApps(); 2857 ArraySet<String> domains = new ArraySet<String>(); 2858 2859 for (String packageName : packages) { 2860 PackageParser.Package pkg = mPackages.get(packageName); 2861 if (pkg != null) { 2862 if (!pkg.isSystemApp()) { 2863 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2864 continue; 2865 } 2866 2867 domains.clear(); 2868 for (PackageParser.Activity a : pkg.activities) { 2869 for (ActivityIntentInfo filter : a.intents) { 2870 if (hasValidDomains(filter)) { 2871 domains.addAll(filter.getHostsList()); 2872 } 2873 } 2874 } 2875 2876 if (domains.size() > 0) { 2877 if (DEBUG_DOMAIN_VERIFICATION) { 2878 Slog.v(TAG, " + " + packageName); 2879 } 2880 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2881 // state w.r.t. the formal app-linkage "no verification attempted" state; 2882 // and then 'always' in the per-user state actually used for intent resolution. 2883 final IntentFilterVerificationInfo ivi; 2884 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2885 new ArrayList<String>(domains)); 2886 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2887 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2888 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2889 } else { 2890 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2891 + "' does not handle web links"); 2892 } 2893 } else { 2894 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2895 } 2896 } 2897 2898 scheduleWritePackageRestrictionsLocked(userId); 2899 scheduleWriteSettingsLocked(); 2900 } 2901 2902 private void applyFactoryDefaultBrowserLPw(int userId) { 2903 // The default browser app's package name is stored in a string resource, 2904 // with a product-specific overlay used for vendor customization. 2905 String browserPkg = mContext.getResources().getString( 2906 com.android.internal.R.string.default_browser); 2907 if (!TextUtils.isEmpty(browserPkg)) { 2908 // non-empty string => required to be a known package 2909 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2910 if (ps == null) { 2911 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2912 browserPkg = null; 2913 } else { 2914 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2915 } 2916 } 2917 2918 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2919 // default. If there's more than one, just leave everything alone. 2920 if (browserPkg == null) { 2921 calculateDefaultBrowserLPw(userId); 2922 } 2923 } 2924 2925 private void calculateDefaultBrowserLPw(int userId) { 2926 List<String> allBrowsers = resolveAllBrowserApps(userId); 2927 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2928 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2929 } 2930 2931 private List<String> resolveAllBrowserApps(int userId) { 2932 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2933 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2934 PackageManager.MATCH_ALL, userId); 2935 2936 final int count = list.size(); 2937 List<String> result = new ArrayList<String>(count); 2938 for (int i=0; i<count; i++) { 2939 ResolveInfo info = list.get(i); 2940 if (info.activityInfo == null 2941 || !info.handleAllWebDataURI 2942 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2943 || result.contains(info.activityInfo.packageName)) { 2944 continue; 2945 } 2946 result.add(info.activityInfo.packageName); 2947 } 2948 2949 return result; 2950 } 2951 2952 private boolean packageIsBrowser(String packageName, int userId) { 2953 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2954 PackageManager.MATCH_ALL, userId); 2955 final int N = list.size(); 2956 for (int i = 0; i < N; i++) { 2957 ResolveInfo info = list.get(i); 2958 if (packageName.equals(info.activityInfo.packageName)) { 2959 return true; 2960 } 2961 } 2962 return false; 2963 } 2964 2965 private void checkDefaultBrowser() { 2966 final int myUserId = UserHandle.myUserId(); 2967 final String packageName = getDefaultBrowserPackageName(myUserId); 2968 if (packageName != null) { 2969 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2970 if (info == null) { 2971 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2972 synchronized (mPackages) { 2973 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2974 } 2975 } 2976 } 2977 } 2978 2979 @Override 2980 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2981 throws RemoteException { 2982 try { 2983 return super.onTransact(code, data, reply, flags); 2984 } catch (RuntimeException e) { 2985 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2986 Slog.wtf(TAG, "Package Manager Crash", e); 2987 } 2988 throw e; 2989 } 2990 } 2991 2992 static int[] appendInts(int[] cur, int[] add) { 2993 if (add == null) return cur; 2994 if (cur == null) return add; 2995 final int N = add.length; 2996 for (int i=0; i<N; i++) { 2997 cur = appendInt(cur, add[i]); 2998 } 2999 return cur; 3000 } 3001 3002 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3003 if (!sUserManager.exists(userId)) return null; 3004 if (ps == null) { 3005 return null; 3006 } 3007 final PackageParser.Package p = ps.pkg; 3008 if (p == null) { 3009 return null; 3010 } 3011 3012 final PermissionsState permissionsState = ps.getPermissionsState(); 3013 3014 // Compute GIDs only if requested 3015 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3016 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3017 // Compute granted permissions only if package has requested permissions 3018 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3019 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3020 final PackageUserState state = ps.readUserState(userId); 3021 3022 return PackageParser.generatePackageInfo(p, gids, flags, 3023 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3024 } 3025 3026 @Override 3027 public void checkPackageStartable(String packageName, int userId) { 3028 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3029 3030 synchronized (mPackages) { 3031 final PackageSetting ps = mSettings.mPackages.get(packageName); 3032 if (ps == null) { 3033 throw new SecurityException("Package " + packageName + " was not found!"); 3034 } 3035 3036 if (!ps.getInstalled(userId)) { 3037 throw new SecurityException( 3038 "Package " + packageName + " was not installed for user " + userId + "!"); 3039 } 3040 3041 if (mSafeMode && !ps.isSystem()) { 3042 throw new SecurityException("Package " + packageName + " not a system app!"); 3043 } 3044 3045 if (mFrozenPackages.contains(packageName)) { 3046 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3047 } 3048 3049 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3050 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3051 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3052 } 3053 } 3054 } 3055 3056 @Override 3057 public boolean isPackageAvailable(String packageName, int userId) { 3058 if (!sUserManager.exists(userId)) return false; 3059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3060 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3061 synchronized (mPackages) { 3062 PackageParser.Package p = mPackages.get(packageName); 3063 if (p != null) { 3064 final PackageSetting ps = (PackageSetting) p.mExtras; 3065 if (ps != null) { 3066 final PackageUserState state = ps.readUserState(userId); 3067 if (state != null) { 3068 return PackageParser.isAvailable(state); 3069 } 3070 } 3071 } 3072 } 3073 return false; 3074 } 3075 3076 @Override 3077 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3078 if (!sUserManager.exists(userId)) return null; 3079 flags = updateFlagsForPackage(flags, userId, packageName); 3080 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3081 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3082 // reader 3083 synchronized (mPackages) { 3084 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3085 PackageParser.Package p = null; 3086 if (matchFactoryOnly) { 3087 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3088 if (ps != null) { 3089 return generatePackageInfo(ps, flags, userId); 3090 } 3091 } 3092 if (p == null) { 3093 p = mPackages.get(packageName); 3094 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3095 return null; 3096 } 3097 } 3098 if (DEBUG_PACKAGE_INFO) 3099 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3100 if (p != null) { 3101 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3102 } 3103 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3104 final PackageSetting ps = mSettings.mPackages.get(packageName); 3105 return generatePackageInfo(ps, flags, userId); 3106 } 3107 } 3108 return null; 3109 } 3110 3111 @Override 3112 public String[] currentToCanonicalPackageNames(String[] names) { 3113 String[] out = new String[names.length]; 3114 // reader 3115 synchronized (mPackages) { 3116 for (int i=names.length-1; i>=0; i--) { 3117 PackageSetting ps = mSettings.mPackages.get(names[i]); 3118 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3119 } 3120 } 3121 return out; 3122 } 3123 3124 @Override 3125 public String[] canonicalToCurrentPackageNames(String[] names) { 3126 String[] out = new String[names.length]; 3127 // reader 3128 synchronized (mPackages) { 3129 for (int i=names.length-1; i>=0; i--) { 3130 String cur = mSettings.mRenamedPackages.get(names[i]); 3131 out[i] = cur != null ? cur : names[i]; 3132 } 3133 } 3134 return out; 3135 } 3136 3137 @Override 3138 public int getPackageUid(String packageName, int flags, int userId) { 3139 if (!sUserManager.exists(userId)) return -1; 3140 flags = updateFlagsForPackage(flags, userId, packageName); 3141 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3142 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3143 3144 // reader 3145 synchronized (mPackages) { 3146 final PackageParser.Package p = mPackages.get(packageName); 3147 if (p != null && p.isMatch(flags)) { 3148 return UserHandle.getUid(userId, p.applicationInfo.uid); 3149 } 3150 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3151 final PackageSetting ps = mSettings.mPackages.get(packageName); 3152 if (ps != null && ps.isMatch(flags)) { 3153 return UserHandle.getUid(userId, ps.appId); 3154 } 3155 } 3156 } 3157 3158 return -1; 3159 } 3160 3161 @Override 3162 public int[] getPackageGids(String packageName, int flags, int userId) { 3163 if (!sUserManager.exists(userId)) return null; 3164 flags = updateFlagsForPackage(flags, userId, packageName); 3165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3166 false /* requireFullPermission */, false /* checkShell */, 3167 "getPackageGids"); 3168 3169 // reader 3170 synchronized (mPackages) { 3171 final PackageParser.Package p = mPackages.get(packageName); 3172 if (p != null && p.isMatch(flags)) { 3173 PackageSetting ps = (PackageSetting) p.mExtras; 3174 return ps.getPermissionsState().computeGids(userId); 3175 } 3176 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3177 final PackageSetting ps = mSettings.mPackages.get(packageName); 3178 if (ps != null && ps.isMatch(flags)) { 3179 return ps.getPermissionsState().computeGids(userId); 3180 } 3181 } 3182 } 3183 3184 return null; 3185 } 3186 3187 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3188 if (bp.perm != null) { 3189 return PackageParser.generatePermissionInfo(bp.perm, flags); 3190 } 3191 PermissionInfo pi = new PermissionInfo(); 3192 pi.name = bp.name; 3193 pi.packageName = bp.sourcePackage; 3194 pi.nonLocalizedLabel = bp.name; 3195 pi.protectionLevel = bp.protectionLevel; 3196 return pi; 3197 } 3198 3199 @Override 3200 public PermissionInfo getPermissionInfo(String name, int flags) { 3201 // reader 3202 synchronized (mPackages) { 3203 final BasePermission p = mSettings.mPermissions.get(name); 3204 if (p != null) { 3205 return generatePermissionInfo(p, flags); 3206 } 3207 return null; 3208 } 3209 } 3210 3211 @Override 3212 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3213 int flags) { 3214 // reader 3215 synchronized (mPackages) { 3216 if (group != null && !mPermissionGroups.containsKey(group)) { 3217 // This is thrown as NameNotFoundException 3218 return null; 3219 } 3220 3221 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3222 for (BasePermission p : mSettings.mPermissions.values()) { 3223 if (group == null) { 3224 if (p.perm == null || p.perm.info.group == null) { 3225 out.add(generatePermissionInfo(p, flags)); 3226 } 3227 } else { 3228 if (p.perm != null && group.equals(p.perm.info.group)) { 3229 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3230 } 3231 } 3232 } 3233 return new ParceledListSlice<>(out); 3234 } 3235 } 3236 3237 @Override 3238 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3239 // reader 3240 synchronized (mPackages) { 3241 return PackageParser.generatePermissionGroupInfo( 3242 mPermissionGroups.get(name), flags); 3243 } 3244 } 3245 3246 @Override 3247 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3248 // reader 3249 synchronized (mPackages) { 3250 final int N = mPermissionGroups.size(); 3251 ArrayList<PermissionGroupInfo> out 3252 = new ArrayList<PermissionGroupInfo>(N); 3253 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3254 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3255 } 3256 return new ParceledListSlice<>(out); 3257 } 3258 } 3259 3260 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3261 int userId) { 3262 if (!sUserManager.exists(userId)) return null; 3263 PackageSetting ps = mSettings.mPackages.get(packageName); 3264 if (ps != null) { 3265 if (ps.pkg == null) { 3266 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3267 if (pInfo != null) { 3268 return pInfo.applicationInfo; 3269 } 3270 return null; 3271 } 3272 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3273 ps.readUserState(userId), userId); 3274 } 3275 return null; 3276 } 3277 3278 @Override 3279 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3280 if (!sUserManager.exists(userId)) return null; 3281 flags = updateFlagsForApplication(flags, userId, packageName); 3282 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3283 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3284 // writer 3285 synchronized (mPackages) { 3286 PackageParser.Package p = mPackages.get(packageName); 3287 if (DEBUG_PACKAGE_INFO) Log.v( 3288 TAG, "getApplicationInfo " + packageName 3289 + ": " + p); 3290 if (p != null) { 3291 PackageSetting ps = mSettings.mPackages.get(packageName); 3292 if (ps == null) return null; 3293 // Note: isEnabledLP() does not apply here - always return info 3294 return PackageParser.generateApplicationInfo( 3295 p, flags, ps.readUserState(userId), userId); 3296 } 3297 if ("android".equals(packageName)||"system".equals(packageName)) { 3298 return mAndroidApplication; 3299 } 3300 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3301 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3302 } 3303 } 3304 return null; 3305 } 3306 3307 @Override 3308 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3309 final IPackageDataObserver observer) { 3310 mContext.enforceCallingOrSelfPermission( 3311 android.Manifest.permission.CLEAR_APP_CACHE, null); 3312 // Queue up an async operation since clearing cache may take a little while. 3313 mHandler.post(new Runnable() { 3314 public void run() { 3315 mHandler.removeCallbacks(this); 3316 boolean success = true; 3317 synchronized (mInstallLock) { 3318 try { 3319 mInstaller.freeCache(volumeUuid, freeStorageSize); 3320 } catch (InstallerException e) { 3321 Slog.w(TAG, "Couldn't clear application caches: " + e); 3322 success = false; 3323 } 3324 } 3325 if (observer != null) { 3326 try { 3327 observer.onRemoveCompleted(null, success); 3328 } catch (RemoteException e) { 3329 Slog.w(TAG, "RemoveException when invoking call back"); 3330 } 3331 } 3332 } 3333 }); 3334 } 3335 3336 @Override 3337 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3338 final IntentSender pi) { 3339 mContext.enforceCallingOrSelfPermission( 3340 android.Manifest.permission.CLEAR_APP_CACHE, null); 3341 // Queue up an async operation since clearing cache may take a little while. 3342 mHandler.post(new Runnable() { 3343 public void run() { 3344 mHandler.removeCallbacks(this); 3345 boolean success = true; 3346 synchronized (mInstallLock) { 3347 try { 3348 mInstaller.freeCache(volumeUuid, freeStorageSize); 3349 } catch (InstallerException e) { 3350 Slog.w(TAG, "Couldn't clear application caches: " + e); 3351 success = false; 3352 } 3353 } 3354 if(pi != null) { 3355 try { 3356 // Callback via pending intent 3357 int code = success ? 1 : 0; 3358 pi.sendIntent(null, code, null, 3359 null, null); 3360 } catch (SendIntentException e1) { 3361 Slog.i(TAG, "Failed to send pending intent"); 3362 } 3363 } 3364 } 3365 }); 3366 } 3367 3368 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3369 synchronized (mInstallLock) { 3370 try { 3371 mInstaller.freeCache(volumeUuid, freeStorageSize); 3372 } catch (InstallerException e) { 3373 throw new IOException("Failed to free enough space", e); 3374 } 3375 } 3376 } 3377 3378 /** 3379 * Update given flags based on encryption status of current user. 3380 */ 3381 private int updateFlags(int flags, int userId) { 3382 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3383 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3384 // Caller expressed an explicit opinion about what encryption 3385 // aware/unaware components they want to see, so fall through and 3386 // give them what they want 3387 } else { 3388 // Caller expressed no opinion, so match based on user state 3389 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3390 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3391 } else { 3392 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3393 } 3394 } 3395 return flags; 3396 } 3397 3398 private UserManagerInternal getUserManagerInternal() { 3399 if (mUserManagerInternal == null) { 3400 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3401 } 3402 return mUserManagerInternal; 3403 } 3404 3405 /** 3406 * Update given flags when being used to request {@link PackageInfo}. 3407 */ 3408 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3409 boolean triaged = true; 3410 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3411 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3412 // Caller is asking for component details, so they'd better be 3413 // asking for specific encryption matching behavior, or be triaged 3414 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3415 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3416 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3417 triaged = false; 3418 } 3419 } 3420 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3421 | PackageManager.MATCH_SYSTEM_ONLY 3422 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3423 triaged = false; 3424 } 3425 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3426 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3427 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3428 } 3429 return updateFlags(flags, userId); 3430 } 3431 3432 /** 3433 * Update given flags when being used to request {@link ApplicationInfo}. 3434 */ 3435 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3436 return updateFlagsForPackage(flags, userId, cookie); 3437 } 3438 3439 /** 3440 * Update given flags when being used to request {@link ComponentInfo}. 3441 */ 3442 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3443 if (cookie instanceof Intent) { 3444 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3445 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3446 } 3447 } 3448 3449 boolean triaged = true; 3450 // Caller is asking for component details, so they'd better be 3451 // asking for specific encryption matching behavior, or be triaged 3452 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3453 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3454 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3455 triaged = false; 3456 } 3457 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3458 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3459 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3460 } 3461 3462 return updateFlags(flags, userId); 3463 } 3464 3465 /** 3466 * Update given flags when being used to request {@link ResolveInfo}. 3467 */ 3468 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3469 // Safe mode means we shouldn't match any third-party components 3470 if (mSafeMode) { 3471 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3472 } 3473 3474 return updateFlagsForComponent(flags, userId, cookie); 3475 } 3476 3477 @Override 3478 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3479 if (!sUserManager.exists(userId)) return null; 3480 flags = updateFlagsForComponent(flags, userId, component); 3481 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3482 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3483 synchronized (mPackages) { 3484 PackageParser.Activity a = mActivities.mActivities.get(component); 3485 3486 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3487 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3488 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3489 if (ps == null) return null; 3490 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3491 userId); 3492 } 3493 if (mResolveComponentName.equals(component)) { 3494 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3495 new PackageUserState(), userId); 3496 } 3497 } 3498 return null; 3499 } 3500 3501 @Override 3502 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3503 String resolvedType) { 3504 synchronized (mPackages) { 3505 if (component.equals(mResolveComponentName)) { 3506 // The resolver supports EVERYTHING! 3507 return true; 3508 } 3509 PackageParser.Activity a = mActivities.mActivities.get(component); 3510 if (a == null) { 3511 return false; 3512 } 3513 for (int i=0; i<a.intents.size(); i++) { 3514 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3515 intent.getData(), intent.getCategories(), TAG) >= 0) { 3516 return true; 3517 } 3518 } 3519 return false; 3520 } 3521 } 3522 3523 @Override 3524 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3525 if (!sUserManager.exists(userId)) return null; 3526 flags = updateFlagsForComponent(flags, userId, component); 3527 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3528 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3529 synchronized (mPackages) { 3530 PackageParser.Activity a = mReceivers.mActivities.get(component); 3531 if (DEBUG_PACKAGE_INFO) Log.v( 3532 TAG, "getReceiverInfo " + component + ": " + a); 3533 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3534 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3535 if (ps == null) return null; 3536 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3537 userId); 3538 } 3539 } 3540 return null; 3541 } 3542 3543 @Override 3544 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3545 if (!sUserManager.exists(userId)) return null; 3546 flags = updateFlagsForComponent(flags, userId, component); 3547 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3548 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3549 synchronized (mPackages) { 3550 PackageParser.Service s = mServices.mServices.get(component); 3551 if (DEBUG_PACKAGE_INFO) Log.v( 3552 TAG, "getServiceInfo " + component + ": " + s); 3553 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3554 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3555 if (ps == null) return null; 3556 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3557 userId); 3558 } 3559 } 3560 return null; 3561 } 3562 3563 @Override 3564 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3565 if (!sUserManager.exists(userId)) return null; 3566 flags = updateFlagsForComponent(flags, userId, component); 3567 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3568 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3569 synchronized (mPackages) { 3570 PackageParser.Provider p = mProviders.mProviders.get(component); 3571 if (DEBUG_PACKAGE_INFO) Log.v( 3572 TAG, "getProviderInfo " + component + ": " + p); 3573 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3574 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3575 if (ps == null) return null; 3576 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3577 userId); 3578 } 3579 } 3580 return null; 3581 } 3582 3583 @Override 3584 public String[] getSystemSharedLibraryNames() { 3585 Set<String> libSet; 3586 synchronized (mPackages) { 3587 libSet = mSharedLibraries.keySet(); 3588 int size = libSet.size(); 3589 if (size > 0) { 3590 String[] libs = new String[size]; 3591 libSet.toArray(libs); 3592 return libs; 3593 } 3594 } 3595 return null; 3596 } 3597 3598 @Override 3599 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3600 synchronized (mPackages) { 3601 return mServicesSystemSharedLibraryPackageName; 3602 } 3603 } 3604 3605 @Override 3606 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3607 synchronized (mPackages) { 3608 return mSharedSystemSharedLibraryPackageName; 3609 } 3610 } 3611 3612 @Override 3613 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3614 synchronized (mPackages) { 3615 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3616 3617 final FeatureInfo fi = new FeatureInfo(); 3618 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3619 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3620 res.add(fi); 3621 3622 return new ParceledListSlice<>(res); 3623 } 3624 } 3625 3626 @Override 3627 public boolean hasSystemFeature(String name, int version) { 3628 synchronized (mPackages) { 3629 final FeatureInfo feat = mAvailableFeatures.get(name); 3630 if (feat == null) { 3631 return false; 3632 } else { 3633 return feat.version >= version; 3634 } 3635 } 3636 } 3637 3638 @Override 3639 public int checkPermission(String permName, String pkgName, int userId) { 3640 if (!sUserManager.exists(userId)) { 3641 return PackageManager.PERMISSION_DENIED; 3642 } 3643 3644 synchronized (mPackages) { 3645 final PackageParser.Package p = mPackages.get(pkgName); 3646 if (p != null && p.mExtras != null) { 3647 final PackageSetting ps = (PackageSetting) p.mExtras; 3648 final PermissionsState permissionsState = ps.getPermissionsState(); 3649 if (permissionsState.hasPermission(permName, userId)) { 3650 return PackageManager.PERMISSION_GRANTED; 3651 } 3652 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3653 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3654 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3655 return PackageManager.PERMISSION_GRANTED; 3656 } 3657 } 3658 } 3659 3660 return PackageManager.PERMISSION_DENIED; 3661 } 3662 3663 @Override 3664 public int checkUidPermission(String permName, int uid) { 3665 final int userId = UserHandle.getUserId(uid); 3666 3667 if (!sUserManager.exists(userId)) { 3668 return PackageManager.PERMISSION_DENIED; 3669 } 3670 3671 synchronized (mPackages) { 3672 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3673 if (obj != null) { 3674 final SettingBase ps = (SettingBase) obj; 3675 final PermissionsState permissionsState = ps.getPermissionsState(); 3676 if (permissionsState.hasPermission(permName, userId)) { 3677 return PackageManager.PERMISSION_GRANTED; 3678 } 3679 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3680 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3681 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3682 return PackageManager.PERMISSION_GRANTED; 3683 } 3684 } else { 3685 ArraySet<String> perms = mSystemPermissions.get(uid); 3686 if (perms != null) { 3687 if (perms.contains(permName)) { 3688 return PackageManager.PERMISSION_GRANTED; 3689 } 3690 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3691 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3692 return PackageManager.PERMISSION_GRANTED; 3693 } 3694 } 3695 } 3696 } 3697 3698 return PackageManager.PERMISSION_DENIED; 3699 } 3700 3701 @Override 3702 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3703 if (UserHandle.getCallingUserId() != userId) { 3704 mContext.enforceCallingPermission( 3705 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3706 "isPermissionRevokedByPolicy for user " + userId); 3707 } 3708 3709 if (checkPermission(permission, packageName, userId) 3710 == PackageManager.PERMISSION_GRANTED) { 3711 return false; 3712 } 3713 3714 final long identity = Binder.clearCallingIdentity(); 3715 try { 3716 final int flags = getPermissionFlags(permission, packageName, userId); 3717 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3718 } finally { 3719 Binder.restoreCallingIdentity(identity); 3720 } 3721 } 3722 3723 @Override 3724 public String getPermissionControllerPackageName() { 3725 synchronized (mPackages) { 3726 return mRequiredInstallerPackage; 3727 } 3728 } 3729 3730 /** 3731 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3732 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3733 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3734 * @param message the message to log on security exception 3735 */ 3736 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3737 boolean checkShell, String message) { 3738 if (userId < 0) { 3739 throw new IllegalArgumentException("Invalid userId " + userId); 3740 } 3741 if (checkShell) { 3742 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3743 } 3744 if (userId == UserHandle.getUserId(callingUid)) return; 3745 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3746 if (requireFullPermission) { 3747 mContext.enforceCallingOrSelfPermission( 3748 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3749 } else { 3750 try { 3751 mContext.enforceCallingOrSelfPermission( 3752 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3753 } catch (SecurityException se) { 3754 mContext.enforceCallingOrSelfPermission( 3755 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3756 } 3757 } 3758 } 3759 } 3760 3761 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3762 if (callingUid == Process.SHELL_UID) { 3763 if (userHandle >= 0 3764 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3765 throw new SecurityException("Shell does not have permission to access user " 3766 + userHandle); 3767 } else if (userHandle < 0) { 3768 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3769 + Debug.getCallers(3)); 3770 } 3771 } 3772 } 3773 3774 private BasePermission findPermissionTreeLP(String permName) { 3775 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3776 if (permName.startsWith(bp.name) && 3777 permName.length() > bp.name.length() && 3778 permName.charAt(bp.name.length()) == '.') { 3779 return bp; 3780 } 3781 } 3782 return null; 3783 } 3784 3785 private BasePermission checkPermissionTreeLP(String permName) { 3786 if (permName != null) { 3787 BasePermission bp = findPermissionTreeLP(permName); 3788 if (bp != null) { 3789 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3790 return bp; 3791 } 3792 throw new SecurityException("Calling uid " 3793 + Binder.getCallingUid() 3794 + " is not allowed to add to permission tree " 3795 + bp.name + " owned by uid " + bp.uid); 3796 } 3797 } 3798 throw new SecurityException("No permission tree found for " + permName); 3799 } 3800 3801 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3802 if (s1 == null) { 3803 return s2 == null; 3804 } 3805 if (s2 == null) { 3806 return false; 3807 } 3808 if (s1.getClass() != s2.getClass()) { 3809 return false; 3810 } 3811 return s1.equals(s2); 3812 } 3813 3814 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3815 if (pi1.icon != pi2.icon) return false; 3816 if (pi1.logo != pi2.logo) return false; 3817 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3818 if (!compareStrings(pi1.name, pi2.name)) return false; 3819 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3820 // We'll take care of setting this one. 3821 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3822 // These are not currently stored in settings. 3823 //if (!compareStrings(pi1.group, pi2.group)) return false; 3824 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3825 //if (pi1.labelRes != pi2.labelRes) return false; 3826 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3827 return true; 3828 } 3829 3830 int permissionInfoFootprint(PermissionInfo info) { 3831 int size = info.name.length(); 3832 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3833 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3834 return size; 3835 } 3836 3837 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3838 int size = 0; 3839 for (BasePermission perm : mSettings.mPermissions.values()) { 3840 if (perm.uid == tree.uid) { 3841 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3842 } 3843 } 3844 return size; 3845 } 3846 3847 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3848 // We calculate the max size of permissions defined by this uid and throw 3849 // if that plus the size of 'info' would exceed our stated maximum. 3850 if (tree.uid != Process.SYSTEM_UID) { 3851 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3852 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3853 throw new SecurityException("Permission tree size cap exceeded"); 3854 } 3855 } 3856 } 3857 3858 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3859 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3860 throw new SecurityException("Label must be specified in permission"); 3861 } 3862 BasePermission tree = checkPermissionTreeLP(info.name); 3863 BasePermission bp = mSettings.mPermissions.get(info.name); 3864 boolean added = bp == null; 3865 boolean changed = true; 3866 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3867 if (added) { 3868 enforcePermissionCapLocked(info, tree); 3869 bp = new BasePermission(info.name, tree.sourcePackage, 3870 BasePermission.TYPE_DYNAMIC); 3871 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3872 throw new SecurityException( 3873 "Not allowed to modify non-dynamic permission " 3874 + info.name); 3875 } else { 3876 if (bp.protectionLevel == fixedLevel 3877 && bp.perm.owner.equals(tree.perm.owner) 3878 && bp.uid == tree.uid 3879 && comparePermissionInfos(bp.perm.info, info)) { 3880 changed = false; 3881 } 3882 } 3883 bp.protectionLevel = fixedLevel; 3884 info = new PermissionInfo(info); 3885 info.protectionLevel = fixedLevel; 3886 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3887 bp.perm.info.packageName = tree.perm.info.packageName; 3888 bp.uid = tree.uid; 3889 if (added) { 3890 mSettings.mPermissions.put(info.name, bp); 3891 } 3892 if (changed) { 3893 if (!async) { 3894 mSettings.writeLPr(); 3895 } else { 3896 scheduleWriteSettingsLocked(); 3897 } 3898 } 3899 return added; 3900 } 3901 3902 @Override 3903 public boolean addPermission(PermissionInfo info) { 3904 synchronized (mPackages) { 3905 return addPermissionLocked(info, false); 3906 } 3907 } 3908 3909 @Override 3910 public boolean addPermissionAsync(PermissionInfo info) { 3911 synchronized (mPackages) { 3912 return addPermissionLocked(info, true); 3913 } 3914 } 3915 3916 @Override 3917 public void removePermission(String name) { 3918 synchronized (mPackages) { 3919 checkPermissionTreeLP(name); 3920 BasePermission bp = mSettings.mPermissions.get(name); 3921 if (bp != null) { 3922 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3923 throw new SecurityException( 3924 "Not allowed to modify non-dynamic permission " 3925 + name); 3926 } 3927 mSettings.mPermissions.remove(name); 3928 mSettings.writeLPr(); 3929 } 3930 } 3931 } 3932 3933 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3934 BasePermission bp) { 3935 int index = pkg.requestedPermissions.indexOf(bp.name); 3936 if (index == -1) { 3937 throw new SecurityException("Package " + pkg.packageName 3938 + " has not requested permission " + bp.name); 3939 } 3940 if (!bp.isRuntime() && !bp.isDevelopment()) { 3941 throw new SecurityException("Permission " + bp.name 3942 + " is not a changeable permission type"); 3943 } 3944 } 3945 3946 @Override 3947 public void grantRuntimePermission(String packageName, String name, final int userId) { 3948 if (!sUserManager.exists(userId)) { 3949 Log.e(TAG, "No such user:" + userId); 3950 return; 3951 } 3952 3953 mContext.enforceCallingOrSelfPermission( 3954 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3955 "grantRuntimePermission"); 3956 3957 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3958 true /* requireFullPermission */, true /* checkShell */, 3959 "grantRuntimePermission"); 3960 3961 final int uid; 3962 final SettingBase sb; 3963 3964 synchronized (mPackages) { 3965 final PackageParser.Package pkg = mPackages.get(packageName); 3966 if (pkg == null) { 3967 throw new IllegalArgumentException("Unknown package: " + packageName); 3968 } 3969 3970 final BasePermission bp = mSettings.mPermissions.get(name); 3971 if (bp == null) { 3972 throw new IllegalArgumentException("Unknown permission: " + name); 3973 } 3974 3975 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3976 3977 // If a permission review is required for legacy apps we represent 3978 // their permissions as always granted runtime ones since we need 3979 // to keep the review required permission flag per user while an 3980 // install permission's state is shared across all users. 3981 if (Build.PERMISSIONS_REVIEW_REQUIRED 3982 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3983 && bp.isRuntime()) { 3984 return; 3985 } 3986 3987 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3988 sb = (SettingBase) pkg.mExtras; 3989 if (sb == null) { 3990 throw new IllegalArgumentException("Unknown package: " + packageName); 3991 } 3992 3993 final PermissionsState permissionsState = sb.getPermissionsState(); 3994 3995 final int flags = permissionsState.getPermissionFlags(name, userId); 3996 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 3997 throw new SecurityException("Cannot grant system fixed permission " 3998 + name + " for package " + packageName); 3999 } 4000 4001 if (bp.isDevelopment()) { 4002 // Development permissions must be handled specially, since they are not 4003 // normal runtime permissions. For now they apply to all users. 4004 if (permissionsState.grantInstallPermission(bp) != 4005 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4006 scheduleWriteSettingsLocked(); 4007 } 4008 return; 4009 } 4010 4011 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4012 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4013 return; 4014 } 4015 4016 final int result = permissionsState.grantRuntimePermission(bp, userId); 4017 switch (result) { 4018 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4019 return; 4020 } 4021 4022 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4023 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4024 mHandler.post(new Runnable() { 4025 @Override 4026 public void run() { 4027 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4028 } 4029 }); 4030 } 4031 break; 4032 } 4033 4034 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4035 4036 // Not critical if that is lost - app has to request again. 4037 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4038 } 4039 4040 // Only need to do this if user is initialized. Otherwise it's a new user 4041 // and there are no processes running as the user yet and there's no need 4042 // to make an expensive call to remount processes for the changed permissions. 4043 if (READ_EXTERNAL_STORAGE.equals(name) 4044 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4045 final long token = Binder.clearCallingIdentity(); 4046 try { 4047 if (sUserManager.isInitialized(userId)) { 4048 MountServiceInternal mountServiceInternal = LocalServices.getService( 4049 MountServiceInternal.class); 4050 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4051 } 4052 } finally { 4053 Binder.restoreCallingIdentity(token); 4054 } 4055 } 4056 } 4057 4058 @Override 4059 public void revokeRuntimePermission(String packageName, String name, int userId) { 4060 if (!sUserManager.exists(userId)) { 4061 Log.e(TAG, "No such user:" + userId); 4062 return; 4063 } 4064 4065 mContext.enforceCallingOrSelfPermission( 4066 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4067 "revokeRuntimePermission"); 4068 4069 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4070 true /* requireFullPermission */, true /* checkShell */, 4071 "revokeRuntimePermission"); 4072 4073 final int appId; 4074 4075 synchronized (mPackages) { 4076 final PackageParser.Package pkg = mPackages.get(packageName); 4077 if (pkg == null) { 4078 throw new IllegalArgumentException("Unknown package: " + packageName); 4079 } 4080 4081 final BasePermission bp = mSettings.mPermissions.get(name); 4082 if (bp == null) { 4083 throw new IllegalArgumentException("Unknown permission: " + name); 4084 } 4085 4086 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4087 4088 // If a permission review is required for legacy apps we represent 4089 // their permissions as always granted runtime ones since we need 4090 // to keep the review required permission flag per user while an 4091 // install permission's state is shared across all users. 4092 if (Build.PERMISSIONS_REVIEW_REQUIRED 4093 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4094 && bp.isRuntime()) { 4095 return; 4096 } 4097 4098 SettingBase sb = (SettingBase) pkg.mExtras; 4099 if (sb == null) { 4100 throw new IllegalArgumentException("Unknown package: " + packageName); 4101 } 4102 4103 final PermissionsState permissionsState = sb.getPermissionsState(); 4104 4105 final int flags = permissionsState.getPermissionFlags(name, userId); 4106 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4107 throw new SecurityException("Cannot revoke system fixed permission " 4108 + name + " for package " + packageName); 4109 } 4110 4111 if (bp.isDevelopment()) { 4112 // Development permissions must be handled specially, since they are not 4113 // normal runtime permissions. For now they apply to all users. 4114 if (permissionsState.revokeInstallPermission(bp) != 4115 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4116 scheduleWriteSettingsLocked(); 4117 } 4118 return; 4119 } 4120 4121 if (permissionsState.revokeRuntimePermission(bp, userId) == 4122 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4123 return; 4124 } 4125 4126 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4127 4128 // Critical, after this call app should never have the permission. 4129 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4130 4131 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4132 } 4133 4134 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4135 } 4136 4137 @Override 4138 public void resetRuntimePermissions() { 4139 mContext.enforceCallingOrSelfPermission( 4140 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4141 "revokeRuntimePermission"); 4142 4143 int callingUid = Binder.getCallingUid(); 4144 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4145 mContext.enforceCallingOrSelfPermission( 4146 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4147 "resetRuntimePermissions"); 4148 } 4149 4150 synchronized (mPackages) { 4151 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4152 for (int userId : UserManagerService.getInstance().getUserIds()) { 4153 final int packageCount = mPackages.size(); 4154 for (int i = 0; i < packageCount; i++) { 4155 PackageParser.Package pkg = mPackages.valueAt(i); 4156 if (!(pkg.mExtras instanceof PackageSetting)) { 4157 continue; 4158 } 4159 PackageSetting ps = (PackageSetting) pkg.mExtras; 4160 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4161 } 4162 } 4163 } 4164 } 4165 4166 @Override 4167 public int getPermissionFlags(String name, String packageName, int userId) { 4168 if (!sUserManager.exists(userId)) { 4169 return 0; 4170 } 4171 4172 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4173 4174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4175 true /* requireFullPermission */, false /* checkShell */, 4176 "getPermissionFlags"); 4177 4178 synchronized (mPackages) { 4179 final PackageParser.Package pkg = mPackages.get(packageName); 4180 if (pkg == null) { 4181 return 0; 4182 } 4183 4184 final BasePermission bp = mSettings.mPermissions.get(name); 4185 if (bp == null) { 4186 return 0; 4187 } 4188 4189 SettingBase sb = (SettingBase) pkg.mExtras; 4190 if (sb == null) { 4191 return 0; 4192 } 4193 4194 PermissionsState permissionsState = sb.getPermissionsState(); 4195 return permissionsState.getPermissionFlags(name, userId); 4196 } 4197 } 4198 4199 @Override 4200 public void updatePermissionFlags(String name, String packageName, int flagMask, 4201 int flagValues, int userId) { 4202 if (!sUserManager.exists(userId)) { 4203 return; 4204 } 4205 4206 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4207 4208 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4209 true /* requireFullPermission */, true /* checkShell */, 4210 "updatePermissionFlags"); 4211 4212 // Only the system can change these flags and nothing else. 4213 if (getCallingUid() != Process.SYSTEM_UID) { 4214 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4215 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4216 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4217 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4218 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4219 } 4220 4221 synchronized (mPackages) { 4222 final PackageParser.Package pkg = mPackages.get(packageName); 4223 if (pkg == null) { 4224 throw new IllegalArgumentException("Unknown package: " + packageName); 4225 } 4226 4227 final BasePermission bp = mSettings.mPermissions.get(name); 4228 if (bp == null) { 4229 throw new IllegalArgumentException("Unknown permission: " + name); 4230 } 4231 4232 SettingBase sb = (SettingBase) pkg.mExtras; 4233 if (sb == null) { 4234 throw new IllegalArgumentException("Unknown package: " + packageName); 4235 } 4236 4237 PermissionsState permissionsState = sb.getPermissionsState(); 4238 4239 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4240 4241 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4242 // Install and runtime permissions are stored in different places, 4243 // so figure out what permission changed and persist the change. 4244 if (permissionsState.getInstallPermissionState(name) != null) { 4245 scheduleWriteSettingsLocked(); 4246 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4247 || hadState) { 4248 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4249 } 4250 } 4251 } 4252 } 4253 4254 /** 4255 * Update the permission flags for all packages and runtime permissions of a user in order 4256 * to allow device or profile owner to remove POLICY_FIXED. 4257 */ 4258 @Override 4259 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4260 if (!sUserManager.exists(userId)) { 4261 return; 4262 } 4263 4264 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4265 4266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4267 true /* requireFullPermission */, true /* checkShell */, 4268 "updatePermissionFlagsForAllApps"); 4269 4270 // Only the system can change system fixed flags. 4271 if (getCallingUid() != Process.SYSTEM_UID) { 4272 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4273 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4274 } 4275 4276 synchronized (mPackages) { 4277 boolean changed = false; 4278 final int packageCount = mPackages.size(); 4279 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4280 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4281 SettingBase sb = (SettingBase) pkg.mExtras; 4282 if (sb == null) { 4283 continue; 4284 } 4285 PermissionsState permissionsState = sb.getPermissionsState(); 4286 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4287 userId, flagMask, flagValues); 4288 } 4289 if (changed) { 4290 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4291 } 4292 } 4293 } 4294 4295 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4296 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4297 != PackageManager.PERMISSION_GRANTED 4298 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4299 != PackageManager.PERMISSION_GRANTED) { 4300 throw new SecurityException(message + " requires " 4301 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4302 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4303 } 4304 } 4305 4306 @Override 4307 public boolean shouldShowRequestPermissionRationale(String permissionName, 4308 String packageName, int userId) { 4309 if (UserHandle.getCallingUserId() != userId) { 4310 mContext.enforceCallingPermission( 4311 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4312 "canShowRequestPermissionRationale for user " + userId); 4313 } 4314 4315 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4316 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4317 return false; 4318 } 4319 4320 if (checkPermission(permissionName, packageName, userId) 4321 == PackageManager.PERMISSION_GRANTED) { 4322 return false; 4323 } 4324 4325 final int flags; 4326 4327 final long identity = Binder.clearCallingIdentity(); 4328 try { 4329 flags = getPermissionFlags(permissionName, 4330 packageName, userId); 4331 } finally { 4332 Binder.restoreCallingIdentity(identity); 4333 } 4334 4335 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4336 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4337 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4338 4339 if ((flags & fixedFlags) != 0) { 4340 return false; 4341 } 4342 4343 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4344 } 4345 4346 @Override 4347 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4348 mContext.enforceCallingOrSelfPermission( 4349 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4350 "addOnPermissionsChangeListener"); 4351 4352 synchronized (mPackages) { 4353 mOnPermissionChangeListeners.addListenerLocked(listener); 4354 } 4355 } 4356 4357 @Override 4358 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4359 synchronized (mPackages) { 4360 mOnPermissionChangeListeners.removeListenerLocked(listener); 4361 } 4362 } 4363 4364 @Override 4365 public boolean isProtectedBroadcast(String actionName) { 4366 synchronized (mPackages) { 4367 if (mProtectedBroadcasts.contains(actionName)) { 4368 return true; 4369 } else if (actionName != null) { 4370 // TODO: remove these terrible hacks 4371 if (actionName.startsWith("android.net.netmon.lingerExpired") 4372 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4373 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4374 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4375 return true; 4376 } 4377 } 4378 } 4379 return false; 4380 } 4381 4382 @Override 4383 public int checkSignatures(String pkg1, String pkg2) { 4384 synchronized (mPackages) { 4385 final PackageParser.Package p1 = mPackages.get(pkg1); 4386 final PackageParser.Package p2 = mPackages.get(pkg2); 4387 if (p1 == null || p1.mExtras == null 4388 || p2 == null || p2.mExtras == null) { 4389 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4390 } 4391 return compareSignatures(p1.mSignatures, p2.mSignatures); 4392 } 4393 } 4394 4395 @Override 4396 public int checkUidSignatures(int uid1, int uid2) { 4397 // Map to base uids. 4398 uid1 = UserHandle.getAppId(uid1); 4399 uid2 = UserHandle.getAppId(uid2); 4400 // reader 4401 synchronized (mPackages) { 4402 Signature[] s1; 4403 Signature[] s2; 4404 Object obj = mSettings.getUserIdLPr(uid1); 4405 if (obj != null) { 4406 if (obj instanceof SharedUserSetting) { 4407 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4408 } else if (obj instanceof PackageSetting) { 4409 s1 = ((PackageSetting)obj).signatures.mSignatures; 4410 } else { 4411 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4412 } 4413 } else { 4414 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4415 } 4416 obj = mSettings.getUserIdLPr(uid2); 4417 if (obj != null) { 4418 if (obj instanceof SharedUserSetting) { 4419 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4420 } else if (obj instanceof PackageSetting) { 4421 s2 = ((PackageSetting)obj).signatures.mSignatures; 4422 } else { 4423 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4424 } 4425 } else { 4426 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4427 } 4428 return compareSignatures(s1, s2); 4429 } 4430 } 4431 4432 /** 4433 * This method should typically only be used when granting or revoking 4434 * permissions, since the app may immediately restart after this call. 4435 * <p> 4436 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4437 * guard your work against the app being relaunched. 4438 */ 4439 private void killUid(int appId, int userId, String reason) { 4440 final long identity = Binder.clearCallingIdentity(); 4441 try { 4442 IActivityManager am = ActivityManagerNative.getDefault(); 4443 if (am != null) { 4444 try { 4445 am.killUid(appId, userId, reason); 4446 } catch (RemoteException e) { 4447 /* ignore - same process */ 4448 } 4449 } 4450 } finally { 4451 Binder.restoreCallingIdentity(identity); 4452 } 4453 } 4454 4455 /** 4456 * Compares two sets of signatures. Returns: 4457 * <br /> 4458 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4459 * <br /> 4460 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4461 * <br /> 4462 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4463 * <br /> 4464 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4465 * <br /> 4466 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4467 */ 4468 static int compareSignatures(Signature[] s1, Signature[] s2) { 4469 if (s1 == null) { 4470 return s2 == null 4471 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4472 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4473 } 4474 4475 if (s2 == null) { 4476 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4477 } 4478 4479 if (s1.length != s2.length) { 4480 return PackageManager.SIGNATURE_NO_MATCH; 4481 } 4482 4483 // Since both signature sets are of size 1, we can compare without HashSets. 4484 if (s1.length == 1) { 4485 return s1[0].equals(s2[0]) ? 4486 PackageManager.SIGNATURE_MATCH : 4487 PackageManager.SIGNATURE_NO_MATCH; 4488 } 4489 4490 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4491 for (Signature sig : s1) { 4492 set1.add(sig); 4493 } 4494 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4495 for (Signature sig : s2) { 4496 set2.add(sig); 4497 } 4498 // Make sure s2 contains all signatures in s1. 4499 if (set1.equals(set2)) { 4500 return PackageManager.SIGNATURE_MATCH; 4501 } 4502 return PackageManager.SIGNATURE_NO_MATCH; 4503 } 4504 4505 /** 4506 * If the database version for this type of package (internal storage or 4507 * external storage) is less than the version where package signatures 4508 * were updated, return true. 4509 */ 4510 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4511 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4512 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4513 } 4514 4515 /** 4516 * Used for backward compatibility to make sure any packages with 4517 * certificate chains get upgraded to the new style. {@code existingSigs} 4518 * will be in the old format (since they were stored on disk from before the 4519 * system upgrade) and {@code scannedSigs} will be in the newer format. 4520 */ 4521 private int compareSignaturesCompat(PackageSignatures existingSigs, 4522 PackageParser.Package scannedPkg) { 4523 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4524 return PackageManager.SIGNATURE_NO_MATCH; 4525 } 4526 4527 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4528 for (Signature sig : existingSigs.mSignatures) { 4529 existingSet.add(sig); 4530 } 4531 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4532 for (Signature sig : scannedPkg.mSignatures) { 4533 try { 4534 Signature[] chainSignatures = sig.getChainSignatures(); 4535 for (Signature chainSig : chainSignatures) { 4536 scannedCompatSet.add(chainSig); 4537 } 4538 } catch (CertificateEncodingException e) { 4539 scannedCompatSet.add(sig); 4540 } 4541 } 4542 /* 4543 * Make sure the expanded scanned set contains all signatures in the 4544 * existing one. 4545 */ 4546 if (scannedCompatSet.equals(existingSet)) { 4547 // Migrate the old signatures to the new scheme. 4548 existingSigs.assignSignatures(scannedPkg.mSignatures); 4549 // The new KeySets will be re-added later in the scanning process. 4550 synchronized (mPackages) { 4551 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4552 } 4553 return PackageManager.SIGNATURE_MATCH; 4554 } 4555 return PackageManager.SIGNATURE_NO_MATCH; 4556 } 4557 4558 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4559 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4560 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4561 } 4562 4563 private int compareSignaturesRecover(PackageSignatures existingSigs, 4564 PackageParser.Package scannedPkg) { 4565 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4566 return PackageManager.SIGNATURE_NO_MATCH; 4567 } 4568 4569 String msg = null; 4570 try { 4571 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4572 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4573 + scannedPkg.packageName); 4574 return PackageManager.SIGNATURE_MATCH; 4575 } 4576 } catch (CertificateException e) { 4577 msg = e.getMessage(); 4578 } 4579 4580 logCriticalInfo(Log.INFO, 4581 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4582 return PackageManager.SIGNATURE_NO_MATCH; 4583 } 4584 4585 @Override 4586 public List<String> getAllPackages() { 4587 synchronized (mPackages) { 4588 return new ArrayList<String>(mPackages.keySet()); 4589 } 4590 } 4591 4592 @Override 4593 public String[] getPackagesForUid(int uid) { 4594 uid = UserHandle.getAppId(uid); 4595 // reader 4596 synchronized (mPackages) { 4597 Object obj = mSettings.getUserIdLPr(uid); 4598 if (obj instanceof SharedUserSetting) { 4599 final SharedUserSetting sus = (SharedUserSetting) obj; 4600 final int N = sus.packages.size(); 4601 final String[] res = new String[N]; 4602 for (int i = 0; i < N; i++) { 4603 res[i] = sus.packages.valueAt(i).name; 4604 } 4605 return res; 4606 } else if (obj instanceof PackageSetting) { 4607 final PackageSetting ps = (PackageSetting) obj; 4608 return new String[] { ps.name }; 4609 } 4610 } 4611 return null; 4612 } 4613 4614 @Override 4615 public String getNameForUid(int uid) { 4616 // reader 4617 synchronized (mPackages) { 4618 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4619 if (obj instanceof SharedUserSetting) { 4620 final SharedUserSetting sus = (SharedUserSetting) obj; 4621 return sus.name + ":" + sus.userId; 4622 } else if (obj instanceof PackageSetting) { 4623 final PackageSetting ps = (PackageSetting) obj; 4624 return ps.name; 4625 } 4626 } 4627 return null; 4628 } 4629 4630 @Override 4631 public int getUidForSharedUser(String sharedUserName) { 4632 if(sharedUserName == null) { 4633 return -1; 4634 } 4635 // reader 4636 synchronized (mPackages) { 4637 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4638 if (suid == null) { 4639 return -1; 4640 } 4641 return suid.userId; 4642 } 4643 } 4644 4645 @Override 4646 public int getFlagsForUid(int uid) { 4647 synchronized (mPackages) { 4648 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4649 if (obj instanceof SharedUserSetting) { 4650 final SharedUserSetting sus = (SharedUserSetting) obj; 4651 return sus.pkgFlags; 4652 } else if (obj instanceof PackageSetting) { 4653 final PackageSetting ps = (PackageSetting) obj; 4654 return ps.pkgFlags; 4655 } 4656 } 4657 return 0; 4658 } 4659 4660 @Override 4661 public int getPrivateFlagsForUid(int uid) { 4662 synchronized (mPackages) { 4663 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4664 if (obj instanceof SharedUserSetting) { 4665 final SharedUserSetting sus = (SharedUserSetting) obj; 4666 return sus.pkgPrivateFlags; 4667 } else if (obj instanceof PackageSetting) { 4668 final PackageSetting ps = (PackageSetting) obj; 4669 return ps.pkgPrivateFlags; 4670 } 4671 } 4672 return 0; 4673 } 4674 4675 @Override 4676 public boolean isUidPrivileged(int uid) { 4677 uid = UserHandle.getAppId(uid); 4678 // reader 4679 synchronized (mPackages) { 4680 Object obj = mSettings.getUserIdLPr(uid); 4681 if (obj instanceof SharedUserSetting) { 4682 final SharedUserSetting sus = (SharedUserSetting) obj; 4683 final Iterator<PackageSetting> it = sus.packages.iterator(); 4684 while (it.hasNext()) { 4685 if (it.next().isPrivileged()) { 4686 return true; 4687 } 4688 } 4689 } else if (obj instanceof PackageSetting) { 4690 final PackageSetting ps = (PackageSetting) obj; 4691 return ps.isPrivileged(); 4692 } 4693 } 4694 return false; 4695 } 4696 4697 @Override 4698 public String[] getAppOpPermissionPackages(String permissionName) { 4699 synchronized (mPackages) { 4700 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4701 if (pkgs == null) { 4702 return null; 4703 } 4704 return pkgs.toArray(new String[pkgs.size()]); 4705 } 4706 } 4707 4708 @Override 4709 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4710 int flags, int userId) { 4711 try { 4712 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4713 4714 if (!sUserManager.exists(userId)) return null; 4715 flags = updateFlagsForResolve(flags, userId, intent); 4716 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4717 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4718 4719 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4720 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4721 flags, userId); 4722 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4723 4724 final ResolveInfo bestChoice = 4725 chooseBestActivity(intent, resolvedType, flags, query, userId); 4726 4727 if (isEphemeralAllowed(intent, query, userId)) { 4728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4729 final EphemeralResolveInfo ai = 4730 getEphemeralResolveInfo(intent, resolvedType, userId); 4731 if (ai != null) { 4732 if (DEBUG_EPHEMERAL) { 4733 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4734 } 4735 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4736 bestChoice.ephemeralResolveInfo = ai; 4737 } 4738 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4739 } 4740 return bestChoice; 4741 } finally { 4742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4743 } 4744 } 4745 4746 @Override 4747 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4748 IntentFilter filter, int match, ComponentName activity) { 4749 final int userId = UserHandle.getCallingUserId(); 4750 if (DEBUG_PREFERRED) { 4751 Log.v(TAG, "setLastChosenActivity intent=" + intent 4752 + " resolvedType=" + resolvedType 4753 + " flags=" + flags 4754 + " filter=" + filter 4755 + " match=" + match 4756 + " activity=" + activity); 4757 filter.dump(new PrintStreamPrinter(System.out), " "); 4758 } 4759 intent.setComponent(null); 4760 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4761 userId); 4762 // Find any earlier preferred or last chosen entries and nuke them 4763 findPreferredActivity(intent, resolvedType, 4764 flags, query, 0, false, true, false, userId); 4765 // Add the new activity as the last chosen for this filter 4766 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4767 "Setting last chosen"); 4768 } 4769 4770 @Override 4771 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4772 final int userId = UserHandle.getCallingUserId(); 4773 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4774 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4775 userId); 4776 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4777 false, false, false, userId); 4778 } 4779 4780 4781 private boolean isEphemeralAllowed( 4782 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4783 // Short circuit and return early if possible. 4784 if (DISABLE_EPHEMERAL_APPS) { 4785 return false; 4786 } 4787 final int callingUser = UserHandle.getCallingUserId(); 4788 if (callingUser != UserHandle.USER_SYSTEM) { 4789 return false; 4790 } 4791 if (mEphemeralResolverConnection == null) { 4792 return false; 4793 } 4794 if (intent.getComponent() != null) { 4795 return false; 4796 } 4797 if (intent.getPackage() != null) { 4798 return false; 4799 } 4800 final boolean isWebUri = hasWebURI(intent); 4801 if (!isWebUri) { 4802 return false; 4803 } 4804 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4805 synchronized (mPackages) { 4806 final int count = resolvedActivites.size(); 4807 for (int n = 0; n < count; n++) { 4808 ResolveInfo info = resolvedActivites.get(n); 4809 String packageName = info.activityInfo.packageName; 4810 PackageSetting ps = mSettings.mPackages.get(packageName); 4811 if (ps != null) { 4812 // Try to get the status from User settings first 4813 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4814 int status = (int) (packedStatus >> 32); 4815 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4816 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4817 if (DEBUG_EPHEMERAL) { 4818 Slog.v(TAG, "DENY ephemeral apps;" 4819 + " pkg: " + packageName + ", status: " + status); 4820 } 4821 return false; 4822 } 4823 } 4824 } 4825 } 4826 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4827 return true; 4828 } 4829 4830 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4831 int userId) { 4832 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 4833 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 4834 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 4835 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 4836 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 4837 ephemeralPrefixCount); 4838 final int[] shaPrefix = digest.getDigestPrefix(); 4839 final byte[][] digestBytes = digest.getDigestBytes(); 4840 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4841 mEphemeralResolverConnection.getEphemeralResolveInfoList( 4842 shaPrefix, ephemeralPrefixMask); 4843 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4844 // No hash prefix match; there are no ephemeral apps for this domain. 4845 return null; 4846 } 4847 4848 // Go in reverse order so we match the narrowest scope first. 4849 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 4850 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 4851 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 4852 continue; 4853 } 4854 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4855 // No filters; this should never happen. 4856 if (filters.isEmpty()) { 4857 continue; 4858 } 4859 // We have a domain match; resolve the filters to see if anything matches. 4860 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4861 for (int j = filters.size() - 1; j >= 0; --j) { 4862 final EphemeralResolveIntentInfo intentInfo = 4863 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4864 ephemeralResolver.addFilter(intentInfo); 4865 } 4866 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4867 intent, resolvedType, false /*defaultOnly*/, userId); 4868 if (!matchedResolveInfoList.isEmpty()) { 4869 return matchedResolveInfoList.get(0); 4870 } 4871 } 4872 } 4873 // Hash or filter mis-match; no ephemeral apps for this domain. 4874 return null; 4875 } 4876 4877 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4878 int flags, List<ResolveInfo> query, int userId) { 4879 if (query != null) { 4880 final int N = query.size(); 4881 if (N == 1) { 4882 return query.get(0); 4883 } else if (N > 1) { 4884 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4885 // If there is more than one activity with the same priority, 4886 // then let the user decide between them. 4887 ResolveInfo r0 = query.get(0); 4888 ResolveInfo r1 = query.get(1); 4889 if (DEBUG_INTENT_MATCHING || debug) { 4890 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4891 + r1.activityInfo.name + "=" + r1.priority); 4892 } 4893 // If the first activity has a higher priority, or a different 4894 // default, then it is always desirable to pick it. 4895 if (r0.priority != r1.priority 4896 || r0.preferredOrder != r1.preferredOrder 4897 || r0.isDefault != r1.isDefault) { 4898 return query.get(0); 4899 } 4900 // If we have saved a preference for a preferred activity for 4901 // this Intent, use that. 4902 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4903 flags, query, r0.priority, true, false, debug, userId); 4904 if (ri != null) { 4905 return ri; 4906 } 4907 ri = new ResolveInfo(mResolveInfo); 4908 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4909 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4910 // If all of the options come from the same package, show the application's 4911 // label and icon instead of the generic resolver's. 4912 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 4913 // and then throw away the ResolveInfo itself, meaning that the caller loses 4914 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 4915 // a fallback for this case; we only set the target package's resources on 4916 // the ResolveInfo, not the ActivityInfo. 4917 final String intentPackage = intent.getPackage(); 4918 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 4919 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 4920 ri.resolvePackageName = intentPackage; 4921 if (userNeedsBadging(userId)) { 4922 ri.noResourceId = true; 4923 } else { 4924 ri.icon = appi.icon; 4925 } 4926 ri.iconResourceId = appi.icon; 4927 ri.labelRes = appi.labelRes; 4928 } 4929 ri.activityInfo.applicationInfo = new ApplicationInfo( 4930 ri.activityInfo.applicationInfo); 4931 if (userId != 0) { 4932 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4933 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4934 } 4935 // Make sure that the resolver is displayable in car mode 4936 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4937 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4938 return ri; 4939 } 4940 } 4941 return null; 4942 } 4943 4944 /** 4945 * Return true if the given list is not empty and all of its contents have 4946 * an activityInfo with the given package name. 4947 */ 4948 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 4949 if (ArrayUtils.isEmpty(list)) { 4950 return false; 4951 } 4952 for (int i = 0, N = list.size(); i < N; i++) { 4953 final ResolveInfo ri = list.get(i); 4954 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 4955 if (ai == null || !packageName.equals(ai.packageName)) { 4956 return false; 4957 } 4958 } 4959 return true; 4960 } 4961 4962 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4963 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4964 final int N = query.size(); 4965 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4966 .get(userId); 4967 // Get the list of persistent preferred activities that handle the intent 4968 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4969 List<PersistentPreferredActivity> pprefs = ppir != null 4970 ? ppir.queryIntent(intent, resolvedType, 4971 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4972 : null; 4973 if (pprefs != null && pprefs.size() > 0) { 4974 final int M = pprefs.size(); 4975 for (int i=0; i<M; i++) { 4976 final PersistentPreferredActivity ppa = pprefs.get(i); 4977 if (DEBUG_PREFERRED || debug) { 4978 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4979 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4980 + "\n component=" + ppa.mComponent); 4981 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4982 } 4983 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4984 flags | MATCH_DISABLED_COMPONENTS, userId); 4985 if (DEBUG_PREFERRED || debug) { 4986 Slog.v(TAG, "Found persistent preferred activity:"); 4987 if (ai != null) { 4988 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4989 } else { 4990 Slog.v(TAG, " null"); 4991 } 4992 } 4993 if (ai == null) { 4994 // This previously registered persistent preferred activity 4995 // component is no longer known. Ignore it and do NOT remove it. 4996 continue; 4997 } 4998 for (int j=0; j<N; j++) { 4999 final ResolveInfo ri = query.get(j); 5000 if (!ri.activityInfo.applicationInfo.packageName 5001 .equals(ai.applicationInfo.packageName)) { 5002 continue; 5003 } 5004 if (!ri.activityInfo.name.equals(ai.name)) { 5005 continue; 5006 } 5007 // Found a persistent preference that can handle the intent. 5008 if (DEBUG_PREFERRED || debug) { 5009 Slog.v(TAG, "Returning persistent preferred activity: " + 5010 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5011 } 5012 return ri; 5013 } 5014 } 5015 } 5016 return null; 5017 } 5018 5019 // TODO: handle preferred activities missing while user has amnesia 5020 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5021 List<ResolveInfo> query, int priority, boolean always, 5022 boolean removeMatches, boolean debug, int userId) { 5023 if (!sUserManager.exists(userId)) return null; 5024 flags = updateFlagsForResolve(flags, userId, intent); 5025 // writer 5026 synchronized (mPackages) { 5027 if (intent.getSelector() != null) { 5028 intent = intent.getSelector(); 5029 } 5030 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5031 5032 // Try to find a matching persistent preferred activity. 5033 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5034 debug, userId); 5035 5036 // If a persistent preferred activity matched, use it. 5037 if (pri != null) { 5038 return pri; 5039 } 5040 5041 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5042 // Get the list of preferred activities that handle the intent 5043 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5044 List<PreferredActivity> prefs = pir != null 5045 ? pir.queryIntent(intent, resolvedType, 5046 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5047 : null; 5048 if (prefs != null && prefs.size() > 0) { 5049 boolean changed = false; 5050 try { 5051 // First figure out how good the original match set is. 5052 // We will only allow preferred activities that came 5053 // from the same match quality. 5054 int match = 0; 5055 5056 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5057 5058 final int N = query.size(); 5059 for (int j=0; j<N; j++) { 5060 final ResolveInfo ri = query.get(j); 5061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5062 + ": 0x" + Integer.toHexString(match)); 5063 if (ri.match > match) { 5064 match = ri.match; 5065 } 5066 } 5067 5068 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5069 + Integer.toHexString(match)); 5070 5071 match &= IntentFilter.MATCH_CATEGORY_MASK; 5072 final int M = prefs.size(); 5073 for (int i=0; i<M; i++) { 5074 final PreferredActivity pa = prefs.get(i); 5075 if (DEBUG_PREFERRED || debug) { 5076 Slog.v(TAG, "Checking PreferredActivity ds=" 5077 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5078 + "\n component=" + pa.mPref.mComponent); 5079 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5080 } 5081 if (pa.mPref.mMatch != match) { 5082 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5083 + Integer.toHexString(pa.mPref.mMatch)); 5084 continue; 5085 } 5086 // If it's not an "always" type preferred activity and that's what we're 5087 // looking for, skip it. 5088 if (always && !pa.mPref.mAlways) { 5089 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5090 continue; 5091 } 5092 final ActivityInfo ai = getActivityInfo( 5093 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5094 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5095 userId); 5096 if (DEBUG_PREFERRED || debug) { 5097 Slog.v(TAG, "Found preferred activity:"); 5098 if (ai != null) { 5099 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5100 } else { 5101 Slog.v(TAG, " null"); 5102 } 5103 } 5104 if (ai == null) { 5105 // This previously registered preferred activity 5106 // component is no longer known. Most likely an update 5107 // to the app was installed and in the new version this 5108 // component no longer exists. Clean it up by removing 5109 // it from the preferred activities list, and skip it. 5110 Slog.w(TAG, "Removing dangling preferred activity: " 5111 + pa.mPref.mComponent); 5112 pir.removeFilter(pa); 5113 changed = true; 5114 continue; 5115 } 5116 for (int j=0; j<N; j++) { 5117 final ResolveInfo ri = query.get(j); 5118 if (!ri.activityInfo.applicationInfo.packageName 5119 .equals(ai.applicationInfo.packageName)) { 5120 continue; 5121 } 5122 if (!ri.activityInfo.name.equals(ai.name)) { 5123 continue; 5124 } 5125 5126 if (removeMatches) { 5127 pir.removeFilter(pa); 5128 changed = true; 5129 if (DEBUG_PREFERRED) { 5130 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5131 } 5132 break; 5133 } 5134 5135 // Okay we found a previously set preferred or last chosen app. 5136 // If the result set is different from when this 5137 // was created, we need to clear it and re-ask the 5138 // user their preference, if we're looking for an "always" type entry. 5139 if (always && !pa.mPref.sameSet(query)) { 5140 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5141 + intent + " type " + resolvedType); 5142 if (DEBUG_PREFERRED) { 5143 Slog.v(TAG, "Removing preferred activity since set changed " 5144 + pa.mPref.mComponent); 5145 } 5146 pir.removeFilter(pa); 5147 // Re-add the filter as a "last chosen" entry (!always) 5148 PreferredActivity lastChosen = new PreferredActivity( 5149 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5150 pir.addFilter(lastChosen); 5151 changed = true; 5152 return null; 5153 } 5154 5155 // Yay! Either the set matched or we're looking for the last chosen 5156 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5157 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5158 return ri; 5159 } 5160 } 5161 } finally { 5162 if (changed) { 5163 if (DEBUG_PREFERRED) { 5164 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5165 } 5166 scheduleWritePackageRestrictionsLocked(userId); 5167 } 5168 } 5169 } 5170 } 5171 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5172 return null; 5173 } 5174 5175 /* 5176 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5177 */ 5178 @Override 5179 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5180 int targetUserId) { 5181 mContext.enforceCallingOrSelfPermission( 5182 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5183 List<CrossProfileIntentFilter> matches = 5184 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5185 if (matches != null) { 5186 int size = matches.size(); 5187 for (int i = 0; i < size; i++) { 5188 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5189 } 5190 } 5191 if (hasWebURI(intent)) { 5192 // cross-profile app linking works only towards the parent. 5193 final UserInfo parent = getProfileParent(sourceUserId); 5194 synchronized(mPackages) { 5195 int flags = updateFlagsForResolve(0, parent.id, intent); 5196 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5197 intent, resolvedType, flags, sourceUserId, parent.id); 5198 return xpDomainInfo != null; 5199 } 5200 } 5201 return false; 5202 } 5203 5204 private UserInfo getProfileParent(int userId) { 5205 final long identity = Binder.clearCallingIdentity(); 5206 try { 5207 return sUserManager.getProfileParent(userId); 5208 } finally { 5209 Binder.restoreCallingIdentity(identity); 5210 } 5211 } 5212 5213 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5214 String resolvedType, int userId) { 5215 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5216 if (resolver != null) { 5217 return resolver.queryIntent(intent, resolvedType, false, userId); 5218 } 5219 return null; 5220 } 5221 5222 @Override 5223 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5224 String resolvedType, int flags, int userId) { 5225 try { 5226 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5227 5228 return new ParceledListSlice<>( 5229 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5230 } finally { 5231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5232 } 5233 } 5234 5235 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5236 String resolvedType, int flags, int userId) { 5237 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5238 flags = updateFlagsForResolve(flags, userId, intent); 5239 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5240 false /* requireFullPermission */, false /* checkShell */, 5241 "query intent activities"); 5242 ComponentName comp = intent.getComponent(); 5243 if (comp == null) { 5244 if (intent.getSelector() != null) { 5245 intent = intent.getSelector(); 5246 comp = intent.getComponent(); 5247 } 5248 } 5249 5250 if (comp != null) { 5251 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5252 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5253 if (ai != null) { 5254 final ResolveInfo ri = new ResolveInfo(); 5255 ri.activityInfo = ai; 5256 list.add(ri); 5257 } 5258 return list; 5259 } 5260 5261 // reader 5262 synchronized (mPackages) { 5263 final String pkgName = intent.getPackage(); 5264 if (pkgName == null) { 5265 List<CrossProfileIntentFilter> matchingFilters = 5266 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5267 // Check for results that need to skip the current profile. 5268 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5269 resolvedType, flags, userId); 5270 if (xpResolveInfo != null) { 5271 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5272 result.add(xpResolveInfo); 5273 return filterIfNotSystemUser(result, userId); 5274 } 5275 5276 // Check for results in the current profile. 5277 List<ResolveInfo> result = mActivities.queryIntent( 5278 intent, resolvedType, flags, userId); 5279 result = filterIfNotSystemUser(result, userId); 5280 5281 // Check for cross profile results. 5282 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5283 xpResolveInfo = queryCrossProfileIntents( 5284 matchingFilters, intent, resolvedType, flags, userId, 5285 hasNonNegativePriorityResult); 5286 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5287 boolean isVisibleToUser = filterIfNotSystemUser( 5288 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5289 if (isVisibleToUser) { 5290 result.add(xpResolveInfo); 5291 Collections.sort(result, mResolvePrioritySorter); 5292 } 5293 } 5294 if (hasWebURI(intent)) { 5295 CrossProfileDomainInfo xpDomainInfo = null; 5296 final UserInfo parent = getProfileParent(userId); 5297 if (parent != null) { 5298 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5299 flags, userId, parent.id); 5300 } 5301 if (xpDomainInfo != null) { 5302 if (xpResolveInfo != null) { 5303 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5304 // in the result. 5305 result.remove(xpResolveInfo); 5306 } 5307 if (result.size() == 0) { 5308 result.add(xpDomainInfo.resolveInfo); 5309 return result; 5310 } 5311 } else if (result.size() <= 1) { 5312 return result; 5313 } 5314 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5315 xpDomainInfo, userId); 5316 Collections.sort(result, mResolvePrioritySorter); 5317 } 5318 return result; 5319 } 5320 final PackageParser.Package pkg = mPackages.get(pkgName); 5321 if (pkg != null) { 5322 return filterIfNotSystemUser( 5323 mActivities.queryIntentForPackage( 5324 intent, resolvedType, flags, pkg.activities, userId), 5325 userId); 5326 } 5327 return new ArrayList<ResolveInfo>(); 5328 } 5329 } 5330 5331 private static class CrossProfileDomainInfo { 5332 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5333 ResolveInfo resolveInfo; 5334 /* Best domain verification status of the activities found in the other profile */ 5335 int bestDomainVerificationStatus; 5336 } 5337 5338 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5339 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5340 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5341 sourceUserId)) { 5342 return null; 5343 } 5344 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5345 resolvedType, flags, parentUserId); 5346 5347 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5348 return null; 5349 } 5350 CrossProfileDomainInfo result = null; 5351 int size = resultTargetUser.size(); 5352 for (int i = 0; i < size; i++) { 5353 ResolveInfo riTargetUser = resultTargetUser.get(i); 5354 // Intent filter verification is only for filters that specify a host. So don't return 5355 // those that handle all web uris. 5356 if (riTargetUser.handleAllWebDataURI) { 5357 continue; 5358 } 5359 String packageName = riTargetUser.activityInfo.packageName; 5360 PackageSetting ps = mSettings.mPackages.get(packageName); 5361 if (ps == null) { 5362 continue; 5363 } 5364 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5365 int status = (int)(verificationState >> 32); 5366 if (result == null) { 5367 result = new CrossProfileDomainInfo(); 5368 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5369 sourceUserId, parentUserId); 5370 result.bestDomainVerificationStatus = status; 5371 } else { 5372 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5373 result.bestDomainVerificationStatus); 5374 } 5375 } 5376 // Don't consider matches with status NEVER across profiles. 5377 if (result != null && result.bestDomainVerificationStatus 5378 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5379 return null; 5380 } 5381 return result; 5382 } 5383 5384 /** 5385 * Verification statuses are ordered from the worse to the best, except for 5386 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5387 */ 5388 private int bestDomainVerificationStatus(int status1, int status2) { 5389 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5390 return status2; 5391 } 5392 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5393 return status1; 5394 } 5395 return (int) MathUtils.max(status1, status2); 5396 } 5397 5398 private boolean isUserEnabled(int userId) { 5399 long callingId = Binder.clearCallingIdentity(); 5400 try { 5401 UserInfo userInfo = sUserManager.getUserInfo(userId); 5402 return userInfo != null && userInfo.isEnabled(); 5403 } finally { 5404 Binder.restoreCallingIdentity(callingId); 5405 } 5406 } 5407 5408 /** 5409 * Filter out activities with systemUserOnly flag set, when current user is not System. 5410 * 5411 * @return filtered list 5412 */ 5413 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5414 if (userId == UserHandle.USER_SYSTEM) { 5415 return resolveInfos; 5416 } 5417 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5418 ResolveInfo info = resolveInfos.get(i); 5419 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5420 resolveInfos.remove(i); 5421 } 5422 } 5423 return resolveInfos; 5424 } 5425 5426 /** 5427 * @param resolveInfos list of resolve infos in descending priority order 5428 * @return if the list contains a resolve info with non-negative priority 5429 */ 5430 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5431 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5432 } 5433 5434 private static boolean hasWebURI(Intent intent) { 5435 if (intent.getData() == null) { 5436 return false; 5437 } 5438 final String scheme = intent.getScheme(); 5439 if (TextUtils.isEmpty(scheme)) { 5440 return false; 5441 } 5442 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5443 } 5444 5445 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5446 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5447 int userId) { 5448 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5449 5450 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5451 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5452 candidates.size()); 5453 } 5454 5455 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5456 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5457 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5458 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5459 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5460 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5461 5462 synchronized (mPackages) { 5463 final int count = candidates.size(); 5464 // First, try to use linked apps. Partition the candidates into four lists: 5465 // one for the final results, one for the "do not use ever", one for "undefined status" 5466 // and finally one for "browser app type". 5467 for (int n=0; n<count; n++) { 5468 ResolveInfo info = candidates.get(n); 5469 String packageName = info.activityInfo.packageName; 5470 PackageSetting ps = mSettings.mPackages.get(packageName); 5471 if (ps != null) { 5472 // Add to the special match all list (Browser use case) 5473 if (info.handleAllWebDataURI) { 5474 matchAllList.add(info); 5475 continue; 5476 } 5477 // Try to get the status from User settings first 5478 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5479 int status = (int)(packedStatus >> 32); 5480 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5481 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5482 if (DEBUG_DOMAIN_VERIFICATION) { 5483 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5484 + " : linkgen=" + linkGeneration); 5485 } 5486 // Use link-enabled generation as preferredOrder, i.e. 5487 // prefer newly-enabled over earlier-enabled. 5488 info.preferredOrder = linkGeneration; 5489 alwaysList.add(info); 5490 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5491 if (DEBUG_DOMAIN_VERIFICATION) { 5492 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5493 } 5494 neverList.add(info); 5495 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5496 if (DEBUG_DOMAIN_VERIFICATION) { 5497 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5498 } 5499 alwaysAskList.add(info); 5500 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5501 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5502 if (DEBUG_DOMAIN_VERIFICATION) { 5503 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5504 } 5505 undefinedList.add(info); 5506 } 5507 } 5508 } 5509 5510 // We'll want to include browser possibilities in a few cases 5511 boolean includeBrowser = false; 5512 5513 // First try to add the "always" resolution(s) for the current user, if any 5514 if (alwaysList.size() > 0) { 5515 result.addAll(alwaysList); 5516 } else { 5517 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5518 result.addAll(undefinedList); 5519 // Maybe add one for the other profile. 5520 if (xpDomainInfo != null && ( 5521 xpDomainInfo.bestDomainVerificationStatus 5522 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5523 result.add(xpDomainInfo.resolveInfo); 5524 } 5525 includeBrowser = true; 5526 } 5527 5528 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5529 // If there were 'always' entries their preferred order has been set, so we also 5530 // back that off to make the alternatives equivalent 5531 if (alwaysAskList.size() > 0) { 5532 for (ResolveInfo i : result) { 5533 i.preferredOrder = 0; 5534 } 5535 result.addAll(alwaysAskList); 5536 includeBrowser = true; 5537 } 5538 5539 if (includeBrowser) { 5540 // Also add browsers (all of them or only the default one) 5541 if (DEBUG_DOMAIN_VERIFICATION) { 5542 Slog.v(TAG, " ...including browsers in candidate set"); 5543 } 5544 if ((matchFlags & MATCH_ALL) != 0) { 5545 result.addAll(matchAllList); 5546 } else { 5547 // Browser/generic handling case. If there's a default browser, go straight 5548 // to that (but only if there is no other higher-priority match). 5549 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5550 int maxMatchPrio = 0; 5551 ResolveInfo defaultBrowserMatch = null; 5552 final int numCandidates = matchAllList.size(); 5553 for (int n = 0; n < numCandidates; n++) { 5554 ResolveInfo info = matchAllList.get(n); 5555 // track the highest overall match priority... 5556 if (info.priority > maxMatchPrio) { 5557 maxMatchPrio = info.priority; 5558 } 5559 // ...and the highest-priority default browser match 5560 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5561 if (defaultBrowserMatch == null 5562 || (defaultBrowserMatch.priority < info.priority)) { 5563 if (debug) { 5564 Slog.v(TAG, "Considering default browser match " + info); 5565 } 5566 defaultBrowserMatch = info; 5567 } 5568 } 5569 } 5570 if (defaultBrowserMatch != null 5571 && defaultBrowserMatch.priority >= maxMatchPrio 5572 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5573 { 5574 if (debug) { 5575 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5576 } 5577 result.add(defaultBrowserMatch); 5578 } else { 5579 result.addAll(matchAllList); 5580 } 5581 } 5582 5583 // If there is nothing selected, add all candidates and remove the ones that the user 5584 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5585 if (result.size() == 0) { 5586 result.addAll(candidates); 5587 result.removeAll(neverList); 5588 } 5589 } 5590 } 5591 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5592 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5593 result.size()); 5594 for (ResolveInfo info : result) { 5595 Slog.v(TAG, " + " + info.activityInfo); 5596 } 5597 } 5598 return result; 5599 } 5600 5601 // Returns a packed value as a long: 5602 // 5603 // high 'int'-sized word: link status: undefined/ask/never/always. 5604 // low 'int'-sized word: relative priority among 'always' results. 5605 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5606 long result = ps.getDomainVerificationStatusForUser(userId); 5607 // if none available, get the master status 5608 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5609 if (ps.getIntentFilterVerificationInfo() != null) { 5610 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5611 } 5612 } 5613 return result; 5614 } 5615 5616 private ResolveInfo querySkipCurrentProfileIntents( 5617 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5618 int flags, int sourceUserId) { 5619 if (matchingFilters != null) { 5620 int size = matchingFilters.size(); 5621 for (int i = 0; i < size; i ++) { 5622 CrossProfileIntentFilter filter = matchingFilters.get(i); 5623 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5624 // Checking if there are activities in the target user that can handle the 5625 // intent. 5626 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5627 resolvedType, flags, sourceUserId); 5628 if (resolveInfo != null) { 5629 return resolveInfo; 5630 } 5631 } 5632 } 5633 } 5634 return null; 5635 } 5636 5637 // Return matching ResolveInfo in target user if any. 5638 private ResolveInfo queryCrossProfileIntents( 5639 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5640 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5641 if (matchingFilters != null) { 5642 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5643 // match the same intent. For performance reasons, it is better not to 5644 // run queryIntent twice for the same userId 5645 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5646 int size = matchingFilters.size(); 5647 for (int i = 0; i < size; i++) { 5648 CrossProfileIntentFilter filter = matchingFilters.get(i); 5649 int targetUserId = filter.getTargetUserId(); 5650 boolean skipCurrentProfile = 5651 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5652 boolean skipCurrentProfileIfNoMatchFound = 5653 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5654 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5655 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5656 // Checking if there are activities in the target user that can handle the 5657 // intent. 5658 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5659 resolvedType, flags, sourceUserId); 5660 if (resolveInfo != null) return resolveInfo; 5661 alreadyTriedUserIds.put(targetUserId, true); 5662 } 5663 } 5664 } 5665 return null; 5666 } 5667 5668 /** 5669 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5670 * will forward the intent to the filter's target user. 5671 * Otherwise, returns null. 5672 */ 5673 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5674 String resolvedType, int flags, int sourceUserId) { 5675 int targetUserId = filter.getTargetUserId(); 5676 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5677 resolvedType, flags, targetUserId); 5678 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5679 // If all the matches in the target profile are suspended, return null. 5680 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5681 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5682 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5683 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5684 targetUserId); 5685 } 5686 } 5687 } 5688 return null; 5689 } 5690 5691 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5692 int sourceUserId, int targetUserId) { 5693 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5694 long ident = Binder.clearCallingIdentity(); 5695 boolean targetIsProfile; 5696 try { 5697 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5698 } finally { 5699 Binder.restoreCallingIdentity(ident); 5700 } 5701 String className; 5702 if (targetIsProfile) { 5703 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5704 } else { 5705 className = FORWARD_INTENT_TO_PARENT; 5706 } 5707 ComponentName forwardingActivityComponentName = new ComponentName( 5708 mAndroidApplication.packageName, className); 5709 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5710 sourceUserId); 5711 if (!targetIsProfile) { 5712 forwardingActivityInfo.showUserIcon = targetUserId; 5713 forwardingResolveInfo.noResourceId = true; 5714 } 5715 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5716 forwardingResolveInfo.priority = 0; 5717 forwardingResolveInfo.preferredOrder = 0; 5718 forwardingResolveInfo.match = 0; 5719 forwardingResolveInfo.isDefault = true; 5720 forwardingResolveInfo.filter = filter; 5721 forwardingResolveInfo.targetUserId = targetUserId; 5722 return forwardingResolveInfo; 5723 } 5724 5725 @Override 5726 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5727 Intent[] specifics, String[] specificTypes, Intent intent, 5728 String resolvedType, int flags, int userId) { 5729 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5730 specificTypes, intent, resolvedType, flags, userId)); 5731 } 5732 5733 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5734 Intent[] specifics, String[] specificTypes, Intent intent, 5735 String resolvedType, int flags, int userId) { 5736 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5737 flags = updateFlagsForResolve(flags, userId, intent); 5738 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5739 false /* requireFullPermission */, false /* checkShell */, 5740 "query intent activity options"); 5741 final String resultsAction = intent.getAction(); 5742 5743 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5744 | PackageManager.GET_RESOLVED_FILTER, userId); 5745 5746 if (DEBUG_INTENT_MATCHING) { 5747 Log.v(TAG, "Query " + intent + ": " + results); 5748 } 5749 5750 int specificsPos = 0; 5751 int N; 5752 5753 // todo: note that the algorithm used here is O(N^2). This 5754 // isn't a problem in our current environment, but if we start running 5755 // into situations where we have more than 5 or 10 matches then this 5756 // should probably be changed to something smarter... 5757 5758 // First we go through and resolve each of the specific items 5759 // that were supplied, taking care of removing any corresponding 5760 // duplicate items in the generic resolve list. 5761 if (specifics != null) { 5762 for (int i=0; i<specifics.length; i++) { 5763 final Intent sintent = specifics[i]; 5764 if (sintent == null) { 5765 continue; 5766 } 5767 5768 if (DEBUG_INTENT_MATCHING) { 5769 Log.v(TAG, "Specific #" + i + ": " + sintent); 5770 } 5771 5772 String action = sintent.getAction(); 5773 if (resultsAction != null && resultsAction.equals(action)) { 5774 // If this action was explicitly requested, then don't 5775 // remove things that have it. 5776 action = null; 5777 } 5778 5779 ResolveInfo ri = null; 5780 ActivityInfo ai = null; 5781 5782 ComponentName comp = sintent.getComponent(); 5783 if (comp == null) { 5784 ri = resolveIntent( 5785 sintent, 5786 specificTypes != null ? specificTypes[i] : null, 5787 flags, userId); 5788 if (ri == null) { 5789 continue; 5790 } 5791 if (ri == mResolveInfo) { 5792 // ACK! Must do something better with this. 5793 } 5794 ai = ri.activityInfo; 5795 comp = new ComponentName(ai.applicationInfo.packageName, 5796 ai.name); 5797 } else { 5798 ai = getActivityInfo(comp, flags, userId); 5799 if (ai == null) { 5800 continue; 5801 } 5802 } 5803 5804 // Look for any generic query activities that are duplicates 5805 // of this specific one, and remove them from the results. 5806 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5807 N = results.size(); 5808 int j; 5809 for (j=specificsPos; j<N; j++) { 5810 ResolveInfo sri = results.get(j); 5811 if ((sri.activityInfo.name.equals(comp.getClassName()) 5812 && sri.activityInfo.applicationInfo.packageName.equals( 5813 comp.getPackageName())) 5814 || (action != null && sri.filter.matchAction(action))) { 5815 results.remove(j); 5816 if (DEBUG_INTENT_MATCHING) Log.v( 5817 TAG, "Removing duplicate item from " + j 5818 + " due to specific " + specificsPos); 5819 if (ri == null) { 5820 ri = sri; 5821 } 5822 j--; 5823 N--; 5824 } 5825 } 5826 5827 // Add this specific item to its proper place. 5828 if (ri == null) { 5829 ri = new ResolveInfo(); 5830 ri.activityInfo = ai; 5831 } 5832 results.add(specificsPos, ri); 5833 ri.specificIndex = i; 5834 specificsPos++; 5835 } 5836 } 5837 5838 // Now we go through the remaining generic results and remove any 5839 // duplicate actions that are found here. 5840 N = results.size(); 5841 for (int i=specificsPos; i<N-1; i++) { 5842 final ResolveInfo rii = results.get(i); 5843 if (rii.filter == null) { 5844 continue; 5845 } 5846 5847 // Iterate over all of the actions of this result's intent 5848 // filter... typically this should be just one. 5849 final Iterator<String> it = rii.filter.actionsIterator(); 5850 if (it == null) { 5851 continue; 5852 } 5853 while (it.hasNext()) { 5854 final String action = it.next(); 5855 if (resultsAction != null && resultsAction.equals(action)) { 5856 // If this action was explicitly requested, then don't 5857 // remove things that have it. 5858 continue; 5859 } 5860 for (int j=i+1; j<N; j++) { 5861 final ResolveInfo rij = results.get(j); 5862 if (rij.filter != null && rij.filter.hasAction(action)) { 5863 results.remove(j); 5864 if (DEBUG_INTENT_MATCHING) Log.v( 5865 TAG, "Removing duplicate item from " + j 5866 + " due to action " + action + " at " + i); 5867 j--; 5868 N--; 5869 } 5870 } 5871 } 5872 5873 // If the caller didn't request filter information, drop it now 5874 // so we don't have to marshall/unmarshall it. 5875 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5876 rii.filter = null; 5877 } 5878 } 5879 5880 // Filter out the caller activity if so requested. 5881 if (caller != null) { 5882 N = results.size(); 5883 for (int i=0; i<N; i++) { 5884 ActivityInfo ainfo = results.get(i).activityInfo; 5885 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5886 && caller.getClassName().equals(ainfo.name)) { 5887 results.remove(i); 5888 break; 5889 } 5890 } 5891 } 5892 5893 // If the caller didn't request filter information, 5894 // drop them now so we don't have to 5895 // marshall/unmarshall it. 5896 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5897 N = results.size(); 5898 for (int i=0; i<N; i++) { 5899 results.get(i).filter = null; 5900 } 5901 } 5902 5903 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5904 return results; 5905 } 5906 5907 @Override 5908 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5909 String resolvedType, int flags, int userId) { 5910 return new ParceledListSlice<>( 5911 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5912 } 5913 5914 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5915 String resolvedType, int flags, int userId) { 5916 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5917 flags = updateFlagsForResolve(flags, userId, intent); 5918 ComponentName comp = intent.getComponent(); 5919 if (comp == null) { 5920 if (intent.getSelector() != null) { 5921 intent = intent.getSelector(); 5922 comp = intent.getComponent(); 5923 } 5924 } 5925 if (comp != null) { 5926 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5927 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5928 if (ai != null) { 5929 ResolveInfo ri = new ResolveInfo(); 5930 ri.activityInfo = ai; 5931 list.add(ri); 5932 } 5933 return list; 5934 } 5935 5936 // reader 5937 synchronized (mPackages) { 5938 String pkgName = intent.getPackage(); 5939 if (pkgName == null) { 5940 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5941 } 5942 final PackageParser.Package pkg = mPackages.get(pkgName); 5943 if (pkg != null) { 5944 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5945 userId); 5946 } 5947 return Collections.emptyList(); 5948 } 5949 } 5950 5951 @Override 5952 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5953 if (!sUserManager.exists(userId)) return null; 5954 flags = updateFlagsForResolve(flags, userId, intent); 5955 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5956 if (query != null) { 5957 if (query.size() >= 1) { 5958 // If there is more than one service with the same priority, 5959 // just arbitrarily pick the first one. 5960 return query.get(0); 5961 } 5962 } 5963 return null; 5964 } 5965 5966 @Override 5967 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5968 String resolvedType, int flags, int userId) { 5969 return new ParceledListSlice<>( 5970 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5971 } 5972 5973 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5974 String resolvedType, int flags, int userId) { 5975 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5976 flags = updateFlagsForResolve(flags, userId, intent); 5977 ComponentName comp = intent.getComponent(); 5978 if (comp == null) { 5979 if (intent.getSelector() != null) { 5980 intent = intent.getSelector(); 5981 comp = intent.getComponent(); 5982 } 5983 } 5984 if (comp != null) { 5985 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5986 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5987 if (si != null) { 5988 final ResolveInfo ri = new ResolveInfo(); 5989 ri.serviceInfo = si; 5990 list.add(ri); 5991 } 5992 return list; 5993 } 5994 5995 // reader 5996 synchronized (mPackages) { 5997 String pkgName = intent.getPackage(); 5998 if (pkgName == null) { 5999 return mServices.queryIntent(intent, resolvedType, flags, userId); 6000 } 6001 final PackageParser.Package pkg = mPackages.get(pkgName); 6002 if (pkg != null) { 6003 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6004 userId); 6005 } 6006 return Collections.emptyList(); 6007 } 6008 } 6009 6010 @Override 6011 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6012 String resolvedType, int flags, int userId) { 6013 return new ParceledListSlice<>( 6014 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6015 } 6016 6017 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6018 Intent intent, String resolvedType, int flags, int userId) { 6019 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6020 flags = updateFlagsForResolve(flags, userId, intent); 6021 ComponentName comp = intent.getComponent(); 6022 if (comp == null) { 6023 if (intent.getSelector() != null) { 6024 intent = intent.getSelector(); 6025 comp = intent.getComponent(); 6026 } 6027 } 6028 if (comp != null) { 6029 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6030 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6031 if (pi != null) { 6032 final ResolveInfo ri = new ResolveInfo(); 6033 ri.providerInfo = pi; 6034 list.add(ri); 6035 } 6036 return list; 6037 } 6038 6039 // reader 6040 synchronized (mPackages) { 6041 String pkgName = intent.getPackage(); 6042 if (pkgName == null) { 6043 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6044 } 6045 final PackageParser.Package pkg = mPackages.get(pkgName); 6046 if (pkg != null) { 6047 return mProviders.queryIntentForPackage( 6048 intent, resolvedType, flags, pkg.providers, userId); 6049 } 6050 return Collections.emptyList(); 6051 } 6052 } 6053 6054 @Override 6055 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6056 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6057 flags = updateFlagsForPackage(flags, userId, null); 6058 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6060 true /* requireFullPermission */, false /* checkShell */, 6061 "get installed packages"); 6062 6063 // writer 6064 synchronized (mPackages) { 6065 ArrayList<PackageInfo> list; 6066 if (listUninstalled) { 6067 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6068 for (PackageSetting ps : mSettings.mPackages.values()) { 6069 final PackageInfo pi; 6070 if (ps.pkg != null) { 6071 pi = generatePackageInfo(ps, flags, userId); 6072 } else { 6073 pi = generatePackageInfo(ps, flags, userId); 6074 } 6075 if (pi != null) { 6076 list.add(pi); 6077 } 6078 } 6079 } else { 6080 list = new ArrayList<PackageInfo>(mPackages.size()); 6081 for (PackageParser.Package p : mPackages.values()) { 6082 final PackageInfo pi = 6083 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6084 if (pi != null) { 6085 list.add(pi); 6086 } 6087 } 6088 } 6089 6090 return new ParceledListSlice<PackageInfo>(list); 6091 } 6092 } 6093 6094 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6095 String[] permissions, boolean[] tmp, int flags, int userId) { 6096 int numMatch = 0; 6097 final PermissionsState permissionsState = ps.getPermissionsState(); 6098 for (int i=0; i<permissions.length; i++) { 6099 final String permission = permissions[i]; 6100 if (permissionsState.hasPermission(permission, userId)) { 6101 tmp[i] = true; 6102 numMatch++; 6103 } else { 6104 tmp[i] = false; 6105 } 6106 } 6107 if (numMatch == 0) { 6108 return; 6109 } 6110 final PackageInfo pi; 6111 if (ps.pkg != null) { 6112 pi = generatePackageInfo(ps, flags, userId); 6113 } else { 6114 pi = generatePackageInfo(ps, flags, userId); 6115 } 6116 // The above might return null in cases of uninstalled apps or install-state 6117 // skew across users/profiles. 6118 if (pi != null) { 6119 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6120 if (numMatch == permissions.length) { 6121 pi.requestedPermissions = permissions; 6122 } else { 6123 pi.requestedPermissions = new String[numMatch]; 6124 numMatch = 0; 6125 for (int i=0; i<permissions.length; i++) { 6126 if (tmp[i]) { 6127 pi.requestedPermissions[numMatch] = permissions[i]; 6128 numMatch++; 6129 } 6130 } 6131 } 6132 } 6133 list.add(pi); 6134 } 6135 } 6136 6137 @Override 6138 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6139 String[] permissions, int flags, int userId) { 6140 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6141 flags = updateFlagsForPackage(flags, userId, permissions); 6142 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6143 6144 // writer 6145 synchronized (mPackages) { 6146 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6147 boolean[] tmpBools = new boolean[permissions.length]; 6148 if (listUninstalled) { 6149 for (PackageSetting ps : mSettings.mPackages.values()) { 6150 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6151 } 6152 } else { 6153 for (PackageParser.Package pkg : mPackages.values()) { 6154 PackageSetting ps = (PackageSetting)pkg.mExtras; 6155 if (ps != null) { 6156 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6157 userId); 6158 } 6159 } 6160 } 6161 6162 return new ParceledListSlice<PackageInfo>(list); 6163 } 6164 } 6165 6166 @Override 6167 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6168 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6169 flags = updateFlagsForApplication(flags, userId, null); 6170 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6171 6172 // writer 6173 synchronized (mPackages) { 6174 ArrayList<ApplicationInfo> list; 6175 if (listUninstalled) { 6176 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6177 for (PackageSetting ps : mSettings.mPackages.values()) { 6178 ApplicationInfo ai; 6179 if (ps.pkg != null) { 6180 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6181 ps.readUserState(userId), userId); 6182 } else { 6183 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6184 } 6185 if (ai != null) { 6186 list.add(ai); 6187 } 6188 } 6189 } else { 6190 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6191 for (PackageParser.Package p : mPackages.values()) { 6192 if (p.mExtras != null) { 6193 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6194 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6195 if (ai != null) { 6196 list.add(ai); 6197 } 6198 } 6199 } 6200 } 6201 6202 return new ParceledListSlice<ApplicationInfo>(list); 6203 } 6204 } 6205 6206 @Override 6207 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6208 if (DISABLE_EPHEMERAL_APPS) { 6209 return null; 6210 } 6211 6212 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6213 "getEphemeralApplications"); 6214 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6215 true /* requireFullPermission */, false /* checkShell */, 6216 "getEphemeralApplications"); 6217 synchronized (mPackages) { 6218 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6219 .getEphemeralApplicationsLPw(userId); 6220 if (ephemeralApps != null) { 6221 return new ParceledListSlice<>(ephemeralApps); 6222 } 6223 } 6224 return null; 6225 } 6226 6227 @Override 6228 public boolean isEphemeralApplication(String packageName, int userId) { 6229 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6230 true /* requireFullPermission */, false /* checkShell */, 6231 "isEphemeral"); 6232 if (DISABLE_EPHEMERAL_APPS) { 6233 return false; 6234 } 6235 6236 if (!isCallerSameApp(packageName)) { 6237 return false; 6238 } 6239 synchronized (mPackages) { 6240 PackageParser.Package pkg = mPackages.get(packageName); 6241 if (pkg != null) { 6242 return pkg.applicationInfo.isEphemeralApp(); 6243 } 6244 } 6245 return false; 6246 } 6247 6248 @Override 6249 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6250 if (DISABLE_EPHEMERAL_APPS) { 6251 return null; 6252 } 6253 6254 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6255 true /* requireFullPermission */, false /* checkShell */, 6256 "getCookie"); 6257 if (!isCallerSameApp(packageName)) { 6258 return null; 6259 } 6260 synchronized (mPackages) { 6261 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6262 packageName, userId); 6263 } 6264 } 6265 6266 @Override 6267 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6268 if (DISABLE_EPHEMERAL_APPS) { 6269 return true; 6270 } 6271 6272 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6273 true /* requireFullPermission */, true /* checkShell */, 6274 "setCookie"); 6275 if (!isCallerSameApp(packageName)) { 6276 return false; 6277 } 6278 synchronized (mPackages) { 6279 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6280 packageName, cookie, userId); 6281 } 6282 } 6283 6284 @Override 6285 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6286 if (DISABLE_EPHEMERAL_APPS) { 6287 return null; 6288 } 6289 6290 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6291 "getEphemeralApplicationIcon"); 6292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6293 true /* requireFullPermission */, false /* checkShell */, 6294 "getEphemeralApplicationIcon"); 6295 synchronized (mPackages) { 6296 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6297 packageName, userId); 6298 } 6299 } 6300 6301 private boolean isCallerSameApp(String packageName) { 6302 PackageParser.Package pkg = mPackages.get(packageName); 6303 return pkg != null 6304 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6305 } 6306 6307 @Override 6308 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6309 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6310 } 6311 6312 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6313 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6314 6315 // reader 6316 synchronized (mPackages) { 6317 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6318 final int userId = UserHandle.getCallingUserId(); 6319 while (i.hasNext()) { 6320 final PackageParser.Package p = i.next(); 6321 if (p.applicationInfo == null) continue; 6322 6323 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6324 && !p.applicationInfo.isDirectBootAware(); 6325 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6326 && p.applicationInfo.isDirectBootAware(); 6327 6328 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6329 && (!mSafeMode || isSystemApp(p)) 6330 && (matchesUnaware || matchesAware)) { 6331 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6332 if (ps != null) { 6333 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6334 ps.readUserState(userId), userId); 6335 if (ai != null) { 6336 finalList.add(ai); 6337 } 6338 } 6339 } 6340 } 6341 } 6342 6343 return finalList; 6344 } 6345 6346 @Override 6347 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6348 if (!sUserManager.exists(userId)) return null; 6349 flags = updateFlagsForComponent(flags, userId, name); 6350 // reader 6351 synchronized (mPackages) { 6352 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6353 PackageSetting ps = provider != null 6354 ? mSettings.mPackages.get(provider.owner.packageName) 6355 : null; 6356 return ps != null 6357 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6358 ? PackageParser.generateProviderInfo(provider, flags, 6359 ps.readUserState(userId), userId) 6360 : null; 6361 } 6362 } 6363 6364 /** 6365 * @deprecated 6366 */ 6367 @Deprecated 6368 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6369 // reader 6370 synchronized (mPackages) { 6371 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6372 .entrySet().iterator(); 6373 final int userId = UserHandle.getCallingUserId(); 6374 while (i.hasNext()) { 6375 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6376 PackageParser.Provider p = entry.getValue(); 6377 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6378 6379 if (ps != null && p.syncable 6380 && (!mSafeMode || (p.info.applicationInfo.flags 6381 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6382 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6383 ps.readUserState(userId), userId); 6384 if (info != null) { 6385 outNames.add(entry.getKey()); 6386 outInfo.add(info); 6387 } 6388 } 6389 } 6390 } 6391 } 6392 6393 @Override 6394 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6395 int uid, int flags) { 6396 final int userId = processName != null ? UserHandle.getUserId(uid) 6397 : UserHandle.getCallingUserId(); 6398 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6399 flags = updateFlagsForComponent(flags, userId, processName); 6400 6401 ArrayList<ProviderInfo> finalList = null; 6402 // reader 6403 synchronized (mPackages) { 6404 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6405 while (i.hasNext()) { 6406 final PackageParser.Provider p = i.next(); 6407 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6408 if (ps != null && p.info.authority != null 6409 && (processName == null 6410 || (p.info.processName.equals(processName) 6411 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6412 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6413 if (finalList == null) { 6414 finalList = new ArrayList<ProviderInfo>(3); 6415 } 6416 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6417 ps.readUserState(userId), userId); 6418 if (info != null) { 6419 finalList.add(info); 6420 } 6421 } 6422 } 6423 } 6424 6425 if (finalList != null) { 6426 Collections.sort(finalList, mProviderInitOrderSorter); 6427 return new ParceledListSlice<ProviderInfo>(finalList); 6428 } 6429 6430 return ParceledListSlice.emptyList(); 6431 } 6432 6433 @Override 6434 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6435 // reader 6436 synchronized (mPackages) { 6437 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6438 return PackageParser.generateInstrumentationInfo(i, flags); 6439 } 6440 } 6441 6442 @Override 6443 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6444 String targetPackage, int flags) { 6445 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6446 } 6447 6448 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6449 int flags) { 6450 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6451 6452 // reader 6453 synchronized (mPackages) { 6454 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6455 while (i.hasNext()) { 6456 final PackageParser.Instrumentation p = i.next(); 6457 if (targetPackage == null 6458 || targetPackage.equals(p.info.targetPackage)) { 6459 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6460 flags); 6461 if (ii != null) { 6462 finalList.add(ii); 6463 } 6464 } 6465 } 6466 } 6467 6468 return finalList; 6469 } 6470 6471 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6472 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6473 if (overlays == null) { 6474 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6475 return; 6476 } 6477 for (PackageParser.Package opkg : overlays.values()) { 6478 // Not much to do if idmap fails: we already logged the error 6479 // and we certainly don't want to abort installation of pkg simply 6480 // because an overlay didn't fit properly. For these reasons, 6481 // ignore the return value of createIdmapForPackagePairLI. 6482 createIdmapForPackagePairLI(pkg, opkg); 6483 } 6484 } 6485 6486 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6487 PackageParser.Package opkg) { 6488 if (!opkg.mTrustedOverlay) { 6489 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6490 opkg.baseCodePath + ": overlay not trusted"); 6491 return false; 6492 } 6493 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6494 if (overlaySet == null) { 6495 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6496 opkg.baseCodePath + " but target package has no known overlays"); 6497 return false; 6498 } 6499 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6500 // TODO: generate idmap for split APKs 6501 try { 6502 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6503 } catch (InstallerException e) { 6504 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6505 + opkg.baseCodePath); 6506 return false; 6507 } 6508 PackageParser.Package[] overlayArray = 6509 overlaySet.values().toArray(new PackageParser.Package[0]); 6510 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6511 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6512 return p1.mOverlayPriority - p2.mOverlayPriority; 6513 } 6514 }; 6515 Arrays.sort(overlayArray, cmp); 6516 6517 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6518 int i = 0; 6519 for (PackageParser.Package p : overlayArray) { 6520 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6521 } 6522 return true; 6523 } 6524 6525 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6526 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6527 try { 6528 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6529 } finally { 6530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6531 } 6532 } 6533 6534 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6535 final File[] files = dir.listFiles(); 6536 if (ArrayUtils.isEmpty(files)) { 6537 Log.d(TAG, "No files in app dir " + dir); 6538 return; 6539 } 6540 6541 if (DEBUG_PACKAGE_SCANNING) { 6542 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6543 + " flags=0x" + Integer.toHexString(parseFlags)); 6544 } 6545 6546 for (File file : files) { 6547 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6548 && !PackageInstallerService.isStageName(file.getName()); 6549 if (!isPackage) { 6550 // Ignore entries which are not packages 6551 continue; 6552 } 6553 try { 6554 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6555 scanFlags, currentTime, null); 6556 } catch (PackageManagerException e) { 6557 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6558 6559 // Delete invalid userdata apps 6560 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6561 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6562 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6563 removeCodePathLI(file); 6564 } 6565 } 6566 } 6567 } 6568 6569 private static File getSettingsProblemFile() { 6570 File dataDir = Environment.getDataDirectory(); 6571 File systemDir = new File(dataDir, "system"); 6572 File fname = new File(systemDir, "uiderrors.txt"); 6573 return fname; 6574 } 6575 6576 static void reportSettingsProblem(int priority, String msg) { 6577 logCriticalInfo(priority, msg); 6578 } 6579 6580 static void logCriticalInfo(int priority, String msg) { 6581 Slog.println(priority, TAG, msg); 6582 EventLogTags.writePmCriticalInfo(msg); 6583 try { 6584 File fname = getSettingsProblemFile(); 6585 FileOutputStream out = new FileOutputStream(fname, true); 6586 PrintWriter pw = new FastPrintWriter(out); 6587 SimpleDateFormat formatter = new SimpleDateFormat(); 6588 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6589 pw.println(dateString + ": " + msg); 6590 pw.close(); 6591 FileUtils.setPermissions( 6592 fname.toString(), 6593 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6594 -1, -1); 6595 } catch (java.io.IOException e) { 6596 } 6597 } 6598 6599 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6600 if (srcFile.isDirectory()) { 6601 final File baseFile = new File(pkg.baseCodePath); 6602 long maxModifiedTime = baseFile.lastModified(); 6603 if (pkg.splitCodePaths != null) { 6604 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6605 final File splitFile = new File(pkg.splitCodePaths[i]); 6606 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6607 } 6608 } 6609 return maxModifiedTime; 6610 } 6611 return srcFile.lastModified(); 6612 } 6613 6614 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6615 final int policyFlags) throws PackageManagerException { 6616 if (ps != null 6617 && ps.codePath.equals(srcFile) 6618 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6619 && !isCompatSignatureUpdateNeeded(pkg) 6620 && !isRecoverSignatureUpdateNeeded(pkg)) { 6621 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6622 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6623 ArraySet<PublicKey> signingKs; 6624 synchronized (mPackages) { 6625 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6626 } 6627 if (ps.signatures.mSignatures != null 6628 && ps.signatures.mSignatures.length != 0 6629 && signingKs != null) { 6630 // Optimization: reuse the existing cached certificates 6631 // if the package appears to be unchanged. 6632 pkg.mSignatures = ps.signatures.mSignatures; 6633 pkg.mSigningKeys = signingKs; 6634 return; 6635 } 6636 6637 Slog.w(TAG, "PackageSetting for " + ps.name 6638 + " is missing signatures. Collecting certs again to recover them."); 6639 } else { 6640 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6641 } 6642 6643 try { 6644 PackageParser.collectCertificates(pkg, policyFlags); 6645 } catch (PackageParserException e) { 6646 throw PackageManagerException.from(e); 6647 } 6648 } 6649 6650 /** 6651 * Traces a package scan. 6652 * @see #scanPackageLI(File, int, int, long, UserHandle) 6653 */ 6654 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6655 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6656 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6657 try { 6658 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6659 } finally { 6660 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6661 } 6662 } 6663 6664 /** 6665 * Scans a package and returns the newly parsed package. 6666 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6667 */ 6668 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6669 long currentTime, UserHandle user) throws PackageManagerException { 6670 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6671 PackageParser pp = new PackageParser(); 6672 pp.setSeparateProcesses(mSeparateProcesses); 6673 pp.setOnlyCoreApps(mOnlyCore); 6674 pp.setDisplayMetrics(mMetrics); 6675 6676 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6677 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6678 } 6679 6680 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6681 final PackageParser.Package pkg; 6682 try { 6683 pkg = pp.parsePackage(scanFile, parseFlags); 6684 } catch (PackageParserException e) { 6685 throw PackageManagerException.from(e); 6686 } finally { 6687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6688 } 6689 6690 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6691 } 6692 6693 /** 6694 * Scans a package and returns the newly parsed package. 6695 * @throws PackageManagerException on a parse error. 6696 */ 6697 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6698 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6699 throws PackageManagerException { 6700 // If the package has children and this is the first dive in the function 6701 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6702 // packages (parent and children) would be successfully scanned before the 6703 // actual scan since scanning mutates internal state and we want to atomically 6704 // install the package and its children. 6705 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6706 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6707 scanFlags |= SCAN_CHECK_ONLY; 6708 } 6709 } else { 6710 scanFlags &= ~SCAN_CHECK_ONLY; 6711 } 6712 6713 // Scan the parent 6714 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6715 scanFlags, currentTime, user); 6716 6717 // Scan the children 6718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6719 for (int i = 0; i < childCount; i++) { 6720 PackageParser.Package childPackage = pkg.childPackages.get(i); 6721 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6722 currentTime, user); 6723 } 6724 6725 6726 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6727 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6728 } 6729 6730 return scannedPkg; 6731 } 6732 6733 /** 6734 * Scans a package and returns the newly parsed package. 6735 * @throws PackageManagerException on a parse error. 6736 */ 6737 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6738 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6739 throws PackageManagerException { 6740 PackageSetting ps = null; 6741 PackageSetting updatedPkg; 6742 // reader 6743 synchronized (mPackages) { 6744 // Look to see if we already know about this package. 6745 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6746 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6747 // This package has been renamed to its original name. Let's 6748 // use that. 6749 ps = mSettings.peekPackageLPr(oldName); 6750 } 6751 // If there was no original package, see one for the real package name. 6752 if (ps == null) { 6753 ps = mSettings.peekPackageLPr(pkg.packageName); 6754 } 6755 // Check to see if this package could be hiding/updating a system 6756 // package. Must look for it either under the original or real 6757 // package name depending on our state. 6758 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6759 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6760 6761 // If this is a package we don't know about on the system partition, we 6762 // may need to remove disabled child packages on the system partition 6763 // or may need to not add child packages if the parent apk is updated 6764 // on the data partition and no longer defines this child package. 6765 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6766 // If this is a parent package for an updated system app and this system 6767 // app got an OTA update which no longer defines some of the child packages 6768 // we have to prune them from the disabled system packages. 6769 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6770 if (disabledPs != null) { 6771 final int scannedChildCount = (pkg.childPackages != null) 6772 ? pkg.childPackages.size() : 0; 6773 final int disabledChildCount = disabledPs.childPackageNames != null 6774 ? disabledPs.childPackageNames.size() : 0; 6775 for (int i = 0; i < disabledChildCount; i++) { 6776 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6777 boolean disabledPackageAvailable = false; 6778 for (int j = 0; j < scannedChildCount; j++) { 6779 PackageParser.Package childPkg = pkg.childPackages.get(j); 6780 if (childPkg.packageName.equals(disabledChildPackageName)) { 6781 disabledPackageAvailable = true; 6782 break; 6783 } 6784 } 6785 if (!disabledPackageAvailable) { 6786 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6787 } 6788 } 6789 } 6790 } 6791 } 6792 6793 boolean updatedPkgBetter = false; 6794 // First check if this is a system package that may involve an update 6795 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6796 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6797 // it needs to drop FLAG_PRIVILEGED. 6798 if (locationIsPrivileged(scanFile)) { 6799 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6800 } else { 6801 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6802 } 6803 6804 if (ps != null && !ps.codePath.equals(scanFile)) { 6805 // The path has changed from what was last scanned... check the 6806 // version of the new path against what we have stored to determine 6807 // what to do. 6808 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6809 if (pkg.mVersionCode <= ps.versionCode) { 6810 // The system package has been updated and the code path does not match 6811 // Ignore entry. Skip it. 6812 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6813 + " ignored: updated version " + ps.versionCode 6814 + " better than this " + pkg.mVersionCode); 6815 if (!updatedPkg.codePath.equals(scanFile)) { 6816 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6817 + ps.name + " changing from " + updatedPkg.codePathString 6818 + " to " + scanFile); 6819 updatedPkg.codePath = scanFile; 6820 updatedPkg.codePathString = scanFile.toString(); 6821 updatedPkg.resourcePath = scanFile; 6822 updatedPkg.resourcePathString = scanFile.toString(); 6823 } 6824 updatedPkg.pkg = pkg; 6825 updatedPkg.versionCode = pkg.mVersionCode; 6826 6827 // Update the disabled system child packages to point to the package too. 6828 final int childCount = updatedPkg.childPackageNames != null 6829 ? updatedPkg.childPackageNames.size() : 0; 6830 for (int i = 0; i < childCount; i++) { 6831 String childPackageName = updatedPkg.childPackageNames.get(i); 6832 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6833 childPackageName); 6834 if (updatedChildPkg != null) { 6835 updatedChildPkg.pkg = pkg; 6836 updatedChildPkg.versionCode = pkg.mVersionCode; 6837 } 6838 } 6839 6840 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6841 + scanFile + " ignored: updated version " + ps.versionCode 6842 + " better than this " + pkg.mVersionCode); 6843 } else { 6844 // The current app on the system partition is better than 6845 // what we have updated to on the data partition; switch 6846 // back to the system partition version. 6847 // At this point, its safely assumed that package installation for 6848 // apps in system partition will go through. If not there won't be a working 6849 // version of the app 6850 // writer 6851 synchronized (mPackages) { 6852 // Just remove the loaded entries from package lists. 6853 mPackages.remove(ps.name); 6854 } 6855 6856 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6857 + " reverting from " + ps.codePathString 6858 + ": new version " + pkg.mVersionCode 6859 + " better than installed " + ps.versionCode); 6860 6861 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6862 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6863 synchronized (mInstallLock) { 6864 args.cleanUpResourcesLI(); 6865 } 6866 synchronized (mPackages) { 6867 mSettings.enableSystemPackageLPw(ps.name); 6868 } 6869 updatedPkgBetter = true; 6870 } 6871 } 6872 } 6873 6874 if (updatedPkg != null) { 6875 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6876 // initially 6877 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6878 6879 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6880 // flag set initially 6881 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6882 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6883 } 6884 } 6885 6886 // Verify certificates against what was last scanned 6887 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6888 6889 /* 6890 * A new system app appeared, but we already had a non-system one of the 6891 * same name installed earlier. 6892 */ 6893 boolean shouldHideSystemApp = false; 6894 if (updatedPkg == null && ps != null 6895 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6896 /* 6897 * Check to make sure the signatures match first. If they don't, 6898 * wipe the installed application and its data. 6899 */ 6900 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6901 != PackageManager.SIGNATURE_MATCH) { 6902 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6903 + " signatures don't match existing userdata copy; removing"); 6904 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6905 "scanPackageInternalLI")) { 6906 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6907 } 6908 ps = null; 6909 } else { 6910 /* 6911 * If the newly-added system app is an older version than the 6912 * already installed version, hide it. It will be scanned later 6913 * and re-added like an update. 6914 */ 6915 if (pkg.mVersionCode <= ps.versionCode) { 6916 shouldHideSystemApp = true; 6917 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6918 + " but new version " + pkg.mVersionCode + " better than installed " 6919 + ps.versionCode + "; hiding system"); 6920 } else { 6921 /* 6922 * The newly found system app is a newer version that the 6923 * one previously installed. Simply remove the 6924 * already-installed application and replace it with our own 6925 * while keeping the application data. 6926 */ 6927 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6928 + " reverting from " + ps.codePathString + ": new version " 6929 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6930 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6931 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6932 synchronized (mInstallLock) { 6933 args.cleanUpResourcesLI(); 6934 } 6935 } 6936 } 6937 } 6938 6939 // The apk is forward locked (not public) if its code and resources 6940 // are kept in different files. (except for app in either system or 6941 // vendor path). 6942 // TODO grab this value from PackageSettings 6943 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6944 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6945 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6946 } 6947 } 6948 6949 // TODO: extend to support forward-locked splits 6950 String resourcePath = null; 6951 String baseResourcePath = null; 6952 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6953 if (ps != null && ps.resourcePathString != null) { 6954 resourcePath = ps.resourcePathString; 6955 baseResourcePath = ps.resourcePathString; 6956 } else { 6957 // Should not happen at all. Just log an error. 6958 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6959 } 6960 } else { 6961 resourcePath = pkg.codePath; 6962 baseResourcePath = pkg.baseCodePath; 6963 } 6964 6965 // Set application objects path explicitly. 6966 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6967 pkg.setApplicationInfoCodePath(pkg.codePath); 6968 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6969 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6970 pkg.setApplicationInfoResourcePath(resourcePath); 6971 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6972 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6973 6974 // Note that we invoke the following method only if we are about to unpack an application 6975 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 6976 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6977 6978 /* 6979 * If the system app should be overridden by a previously installed 6980 * data, hide the system app now and let the /data/app scan pick it up 6981 * again. 6982 */ 6983 if (shouldHideSystemApp) { 6984 synchronized (mPackages) { 6985 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6986 } 6987 } 6988 6989 return scannedPkg; 6990 } 6991 6992 private static String fixProcessName(String defProcessName, 6993 String processName, int uid) { 6994 if (processName == null) { 6995 return defProcessName; 6996 } 6997 return processName; 6998 } 6999 7000 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7001 throws PackageManagerException { 7002 if (pkgSetting.signatures.mSignatures != null) { 7003 // Already existing package. Make sure signatures match 7004 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7005 == PackageManager.SIGNATURE_MATCH; 7006 if (!match) { 7007 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7008 == PackageManager.SIGNATURE_MATCH; 7009 } 7010 if (!match) { 7011 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7012 == PackageManager.SIGNATURE_MATCH; 7013 } 7014 if (!match) { 7015 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7016 + pkg.packageName + " signatures do not match the " 7017 + "previously installed version; ignoring!"); 7018 } 7019 } 7020 7021 // Check for shared user signatures 7022 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7023 // Already existing package. Make sure signatures match 7024 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7025 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7026 if (!match) { 7027 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7028 == PackageManager.SIGNATURE_MATCH; 7029 } 7030 if (!match) { 7031 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7032 == PackageManager.SIGNATURE_MATCH; 7033 } 7034 if (!match) { 7035 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7036 "Package " + pkg.packageName 7037 + " has no signatures that match those in shared user " 7038 + pkgSetting.sharedUser.name + "; ignoring!"); 7039 } 7040 } 7041 } 7042 7043 /** 7044 * Enforces that only the system UID or root's UID can call a method exposed 7045 * via Binder. 7046 * 7047 * @param message used as message if SecurityException is thrown 7048 * @throws SecurityException if the caller is not system or root 7049 */ 7050 private static final void enforceSystemOrRoot(String message) { 7051 final int uid = Binder.getCallingUid(); 7052 if (uid != Process.SYSTEM_UID && uid != 0) { 7053 throw new SecurityException(message); 7054 } 7055 } 7056 7057 @Override 7058 public void performFstrimIfNeeded() { 7059 enforceSystemOrRoot("Only the system can request fstrim"); 7060 7061 // Before everything else, see whether we need to fstrim. 7062 try { 7063 IMountService ms = PackageHelper.getMountService(); 7064 if (ms != null) { 7065 boolean doTrim = false; 7066 final long interval = android.provider.Settings.Global.getLong( 7067 mContext.getContentResolver(), 7068 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7069 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7070 if (interval > 0) { 7071 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7072 if (timeSinceLast > interval) { 7073 doTrim = true; 7074 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7075 + "; running immediately"); 7076 } 7077 } 7078 if (doTrim) { 7079 if (!isFirstBoot()) { 7080 try { 7081 ActivityManagerNative.getDefault().showBootMessage( 7082 mContext.getResources().getString( 7083 R.string.android_upgrading_fstrim), true); 7084 } catch (RemoteException e) { 7085 } 7086 } 7087 ms.runMaintenance(); 7088 } 7089 } else { 7090 Slog.e(TAG, "Mount service unavailable!"); 7091 } 7092 } catch (RemoteException e) { 7093 // Can't happen; MountService is local 7094 } 7095 } 7096 7097 @Override 7098 public void updatePackagesIfNeeded() { 7099 enforceSystemOrRoot("Only the system can request package update"); 7100 7101 // We need to re-extract after an OTA. 7102 boolean causeUpgrade = isUpgrade(); 7103 7104 // First boot or factory reset. 7105 // Note: we also handle devices that are upgrading to N right now as if it is their 7106 // first boot, as they do not have profile data. 7107 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7108 7109 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7110 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7111 7112 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7113 return; 7114 } 7115 7116 List<PackageParser.Package> pkgs; 7117 synchronized (mPackages) { 7118 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7119 } 7120 7121 final long startTime = System.nanoTime(); 7122 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 7123 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7124 7125 final int elapsedTimeSeconds = 7126 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7127 7128 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7129 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7130 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7131 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7132 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7133 } 7134 7135 /** 7136 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7137 * containing statistics about the invocation. The array consists of three elements, 7138 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7139 * and {@code numberOfPackagesFailed}. 7140 */ 7141 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 7142 String compilerFilter) { 7143 7144 int numberOfPackagesVisited = 0; 7145 int numberOfPackagesOptimized = 0; 7146 int numberOfPackagesSkipped = 0; 7147 int numberOfPackagesFailed = 0; 7148 final int numberOfPackagesToDexopt = pkgs.size(); 7149 7150 for (PackageParser.Package pkg : pkgs) { 7151 numberOfPackagesVisited++; 7152 7153 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7154 if (DEBUG_DEXOPT) { 7155 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7156 } 7157 numberOfPackagesSkipped++; 7158 continue; 7159 } 7160 7161 if (DEBUG_DEXOPT) { 7162 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7163 numberOfPackagesToDexopt + ": " + pkg.packageName); 7164 } 7165 7166 if (showDialog) { 7167 try { 7168 ActivityManagerNative.getDefault().showBootMessage( 7169 mContext.getResources().getString(R.string.android_upgrading_apk, 7170 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7171 } catch (RemoteException e) { 7172 } 7173 } 7174 7175 // If the OTA updates a system app which was previously preopted to a non-preopted state 7176 // the app might end up being verified at runtime. That's because by default the apps 7177 // are verify-profile but for preopted apps there's no profile. 7178 // Do a hacky check to ensure that if we have no profiles (a reasonable indication 7179 // that before the OTA the app was preopted) the app gets compiled with a non-profile 7180 // filter (by default interpret-only). 7181 // Note that at this stage unused apps are already filtered. 7182 if (isSystemApp(pkg) && 7183 DexFile.isProfileGuidedCompilerFilter(compilerFilter) && 7184 !Environment.getReferenceProfile(pkg.packageName).exists()) { 7185 compilerFilter = getNonProfileGuidedCompilerFilter(compilerFilter); 7186 } 7187 7188 // checkProfiles is false to avoid merging profiles during boot which 7189 // might interfere with background compilation (b/28612421). 7190 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7191 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7192 // trade-off worth doing to save boot time work. 7193 int dexOptStatus = performDexOptTraced(pkg.packageName, 7194 false /* checkProfiles */, 7195 compilerFilter, 7196 false /* force */); 7197 switch (dexOptStatus) { 7198 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7199 numberOfPackagesOptimized++; 7200 break; 7201 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7202 numberOfPackagesSkipped++; 7203 break; 7204 case PackageDexOptimizer.DEX_OPT_FAILED: 7205 numberOfPackagesFailed++; 7206 break; 7207 default: 7208 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7209 break; 7210 } 7211 } 7212 7213 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7214 numberOfPackagesFailed }; 7215 } 7216 7217 @Override 7218 public void notifyPackageUse(String packageName, int reason) { 7219 synchronized (mPackages) { 7220 PackageParser.Package p = mPackages.get(packageName); 7221 if (p == null) { 7222 return; 7223 } 7224 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7225 } 7226 } 7227 7228 // TODO: this is not used nor needed. Delete it. 7229 @Override 7230 public boolean performDexOptIfNeeded(String packageName) { 7231 int dexOptStatus = performDexOptTraced(packageName, 7232 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7233 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7234 } 7235 7236 @Override 7237 public boolean performDexOpt(String packageName, 7238 boolean checkProfiles, int compileReason, boolean force) { 7239 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7240 getCompilerFilterForReason(compileReason), force); 7241 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7242 } 7243 7244 @Override 7245 public boolean performDexOptMode(String packageName, 7246 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7247 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7248 targetCompilerFilter, force); 7249 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7250 } 7251 7252 private int performDexOptTraced(String packageName, 7253 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7254 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7255 try { 7256 return performDexOptInternal(packageName, checkProfiles, 7257 targetCompilerFilter, force); 7258 } finally { 7259 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7260 } 7261 } 7262 7263 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7264 // if the package can now be considered up to date for the given filter. 7265 private int performDexOptInternal(String packageName, 7266 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7267 PackageParser.Package p; 7268 synchronized (mPackages) { 7269 p = mPackages.get(packageName); 7270 if (p == null) { 7271 // Package could not be found. Report failure. 7272 return PackageDexOptimizer.DEX_OPT_FAILED; 7273 } 7274 mPackageUsage.maybeWriteAsync(mPackages); 7275 mCompilerStats.maybeWriteAsync(); 7276 } 7277 long callingId = Binder.clearCallingIdentity(); 7278 try { 7279 synchronized (mInstallLock) { 7280 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7281 targetCompilerFilter, force); 7282 } 7283 } finally { 7284 Binder.restoreCallingIdentity(callingId); 7285 } 7286 } 7287 7288 public ArraySet<String> getOptimizablePackages() { 7289 ArraySet<String> pkgs = new ArraySet<String>(); 7290 synchronized (mPackages) { 7291 for (PackageParser.Package p : mPackages.values()) { 7292 if (PackageDexOptimizer.canOptimizePackage(p)) { 7293 pkgs.add(p.packageName); 7294 } 7295 } 7296 } 7297 return pkgs; 7298 } 7299 7300 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7301 boolean checkProfiles, String targetCompilerFilter, 7302 boolean force) { 7303 // Select the dex optimizer based on the force parameter. 7304 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7305 // allocate an object here. 7306 PackageDexOptimizer pdo = force 7307 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7308 : mPackageDexOptimizer; 7309 7310 // Optimize all dependencies first. Note: we ignore the return value and march on 7311 // on errors. 7312 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7313 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7314 if (!deps.isEmpty()) { 7315 for (PackageParser.Package depPackage : deps) { 7316 // TODO: Analyze and investigate if we (should) profile libraries. 7317 // Currently this will do a full compilation of the library by default. 7318 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7319 false /* checkProfiles */, 7320 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY), 7321 getOrCreateCompilerPackageStats(depPackage)); 7322 } 7323 } 7324 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7325 targetCompilerFilter, getOrCreateCompilerPackageStats(p)); 7326 } 7327 7328 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7329 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7330 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7331 Set<String> collectedNames = new HashSet<>(); 7332 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7333 7334 retValue.remove(p); 7335 7336 return retValue; 7337 } else { 7338 return Collections.emptyList(); 7339 } 7340 } 7341 7342 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7343 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7344 if (!collectedNames.contains(p.packageName)) { 7345 collectedNames.add(p.packageName); 7346 collected.add(p); 7347 7348 if (p.usesLibraries != null) { 7349 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7350 } 7351 if (p.usesOptionalLibraries != null) { 7352 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7353 collectedNames); 7354 } 7355 } 7356 } 7357 7358 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7359 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7360 for (String libName : libs) { 7361 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7362 if (libPkg != null) { 7363 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7364 } 7365 } 7366 } 7367 7368 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7369 synchronized (mPackages) { 7370 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7371 if (lib != null && lib.apk != null) { 7372 return mPackages.get(lib.apk); 7373 } 7374 } 7375 return null; 7376 } 7377 7378 public void shutdown() { 7379 mPackageUsage.writeNow(mPackages); 7380 mCompilerStats.writeNow(); 7381 } 7382 7383 @Override 7384 public void dumpProfiles(String packageName) { 7385 PackageParser.Package pkg; 7386 synchronized (mPackages) { 7387 pkg = mPackages.get(packageName); 7388 if (pkg == null) { 7389 throw new IllegalArgumentException("Unknown package: " + packageName); 7390 } 7391 } 7392 /* Only the shell, root, or the app user should be able to dump profiles. */ 7393 int callingUid = Binder.getCallingUid(); 7394 if (callingUid != Process.SHELL_UID && 7395 callingUid != Process.ROOT_UID && 7396 callingUid != pkg.applicationInfo.uid) { 7397 throw new SecurityException("dumpProfiles"); 7398 } 7399 7400 synchronized (mInstallLock) { 7401 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7402 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7403 try { 7404 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7405 String gid = Integer.toString(sharedGid); 7406 String codePaths = TextUtils.join(";", allCodePaths); 7407 mInstaller.dumpProfiles(gid, packageName, codePaths); 7408 } catch (InstallerException e) { 7409 Slog.w(TAG, "Failed to dump profiles", e); 7410 } 7411 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7412 } 7413 } 7414 7415 @Override 7416 public void forceDexOpt(String packageName) { 7417 enforceSystemOrRoot("forceDexOpt"); 7418 7419 PackageParser.Package pkg; 7420 synchronized (mPackages) { 7421 pkg = mPackages.get(packageName); 7422 if (pkg == null) { 7423 throw new IllegalArgumentException("Unknown package: " + packageName); 7424 } 7425 } 7426 7427 synchronized (mInstallLock) { 7428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7429 7430 // Whoever is calling forceDexOpt wants a fully compiled package. 7431 // Don't use profiles since that may cause compilation to be skipped. 7432 final int res = performDexOptInternalWithDependenciesLI(pkg, 7433 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7434 true /* force */); 7435 7436 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7437 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7438 throw new IllegalStateException("Failed to dexopt: " + res); 7439 } 7440 } 7441 } 7442 7443 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7444 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7445 Slog.w(TAG, "Unable to update from " + oldPkg.name 7446 + " to " + newPkg.packageName 7447 + ": old package not in system partition"); 7448 return false; 7449 } else if (mPackages.get(oldPkg.name) != null) { 7450 Slog.w(TAG, "Unable to update from " + oldPkg.name 7451 + " to " + newPkg.packageName 7452 + ": old package still exists"); 7453 return false; 7454 } 7455 return true; 7456 } 7457 7458 void removeCodePathLI(File codePath) { 7459 if (codePath.isDirectory()) { 7460 try { 7461 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7462 } catch (InstallerException e) { 7463 Slog.w(TAG, "Failed to remove code path", e); 7464 } 7465 } else { 7466 codePath.delete(); 7467 } 7468 } 7469 7470 private int[] resolveUserIds(int userId) { 7471 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7472 } 7473 7474 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7475 if (pkg == null) { 7476 Slog.wtf(TAG, "Package was null!", new Throwable()); 7477 return; 7478 } 7479 clearAppDataLeafLIF(pkg, userId, flags); 7480 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7481 for (int i = 0; i < childCount; i++) { 7482 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7483 } 7484 } 7485 7486 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7487 final PackageSetting ps; 7488 synchronized (mPackages) { 7489 ps = mSettings.mPackages.get(pkg.packageName); 7490 } 7491 for (int realUserId : resolveUserIds(userId)) { 7492 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7493 try { 7494 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7495 ceDataInode); 7496 } catch (InstallerException e) { 7497 Slog.w(TAG, String.valueOf(e)); 7498 } 7499 } 7500 } 7501 7502 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7503 if (pkg == null) { 7504 Slog.wtf(TAG, "Package was null!", new Throwable()); 7505 return; 7506 } 7507 destroyAppDataLeafLIF(pkg, userId, flags); 7508 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7509 for (int i = 0; i < childCount; i++) { 7510 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7511 } 7512 } 7513 7514 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7515 final PackageSetting ps; 7516 synchronized (mPackages) { 7517 ps = mSettings.mPackages.get(pkg.packageName); 7518 } 7519 for (int realUserId : resolveUserIds(userId)) { 7520 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7521 try { 7522 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7523 ceDataInode); 7524 } catch (InstallerException e) { 7525 Slog.w(TAG, String.valueOf(e)); 7526 } 7527 } 7528 } 7529 7530 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7531 if (pkg == null) { 7532 Slog.wtf(TAG, "Package was null!", new Throwable()); 7533 return; 7534 } 7535 destroyAppProfilesLeafLIF(pkg); 7536 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7537 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7538 for (int i = 0; i < childCount; i++) { 7539 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7540 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7541 true /* removeBaseMarker */); 7542 } 7543 } 7544 7545 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7546 boolean removeBaseMarker) { 7547 if (pkg.isForwardLocked()) { 7548 return; 7549 } 7550 7551 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7552 try { 7553 path = PackageManagerServiceUtils.realpath(new File(path)); 7554 } catch (IOException e) { 7555 // TODO: Should we return early here ? 7556 Slog.w(TAG, "Failed to get canonical path", e); 7557 continue; 7558 } 7559 7560 final String useMarker = path.replace('/', '@'); 7561 for (int realUserId : resolveUserIds(userId)) { 7562 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7563 if (removeBaseMarker) { 7564 File foreignUseMark = new File(profileDir, useMarker); 7565 if (foreignUseMark.exists()) { 7566 if (!foreignUseMark.delete()) { 7567 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7568 + pkg.packageName); 7569 } 7570 } 7571 } 7572 7573 File[] markers = profileDir.listFiles(); 7574 if (markers != null) { 7575 final String searchString = "@" + pkg.packageName + "@"; 7576 // We also delete all markers that contain the package name we're 7577 // uninstalling. These are associated with secondary dex-files belonging 7578 // to the package. Reconstructing the path of these dex files is messy 7579 // in general. 7580 for (File marker : markers) { 7581 if (marker.getName().indexOf(searchString) > 0) { 7582 if (!marker.delete()) { 7583 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7584 + pkg.packageName); 7585 } 7586 } 7587 } 7588 } 7589 } 7590 } 7591 } 7592 7593 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7594 try { 7595 mInstaller.destroyAppProfiles(pkg.packageName); 7596 } catch (InstallerException e) { 7597 Slog.w(TAG, String.valueOf(e)); 7598 } 7599 } 7600 7601 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7602 if (pkg == null) { 7603 Slog.wtf(TAG, "Package was null!", new Throwable()); 7604 return; 7605 } 7606 clearAppProfilesLeafLIF(pkg); 7607 // We don't remove the base foreign use marker when clearing profiles because 7608 // we will rename it when the app is updated. Unlike the actual profile contents, 7609 // the foreign use marker is good across installs. 7610 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7611 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7612 for (int i = 0; i < childCount; i++) { 7613 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7614 } 7615 } 7616 7617 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7618 try { 7619 mInstaller.clearAppProfiles(pkg.packageName); 7620 } catch (InstallerException e) { 7621 Slog.w(TAG, String.valueOf(e)); 7622 } 7623 } 7624 7625 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7626 long lastUpdateTime) { 7627 // Set parent install/update time 7628 PackageSetting ps = (PackageSetting) pkg.mExtras; 7629 if (ps != null) { 7630 ps.firstInstallTime = firstInstallTime; 7631 ps.lastUpdateTime = lastUpdateTime; 7632 } 7633 // Set children install/update time 7634 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7635 for (int i = 0; i < childCount; i++) { 7636 PackageParser.Package childPkg = pkg.childPackages.get(i); 7637 ps = (PackageSetting) childPkg.mExtras; 7638 if (ps != null) { 7639 ps.firstInstallTime = firstInstallTime; 7640 ps.lastUpdateTime = lastUpdateTime; 7641 } 7642 } 7643 } 7644 7645 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7646 PackageParser.Package changingLib) { 7647 if (file.path != null) { 7648 usesLibraryFiles.add(file.path); 7649 return; 7650 } 7651 PackageParser.Package p = mPackages.get(file.apk); 7652 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7653 // If we are doing this while in the middle of updating a library apk, 7654 // then we need to make sure to use that new apk for determining the 7655 // dependencies here. (We haven't yet finished committing the new apk 7656 // to the package manager state.) 7657 if (p == null || p.packageName.equals(changingLib.packageName)) { 7658 p = changingLib; 7659 } 7660 } 7661 if (p != null) { 7662 usesLibraryFiles.addAll(p.getAllCodePaths()); 7663 } 7664 } 7665 7666 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7667 PackageParser.Package changingLib) throws PackageManagerException { 7668 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7669 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7670 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7671 for (int i=0; i<N; i++) { 7672 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7673 if (file == null) { 7674 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7675 "Package " + pkg.packageName + " requires unavailable shared library " 7676 + pkg.usesLibraries.get(i) + "; failing!"); 7677 } 7678 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7679 } 7680 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7681 for (int i=0; i<N; i++) { 7682 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7683 if (file == null) { 7684 Slog.w(TAG, "Package " + pkg.packageName 7685 + " desires unavailable shared library " 7686 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7687 } else { 7688 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7689 } 7690 } 7691 N = usesLibraryFiles.size(); 7692 if (N > 0) { 7693 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7694 } else { 7695 pkg.usesLibraryFiles = null; 7696 } 7697 } 7698 } 7699 7700 private static boolean hasString(List<String> list, List<String> which) { 7701 if (list == null) { 7702 return false; 7703 } 7704 for (int i=list.size()-1; i>=0; i--) { 7705 for (int j=which.size()-1; j>=0; j--) { 7706 if (which.get(j).equals(list.get(i))) { 7707 return true; 7708 } 7709 } 7710 } 7711 return false; 7712 } 7713 7714 private void updateAllSharedLibrariesLPw() { 7715 for (PackageParser.Package pkg : mPackages.values()) { 7716 try { 7717 updateSharedLibrariesLPw(pkg, null); 7718 } catch (PackageManagerException e) { 7719 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7720 } 7721 } 7722 } 7723 7724 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7725 PackageParser.Package changingPkg) { 7726 ArrayList<PackageParser.Package> res = null; 7727 for (PackageParser.Package pkg : mPackages.values()) { 7728 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7729 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7730 if (res == null) { 7731 res = new ArrayList<PackageParser.Package>(); 7732 } 7733 res.add(pkg); 7734 try { 7735 updateSharedLibrariesLPw(pkg, changingPkg); 7736 } catch (PackageManagerException e) { 7737 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7738 } 7739 } 7740 } 7741 return res; 7742 } 7743 7744 /** 7745 * Derive the value of the {@code cpuAbiOverride} based on the provided 7746 * value and an optional stored value from the package settings. 7747 */ 7748 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7749 String cpuAbiOverride = null; 7750 7751 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7752 cpuAbiOverride = null; 7753 } else if (abiOverride != null) { 7754 cpuAbiOverride = abiOverride; 7755 } else if (settings != null) { 7756 cpuAbiOverride = settings.cpuAbiOverrideString; 7757 } 7758 7759 return cpuAbiOverride; 7760 } 7761 7762 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7763 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7764 throws PackageManagerException { 7765 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7766 // If the package has children and this is the first dive in the function 7767 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7768 // whether all packages (parent and children) would be successfully scanned 7769 // before the actual scan since scanning mutates internal state and we want 7770 // to atomically install the package and its children. 7771 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7772 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7773 scanFlags |= SCAN_CHECK_ONLY; 7774 } 7775 } else { 7776 scanFlags &= ~SCAN_CHECK_ONLY; 7777 } 7778 7779 final PackageParser.Package scannedPkg; 7780 try { 7781 // Scan the parent 7782 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7783 // Scan the children 7784 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7785 for (int i = 0; i < childCount; i++) { 7786 PackageParser.Package childPkg = pkg.childPackages.get(i); 7787 scanPackageLI(childPkg, policyFlags, 7788 scanFlags, currentTime, user); 7789 } 7790 } finally { 7791 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7792 } 7793 7794 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7795 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7796 } 7797 7798 return scannedPkg; 7799 } 7800 7801 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7802 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7803 boolean success = false; 7804 try { 7805 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7806 currentTime, user); 7807 success = true; 7808 return res; 7809 } finally { 7810 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7811 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7812 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7813 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7814 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7815 } 7816 } 7817 } 7818 7819 /** 7820 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7821 */ 7822 private static boolean apkHasCode(String fileName) { 7823 StrictJarFile jarFile = null; 7824 try { 7825 jarFile = new StrictJarFile(fileName, 7826 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7827 return jarFile.findEntry("classes.dex") != null; 7828 } catch (IOException ignore) { 7829 } finally { 7830 try { 7831 if (jarFile != null) { 7832 jarFile.close(); 7833 } 7834 } catch (IOException ignore) {} 7835 } 7836 return false; 7837 } 7838 7839 /** 7840 * Enforces code policy for the package. This ensures that if an APK has 7841 * declared hasCode="true" in its manifest that the APK actually contains 7842 * code. 7843 * 7844 * @throws PackageManagerException If bytecode could not be found when it should exist 7845 */ 7846 private static void enforceCodePolicy(PackageParser.Package pkg) 7847 throws PackageManagerException { 7848 final boolean shouldHaveCode = 7849 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7850 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7851 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7852 "Package " + pkg.baseCodePath + " code is missing"); 7853 } 7854 7855 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7856 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7857 final boolean splitShouldHaveCode = 7858 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7859 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7860 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7861 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7862 } 7863 } 7864 } 7865 } 7866 7867 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7868 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7869 throws PackageManagerException { 7870 final File scanFile = new File(pkg.codePath); 7871 if (pkg.applicationInfo.getCodePath() == null || 7872 pkg.applicationInfo.getResourcePath() == null) { 7873 // Bail out. The resource and code paths haven't been set. 7874 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7875 "Code and resource paths haven't been set correctly"); 7876 } 7877 7878 // Apply policy 7879 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7880 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7881 if (pkg.applicationInfo.isDirectBootAware()) { 7882 // we're direct boot aware; set for all components 7883 for (PackageParser.Service s : pkg.services) { 7884 s.info.encryptionAware = s.info.directBootAware = true; 7885 } 7886 for (PackageParser.Provider p : pkg.providers) { 7887 p.info.encryptionAware = p.info.directBootAware = true; 7888 } 7889 for (PackageParser.Activity a : pkg.activities) { 7890 a.info.encryptionAware = a.info.directBootAware = true; 7891 } 7892 for (PackageParser.Activity r : pkg.receivers) { 7893 r.info.encryptionAware = r.info.directBootAware = true; 7894 } 7895 } 7896 } else { 7897 // Only allow system apps to be flagged as core apps. 7898 pkg.coreApp = false; 7899 // clear flags not applicable to regular apps 7900 pkg.applicationInfo.privateFlags &= 7901 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7902 pkg.applicationInfo.privateFlags &= 7903 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7904 } 7905 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7906 7907 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7908 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7909 } 7910 7911 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7912 enforceCodePolicy(pkg); 7913 } 7914 7915 if (mCustomResolverComponentName != null && 7916 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7917 setUpCustomResolverActivity(pkg); 7918 } 7919 7920 if (pkg.packageName.equals("android")) { 7921 synchronized (mPackages) { 7922 if (mAndroidApplication != null) { 7923 Slog.w(TAG, "*************************************************"); 7924 Slog.w(TAG, "Core android package being redefined. Skipping."); 7925 Slog.w(TAG, " file=" + scanFile); 7926 Slog.w(TAG, "*************************************************"); 7927 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7928 "Core android package being redefined. Skipping."); 7929 } 7930 7931 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7932 // Set up information for our fall-back user intent resolution activity. 7933 mPlatformPackage = pkg; 7934 pkg.mVersionCode = mSdkVersion; 7935 mAndroidApplication = pkg.applicationInfo; 7936 7937 if (!mResolverReplaced) { 7938 mResolveActivity.applicationInfo = mAndroidApplication; 7939 mResolveActivity.name = ResolverActivity.class.getName(); 7940 mResolveActivity.packageName = mAndroidApplication.packageName; 7941 mResolveActivity.processName = "system:ui"; 7942 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7943 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7944 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7945 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7946 mResolveActivity.exported = true; 7947 mResolveActivity.enabled = true; 7948 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7949 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7950 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7951 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7952 | ActivityInfo.CONFIG_ORIENTATION 7953 | ActivityInfo.CONFIG_KEYBOARD 7954 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7955 mResolveInfo.activityInfo = mResolveActivity; 7956 mResolveInfo.priority = 0; 7957 mResolveInfo.preferredOrder = 0; 7958 mResolveInfo.match = 0; 7959 mResolveComponentName = new ComponentName( 7960 mAndroidApplication.packageName, mResolveActivity.name); 7961 } 7962 } 7963 } 7964 } 7965 7966 if (DEBUG_PACKAGE_SCANNING) { 7967 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7968 Log.d(TAG, "Scanning package " + pkg.packageName); 7969 } 7970 7971 synchronized (mPackages) { 7972 if (mPackages.containsKey(pkg.packageName) 7973 || mSharedLibraries.containsKey(pkg.packageName)) { 7974 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7975 "Application package " + pkg.packageName 7976 + " already installed. Skipping duplicate."); 7977 } 7978 7979 // If we're only installing presumed-existing packages, require that the 7980 // scanned APK is both already known and at the path previously established 7981 // for it. Previously unknown packages we pick up normally, but if we have an 7982 // a priori expectation about this package's install presence, enforce it. 7983 // With a singular exception for new system packages. When an OTA contains 7984 // a new system package, we allow the codepath to change from a system location 7985 // to the user-installed location. If we don't allow this change, any newer, 7986 // user-installed version of the application will be ignored. 7987 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7988 if (mExpectingBetter.containsKey(pkg.packageName)) { 7989 logCriticalInfo(Log.WARN, 7990 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7991 } else { 7992 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7993 if (known != null) { 7994 if (DEBUG_PACKAGE_SCANNING) { 7995 Log.d(TAG, "Examining " + pkg.codePath 7996 + " and requiring known paths " + known.codePathString 7997 + " & " + known.resourcePathString); 7998 } 7999 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8000 || !pkg.applicationInfo.getResourcePath().equals( 8001 known.resourcePathString)) { 8002 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8003 "Application package " + pkg.packageName 8004 + " found at " + pkg.applicationInfo.getCodePath() 8005 + " but expected at " + known.codePathString 8006 + "; ignoring."); 8007 } 8008 } 8009 } 8010 } 8011 } 8012 8013 // Initialize package source and resource directories 8014 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8015 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8016 8017 SharedUserSetting suid = null; 8018 PackageSetting pkgSetting = null; 8019 8020 if (!isSystemApp(pkg)) { 8021 // Only system apps can use these features. 8022 pkg.mOriginalPackages = null; 8023 pkg.mRealPackage = null; 8024 pkg.mAdoptPermissions = null; 8025 } 8026 8027 // Getting the package setting may have a side-effect, so if we 8028 // are only checking if scan would succeed, stash a copy of the 8029 // old setting to restore at the end. 8030 PackageSetting nonMutatedPs = null; 8031 8032 // writer 8033 synchronized (mPackages) { 8034 if (pkg.mSharedUserId != null) { 8035 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8036 if (suid == null) { 8037 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8038 "Creating application package " + pkg.packageName 8039 + " for shared user failed"); 8040 } 8041 if (DEBUG_PACKAGE_SCANNING) { 8042 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8043 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8044 + "): packages=" + suid.packages); 8045 } 8046 } 8047 8048 // Check if we are renaming from an original package name. 8049 PackageSetting origPackage = null; 8050 String realName = null; 8051 if (pkg.mOriginalPackages != null) { 8052 // This package may need to be renamed to a previously 8053 // installed name. Let's check on that... 8054 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8055 if (pkg.mOriginalPackages.contains(renamed)) { 8056 // This package had originally been installed as the 8057 // original name, and we have already taken care of 8058 // transitioning to the new one. Just update the new 8059 // one to continue using the old name. 8060 realName = pkg.mRealPackage; 8061 if (!pkg.packageName.equals(renamed)) { 8062 // Callers into this function may have already taken 8063 // care of renaming the package; only do it here if 8064 // it is not already done. 8065 pkg.setPackageName(renamed); 8066 } 8067 8068 } else { 8069 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8070 if ((origPackage = mSettings.peekPackageLPr( 8071 pkg.mOriginalPackages.get(i))) != null) { 8072 // We do have the package already installed under its 8073 // original name... should we use it? 8074 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8075 // New package is not compatible with original. 8076 origPackage = null; 8077 continue; 8078 } else if (origPackage.sharedUser != null) { 8079 // Make sure uid is compatible between packages. 8080 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8081 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8082 + " to " + pkg.packageName + ": old uid " 8083 + origPackage.sharedUser.name 8084 + " differs from " + pkg.mSharedUserId); 8085 origPackage = null; 8086 continue; 8087 } 8088 // TODO: Add case when shared user id is added [b/28144775] 8089 } else { 8090 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8091 + pkg.packageName + " to old name " + origPackage.name); 8092 } 8093 break; 8094 } 8095 } 8096 } 8097 } 8098 8099 if (mTransferedPackages.contains(pkg.packageName)) { 8100 Slog.w(TAG, "Package " + pkg.packageName 8101 + " was transferred to another, but its .apk remains"); 8102 } 8103 8104 // See comments in nonMutatedPs declaration 8105 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8106 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8107 if (foundPs != null) { 8108 nonMutatedPs = new PackageSetting(foundPs); 8109 } 8110 } 8111 8112 // Just create the setting, don't add it yet. For already existing packages 8113 // the PkgSetting exists already and doesn't have to be created. 8114 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8115 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8116 pkg.applicationInfo.primaryCpuAbi, 8117 pkg.applicationInfo.secondaryCpuAbi, 8118 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8119 user, false); 8120 if (pkgSetting == null) { 8121 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8122 "Creating application package " + pkg.packageName + " failed"); 8123 } 8124 8125 if (pkgSetting.origPackage != null) { 8126 // If we are first transitioning from an original package, 8127 // fix up the new package's name now. We need to do this after 8128 // looking up the package under its new name, so getPackageLP 8129 // can take care of fiddling things correctly. 8130 pkg.setPackageName(origPackage.name); 8131 8132 // File a report about this. 8133 String msg = "New package " + pkgSetting.realName 8134 + " renamed to replace old package " + pkgSetting.name; 8135 reportSettingsProblem(Log.WARN, msg); 8136 8137 // Make a note of it. 8138 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8139 mTransferedPackages.add(origPackage.name); 8140 } 8141 8142 // No longer need to retain this. 8143 pkgSetting.origPackage = null; 8144 } 8145 8146 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8147 // Make a note of it. 8148 mTransferedPackages.add(pkg.packageName); 8149 } 8150 8151 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8152 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8153 } 8154 8155 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8156 // Check all shared libraries and map to their actual file path. 8157 // We only do this here for apps not on a system dir, because those 8158 // are the only ones that can fail an install due to this. We 8159 // will take care of the system apps by updating all of their 8160 // library paths after the scan is done. 8161 updateSharedLibrariesLPw(pkg, null); 8162 } 8163 8164 if (mFoundPolicyFile) { 8165 SELinuxMMAC.assignSeinfoValue(pkg); 8166 } 8167 8168 pkg.applicationInfo.uid = pkgSetting.appId; 8169 pkg.mExtras = pkgSetting; 8170 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8171 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8172 // We just determined the app is signed correctly, so bring 8173 // over the latest parsed certs. 8174 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8175 } else { 8176 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8177 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8178 "Package " + pkg.packageName + " upgrade keys do not match the " 8179 + "previously installed version"); 8180 } else { 8181 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8182 String msg = "System package " + pkg.packageName 8183 + " signature changed; retaining data."; 8184 reportSettingsProblem(Log.WARN, msg); 8185 } 8186 } 8187 } else { 8188 try { 8189 verifySignaturesLP(pkgSetting, pkg); 8190 // We just determined the app is signed correctly, so bring 8191 // over the latest parsed certs. 8192 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8193 } catch (PackageManagerException e) { 8194 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8195 throw e; 8196 } 8197 // The signature has changed, but this package is in the system 8198 // image... let's recover! 8199 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8200 // However... if this package is part of a shared user, but it 8201 // doesn't match the signature of the shared user, let's fail. 8202 // What this means is that you can't change the signatures 8203 // associated with an overall shared user, which doesn't seem all 8204 // that unreasonable. 8205 if (pkgSetting.sharedUser != null) { 8206 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8207 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8208 throw new PackageManagerException( 8209 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8210 "Signature mismatch for shared user: " 8211 + pkgSetting.sharedUser); 8212 } 8213 } 8214 // File a report about this. 8215 String msg = "System package " + pkg.packageName 8216 + " signature changed; retaining data."; 8217 reportSettingsProblem(Log.WARN, msg); 8218 } 8219 } 8220 // Verify that this new package doesn't have any content providers 8221 // that conflict with existing packages. Only do this if the 8222 // package isn't already installed, since we don't want to break 8223 // things that are installed. 8224 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8225 final int N = pkg.providers.size(); 8226 int i; 8227 for (i=0; i<N; i++) { 8228 PackageParser.Provider p = pkg.providers.get(i); 8229 if (p.info.authority != null) { 8230 String names[] = p.info.authority.split(";"); 8231 for (int j = 0; j < names.length; j++) { 8232 if (mProvidersByAuthority.containsKey(names[j])) { 8233 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8234 final String otherPackageName = 8235 ((other != null && other.getComponentName() != null) ? 8236 other.getComponentName().getPackageName() : "?"); 8237 throw new PackageManagerException( 8238 INSTALL_FAILED_CONFLICTING_PROVIDER, 8239 "Can't install because provider name " + names[j] 8240 + " (in package " + pkg.applicationInfo.packageName 8241 + ") is already used by " + otherPackageName); 8242 } 8243 } 8244 } 8245 } 8246 } 8247 8248 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8249 // This package wants to adopt ownership of permissions from 8250 // another package. 8251 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8252 final String origName = pkg.mAdoptPermissions.get(i); 8253 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8254 if (orig != null) { 8255 if (verifyPackageUpdateLPr(orig, pkg)) { 8256 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8257 + pkg.packageName); 8258 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8259 } 8260 } 8261 } 8262 } 8263 } 8264 8265 final String pkgName = pkg.packageName; 8266 8267 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8268 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8269 pkg.applicationInfo.processName = fixProcessName( 8270 pkg.applicationInfo.packageName, 8271 pkg.applicationInfo.processName, 8272 pkg.applicationInfo.uid); 8273 8274 if (pkg != mPlatformPackage) { 8275 // Get all of our default paths setup 8276 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8277 } 8278 8279 final String path = scanFile.getPath(); 8280 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8281 8282 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8283 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8284 8285 // Some system apps still use directory structure for native libraries 8286 // in which case we might end up not detecting abi solely based on apk 8287 // structure. Try to detect abi based on directory structure. 8288 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8289 pkg.applicationInfo.primaryCpuAbi == null) { 8290 setBundledAppAbisAndRoots(pkg, pkgSetting); 8291 setNativeLibraryPaths(pkg); 8292 } 8293 8294 } else { 8295 if ((scanFlags & SCAN_MOVE) != 0) { 8296 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8297 // but we already have this packages package info in the PackageSetting. We just 8298 // use that and derive the native library path based on the new codepath. 8299 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8300 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8301 } 8302 8303 // Set native library paths again. For moves, the path will be updated based on the 8304 // ABIs we've determined above. For non-moves, the path will be updated based on the 8305 // ABIs we determined during compilation, but the path will depend on the final 8306 // package path (after the rename away from the stage path). 8307 setNativeLibraryPaths(pkg); 8308 } 8309 8310 // This is a special case for the "system" package, where the ABI is 8311 // dictated by the zygote configuration (and init.rc). We should keep track 8312 // of this ABI so that we can deal with "normal" applications that run under 8313 // the same UID correctly. 8314 if (mPlatformPackage == pkg) { 8315 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8316 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8317 } 8318 8319 // If there's a mismatch between the abi-override in the package setting 8320 // and the abiOverride specified for the install. Warn about this because we 8321 // would've already compiled the app without taking the package setting into 8322 // account. 8323 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8324 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8325 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8326 " for package " + pkg.packageName); 8327 } 8328 } 8329 8330 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8331 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8332 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8333 8334 // Copy the derived override back to the parsed package, so that we can 8335 // update the package settings accordingly. 8336 pkg.cpuAbiOverride = cpuAbiOverride; 8337 8338 if (DEBUG_ABI_SELECTION) { 8339 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8340 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8341 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8342 } 8343 8344 // Push the derived path down into PackageSettings so we know what to 8345 // clean up at uninstall time. 8346 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8347 8348 if (DEBUG_ABI_SELECTION) { 8349 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8350 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8351 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8352 } 8353 8354 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8355 // We don't do this here during boot because we can do it all 8356 // at once after scanning all existing packages. 8357 // 8358 // We also do this *before* we perform dexopt on this package, so that 8359 // we can avoid redundant dexopts, and also to make sure we've got the 8360 // code and package path correct. 8361 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8362 pkg, true /* boot complete */); 8363 } 8364 8365 if (mFactoryTest && pkg.requestedPermissions.contains( 8366 android.Manifest.permission.FACTORY_TEST)) { 8367 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8368 } 8369 8370 ArrayList<PackageParser.Package> clientLibPkgs = null; 8371 8372 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8373 if (nonMutatedPs != null) { 8374 synchronized (mPackages) { 8375 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8376 } 8377 } 8378 return pkg; 8379 } 8380 8381 // Only privileged apps and updated privileged apps can add child packages. 8382 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8383 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8384 throw new PackageManagerException("Only privileged apps and updated " 8385 + "privileged apps can add child packages. Ignoring package " 8386 + pkg.packageName); 8387 } 8388 final int childCount = pkg.childPackages.size(); 8389 for (int i = 0; i < childCount; i++) { 8390 PackageParser.Package childPkg = pkg.childPackages.get(i); 8391 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8392 childPkg.packageName)) { 8393 throw new PackageManagerException("Cannot override a child package of " 8394 + "another disabled system app. Ignoring package " + pkg.packageName); 8395 } 8396 } 8397 } 8398 8399 // writer 8400 synchronized (mPackages) { 8401 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8402 // Only system apps can add new shared libraries. 8403 if (pkg.libraryNames != null) { 8404 for (int i=0; i<pkg.libraryNames.size(); i++) { 8405 String name = pkg.libraryNames.get(i); 8406 boolean allowed = false; 8407 if (pkg.isUpdatedSystemApp()) { 8408 // New library entries can only be added through the 8409 // system image. This is important to get rid of a lot 8410 // of nasty edge cases: for example if we allowed a non- 8411 // system update of the app to add a library, then uninstalling 8412 // the update would make the library go away, and assumptions 8413 // we made such as through app install filtering would now 8414 // have allowed apps on the device which aren't compatible 8415 // with it. Better to just have the restriction here, be 8416 // conservative, and create many fewer cases that can negatively 8417 // impact the user experience. 8418 final PackageSetting sysPs = mSettings 8419 .getDisabledSystemPkgLPr(pkg.packageName); 8420 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8421 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8422 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8423 allowed = true; 8424 break; 8425 } 8426 } 8427 } 8428 } else { 8429 allowed = true; 8430 } 8431 if (allowed) { 8432 if (!mSharedLibraries.containsKey(name)) { 8433 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8434 } else if (!name.equals(pkg.packageName)) { 8435 Slog.w(TAG, "Package " + pkg.packageName + " library " 8436 + name + " already exists; skipping"); 8437 } 8438 } else { 8439 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8440 + name + " that is not declared on system image; skipping"); 8441 } 8442 } 8443 if ((scanFlags & SCAN_BOOTING) == 0) { 8444 // If we are not booting, we need to update any applications 8445 // that are clients of our shared library. If we are booting, 8446 // this will all be done once the scan is complete. 8447 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8448 } 8449 } 8450 } 8451 } 8452 8453 if ((scanFlags & SCAN_BOOTING) != 0) { 8454 // No apps can run during boot scan, so they don't need to be frozen 8455 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8456 // Caller asked to not kill app, so it's probably not frozen 8457 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8458 // Caller asked us to ignore frozen check for some reason; they 8459 // probably didn't know the package name 8460 } else { 8461 // We're doing major surgery on this package, so it better be frozen 8462 // right now to keep it from launching 8463 checkPackageFrozen(pkgName); 8464 } 8465 8466 // Also need to kill any apps that are dependent on the library. 8467 if (clientLibPkgs != null) { 8468 for (int i=0; i<clientLibPkgs.size(); i++) { 8469 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8470 killApplication(clientPkg.applicationInfo.packageName, 8471 clientPkg.applicationInfo.uid, "update lib"); 8472 } 8473 } 8474 8475 // Make sure we're not adding any bogus keyset info 8476 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8477 ksms.assertScannedPackageValid(pkg); 8478 8479 // writer 8480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8481 8482 boolean createIdmapFailed = false; 8483 synchronized (mPackages) { 8484 // We don't expect installation to fail beyond this point 8485 8486 if (pkgSetting.pkg != null) { 8487 // Note that |user| might be null during the initial boot scan. If a codePath 8488 // for an app has changed during a boot scan, it's due to an app update that's 8489 // part of the system partition and marker changes must be applied to all users. 8490 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8491 (user != null) ? user : UserHandle.ALL); 8492 } 8493 8494 // Add the new setting to mSettings 8495 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8496 // Add the new setting to mPackages 8497 mPackages.put(pkg.applicationInfo.packageName, pkg); 8498 // Make sure we don't accidentally delete its data. 8499 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8500 while (iter.hasNext()) { 8501 PackageCleanItem item = iter.next(); 8502 if (pkgName.equals(item.packageName)) { 8503 iter.remove(); 8504 } 8505 } 8506 8507 // Take care of first install / last update times. 8508 if (currentTime != 0) { 8509 if (pkgSetting.firstInstallTime == 0) { 8510 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8511 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8512 pkgSetting.lastUpdateTime = currentTime; 8513 } 8514 } else if (pkgSetting.firstInstallTime == 0) { 8515 // We need *something*. Take time time stamp of the file. 8516 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8517 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8518 if (scanFileTime != pkgSetting.timeStamp) { 8519 // A package on the system image has changed; consider this 8520 // to be an update. 8521 pkgSetting.lastUpdateTime = scanFileTime; 8522 } 8523 } 8524 8525 // Add the package's KeySets to the global KeySetManagerService 8526 ksms.addScannedPackageLPw(pkg); 8527 8528 int N = pkg.providers.size(); 8529 StringBuilder r = null; 8530 int i; 8531 for (i=0; i<N; i++) { 8532 PackageParser.Provider p = pkg.providers.get(i); 8533 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8534 p.info.processName, pkg.applicationInfo.uid); 8535 mProviders.addProvider(p); 8536 p.syncable = p.info.isSyncable; 8537 if (p.info.authority != null) { 8538 String names[] = p.info.authority.split(";"); 8539 p.info.authority = null; 8540 for (int j = 0; j < names.length; j++) { 8541 if (j == 1 && p.syncable) { 8542 // We only want the first authority for a provider to possibly be 8543 // syncable, so if we already added this provider using a different 8544 // authority clear the syncable flag. We copy the provider before 8545 // changing it because the mProviders object contains a reference 8546 // to a provider that we don't want to change. 8547 // Only do this for the second authority since the resulting provider 8548 // object can be the same for all future authorities for this provider. 8549 p = new PackageParser.Provider(p); 8550 p.syncable = false; 8551 } 8552 if (!mProvidersByAuthority.containsKey(names[j])) { 8553 mProvidersByAuthority.put(names[j], p); 8554 if (p.info.authority == null) { 8555 p.info.authority = names[j]; 8556 } else { 8557 p.info.authority = p.info.authority + ";" + names[j]; 8558 } 8559 if (DEBUG_PACKAGE_SCANNING) { 8560 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8561 Log.d(TAG, "Registered content provider: " + names[j] 8562 + ", className = " + p.info.name + ", isSyncable = " 8563 + p.info.isSyncable); 8564 } 8565 } else { 8566 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8567 Slog.w(TAG, "Skipping provider name " + names[j] + 8568 " (in package " + pkg.applicationInfo.packageName + 8569 "): name already used by " 8570 + ((other != null && other.getComponentName() != null) 8571 ? other.getComponentName().getPackageName() : "?")); 8572 } 8573 } 8574 } 8575 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8576 if (r == null) { 8577 r = new StringBuilder(256); 8578 } else { 8579 r.append(' '); 8580 } 8581 r.append(p.info.name); 8582 } 8583 } 8584 if (r != null) { 8585 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8586 } 8587 8588 N = pkg.services.size(); 8589 r = null; 8590 for (i=0; i<N; i++) { 8591 PackageParser.Service s = pkg.services.get(i); 8592 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8593 s.info.processName, pkg.applicationInfo.uid); 8594 mServices.addService(s); 8595 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8596 if (r == null) { 8597 r = new StringBuilder(256); 8598 } else { 8599 r.append(' '); 8600 } 8601 r.append(s.info.name); 8602 } 8603 } 8604 if (r != null) { 8605 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8606 } 8607 8608 N = pkg.receivers.size(); 8609 r = null; 8610 for (i=0; i<N; i++) { 8611 PackageParser.Activity a = pkg.receivers.get(i); 8612 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8613 a.info.processName, pkg.applicationInfo.uid); 8614 mReceivers.addActivity(a, "receiver"); 8615 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8616 if (r == null) { 8617 r = new StringBuilder(256); 8618 } else { 8619 r.append(' '); 8620 } 8621 r.append(a.info.name); 8622 } 8623 } 8624 if (r != null) { 8625 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8626 } 8627 8628 N = pkg.activities.size(); 8629 r = null; 8630 for (i=0; i<N; i++) { 8631 PackageParser.Activity a = pkg.activities.get(i); 8632 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8633 a.info.processName, pkg.applicationInfo.uid); 8634 mActivities.addActivity(a, "activity"); 8635 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8636 if (r == null) { 8637 r = new StringBuilder(256); 8638 } else { 8639 r.append(' '); 8640 } 8641 r.append(a.info.name); 8642 } 8643 } 8644 if (r != null) { 8645 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8646 } 8647 8648 N = pkg.permissionGroups.size(); 8649 r = null; 8650 for (i=0; i<N; i++) { 8651 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8652 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8653 if (cur == null) { 8654 mPermissionGroups.put(pg.info.name, pg); 8655 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8656 if (r == null) { 8657 r = new StringBuilder(256); 8658 } else { 8659 r.append(' '); 8660 } 8661 r.append(pg.info.name); 8662 } 8663 } else { 8664 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8665 + pg.info.packageName + " ignored: original from " 8666 + cur.info.packageName); 8667 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8668 if (r == null) { 8669 r = new StringBuilder(256); 8670 } else { 8671 r.append(' '); 8672 } 8673 r.append("DUP:"); 8674 r.append(pg.info.name); 8675 } 8676 } 8677 } 8678 if (r != null) { 8679 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8680 } 8681 8682 N = pkg.permissions.size(); 8683 r = null; 8684 for (i=0; i<N; i++) { 8685 PackageParser.Permission p = pkg.permissions.get(i); 8686 8687 // Assume by default that we did not install this permission into the system. 8688 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8689 8690 // Now that permission groups have a special meaning, we ignore permission 8691 // groups for legacy apps to prevent unexpected behavior. In particular, 8692 // permissions for one app being granted to someone just becase they happen 8693 // to be in a group defined by another app (before this had no implications). 8694 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8695 p.group = mPermissionGroups.get(p.info.group); 8696 // Warn for a permission in an unknown group. 8697 if (p.info.group != null && p.group == null) { 8698 Slog.w(TAG, "Permission " + p.info.name + " from package " 8699 + p.info.packageName + " in an unknown group " + p.info.group); 8700 } 8701 } 8702 8703 ArrayMap<String, BasePermission> permissionMap = 8704 p.tree ? mSettings.mPermissionTrees 8705 : mSettings.mPermissions; 8706 BasePermission bp = permissionMap.get(p.info.name); 8707 8708 // Allow system apps to redefine non-system permissions 8709 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8710 final boolean currentOwnerIsSystem = (bp.perm != null 8711 && isSystemApp(bp.perm.owner)); 8712 if (isSystemApp(p.owner)) { 8713 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8714 // It's a built-in permission and no owner, take ownership now 8715 bp.packageSetting = pkgSetting; 8716 bp.perm = p; 8717 bp.uid = pkg.applicationInfo.uid; 8718 bp.sourcePackage = p.info.packageName; 8719 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8720 } else if (!currentOwnerIsSystem) { 8721 String msg = "New decl " + p.owner + " of permission " 8722 + p.info.name + " is system; overriding " + bp.sourcePackage; 8723 reportSettingsProblem(Log.WARN, msg); 8724 bp = null; 8725 } 8726 } 8727 } 8728 8729 if (bp == null) { 8730 bp = new BasePermission(p.info.name, p.info.packageName, 8731 BasePermission.TYPE_NORMAL); 8732 permissionMap.put(p.info.name, bp); 8733 } 8734 8735 if (bp.perm == null) { 8736 if (bp.sourcePackage == null 8737 || bp.sourcePackage.equals(p.info.packageName)) { 8738 BasePermission tree = findPermissionTreeLP(p.info.name); 8739 if (tree == null 8740 || tree.sourcePackage.equals(p.info.packageName)) { 8741 bp.packageSetting = pkgSetting; 8742 bp.perm = p; 8743 bp.uid = pkg.applicationInfo.uid; 8744 bp.sourcePackage = p.info.packageName; 8745 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8746 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8747 if (r == null) { 8748 r = new StringBuilder(256); 8749 } else { 8750 r.append(' '); 8751 } 8752 r.append(p.info.name); 8753 } 8754 } else { 8755 Slog.w(TAG, "Permission " + p.info.name + " from package " 8756 + p.info.packageName + " ignored: base tree " 8757 + tree.name + " is from package " 8758 + tree.sourcePackage); 8759 } 8760 } else { 8761 Slog.w(TAG, "Permission " + p.info.name + " from package " 8762 + p.info.packageName + " ignored: original from " 8763 + bp.sourcePackage); 8764 } 8765 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8766 if (r == null) { 8767 r = new StringBuilder(256); 8768 } else { 8769 r.append(' '); 8770 } 8771 r.append("DUP:"); 8772 r.append(p.info.name); 8773 } 8774 if (bp.perm == p) { 8775 bp.protectionLevel = p.info.protectionLevel; 8776 } 8777 } 8778 8779 if (r != null) { 8780 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8781 } 8782 8783 N = pkg.instrumentation.size(); 8784 r = null; 8785 for (i=0; i<N; i++) { 8786 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8787 a.info.packageName = pkg.applicationInfo.packageName; 8788 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8789 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8790 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8791 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8792 a.info.dataDir = pkg.applicationInfo.dataDir; 8793 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8794 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8795 8796 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8797 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8798 mInstrumentation.put(a.getComponentName(), a); 8799 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8800 if (r == null) { 8801 r = new StringBuilder(256); 8802 } else { 8803 r.append(' '); 8804 } 8805 r.append(a.info.name); 8806 } 8807 } 8808 if (r != null) { 8809 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8810 } 8811 8812 if (pkg.protectedBroadcasts != null) { 8813 N = pkg.protectedBroadcasts.size(); 8814 for (i=0; i<N; i++) { 8815 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8816 } 8817 } 8818 8819 pkgSetting.setTimeStamp(scanFileTime); 8820 8821 // Create idmap files for pairs of (packages, overlay packages). 8822 // Note: "android", ie framework-res.apk, is handled by native layers. 8823 if (pkg.mOverlayTarget != null) { 8824 // This is an overlay package. 8825 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8826 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8827 mOverlays.put(pkg.mOverlayTarget, 8828 new ArrayMap<String, PackageParser.Package>()); 8829 } 8830 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8831 map.put(pkg.packageName, pkg); 8832 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8833 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8834 createIdmapFailed = true; 8835 } 8836 } 8837 } else if (mOverlays.containsKey(pkg.packageName) && 8838 !pkg.packageName.equals("android")) { 8839 // This is a regular package, with one or more known overlay packages. 8840 createIdmapsForPackageLI(pkg); 8841 } 8842 } 8843 8844 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8845 8846 if (createIdmapFailed) { 8847 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8848 "scanPackageLI failed to createIdmap"); 8849 } 8850 return pkg; 8851 } 8852 8853 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8854 PackageParser.Package update, UserHandle user) { 8855 if (existing.applicationInfo == null || update.applicationInfo == null) { 8856 // This isn't due to an app installation. 8857 return; 8858 } 8859 8860 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8861 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8862 8863 // The codePath hasn't changed, so there's nothing for us to do. 8864 if (Objects.equals(oldCodePath, newCodePath)) { 8865 return; 8866 } 8867 8868 File canonicalNewCodePath; 8869 try { 8870 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 8871 } catch (IOException e) { 8872 Slog.w(TAG, "Failed to get canonical path.", e); 8873 return; 8874 } 8875 8876 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 8877 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 8878 // that the last component of the path (i.e, the name) doesn't need canonicalization 8879 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 8880 // but may change in the future. Hopefully this function won't exist at that point. 8881 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 8882 oldCodePath.getName()); 8883 8884 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 8885 // with "@". 8886 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 8887 if (!oldMarkerPrefix.endsWith("@")) { 8888 oldMarkerPrefix += "@"; 8889 } 8890 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 8891 if (!newMarkerPrefix.endsWith("@")) { 8892 newMarkerPrefix += "@"; 8893 } 8894 8895 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 8896 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 8897 for (String updatedPath : updatedPaths) { 8898 String updatedPathName = new File(updatedPath).getName(); 8899 markerSuffixes.add(updatedPathName.replace('/', '@')); 8900 } 8901 8902 for (int userId : resolveUserIds(user.getIdentifier())) { 8903 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 8904 8905 for (String markerSuffix : markerSuffixes) { 8906 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 8907 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 8908 if (oldForeignUseMark.exists()) { 8909 try { 8910 Os.rename(oldForeignUseMark.getAbsolutePath(), 8911 newForeignUseMark.getAbsolutePath()); 8912 } catch (ErrnoException e) { 8913 Slog.w(TAG, "Failed to rename foreign use marker", e); 8914 oldForeignUseMark.delete(); 8915 } 8916 } 8917 } 8918 } 8919 } 8920 8921 /** 8922 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8923 * is derived purely on the basis of the contents of {@code scanFile} and 8924 * {@code cpuAbiOverride}. 8925 * 8926 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8927 */ 8928 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8929 String cpuAbiOverride, boolean extractLibs) 8930 throws PackageManagerException { 8931 // TODO: We can probably be smarter about this stuff. For installed apps, 8932 // we can calculate this information at install time once and for all. For 8933 // system apps, we can probably assume that this information doesn't change 8934 // after the first boot scan. As things stand, we do lots of unnecessary work. 8935 8936 // Give ourselves some initial paths; we'll come back for another 8937 // pass once we've determined ABI below. 8938 setNativeLibraryPaths(pkg); 8939 8940 // We would never need to extract libs for forward-locked and external packages, 8941 // since the container service will do it for us. We shouldn't attempt to 8942 // extract libs from system app when it was not updated. 8943 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8944 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8945 extractLibs = false; 8946 } 8947 8948 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8949 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8950 8951 NativeLibraryHelper.Handle handle = null; 8952 try { 8953 handle = NativeLibraryHelper.Handle.create(pkg); 8954 // TODO(multiArch): This can be null for apps that didn't go through the 8955 // usual installation process. We can calculate it again, like we 8956 // do during install time. 8957 // 8958 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8959 // unnecessary. 8960 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8961 8962 // Null out the abis so that they can be recalculated. 8963 pkg.applicationInfo.primaryCpuAbi = null; 8964 pkg.applicationInfo.secondaryCpuAbi = null; 8965 if (isMultiArch(pkg.applicationInfo)) { 8966 // Warn if we've set an abiOverride for multi-lib packages.. 8967 // By definition, we need to copy both 32 and 64 bit libraries for 8968 // such packages. 8969 if (pkg.cpuAbiOverride != null 8970 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8971 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8972 } 8973 8974 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8975 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8976 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8977 if (extractLibs) { 8978 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8979 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8980 useIsaSpecificSubdirs); 8981 } else { 8982 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8983 } 8984 } 8985 8986 maybeThrowExceptionForMultiArchCopy( 8987 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8988 8989 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8990 if (extractLibs) { 8991 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8992 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8993 useIsaSpecificSubdirs); 8994 } else { 8995 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8996 } 8997 } 8998 8999 maybeThrowExceptionForMultiArchCopy( 9000 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9001 9002 if (abi64 >= 0) { 9003 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9004 } 9005 9006 if (abi32 >= 0) { 9007 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9008 if (abi64 >= 0) { 9009 if (pkg.use32bitAbi) { 9010 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9011 pkg.applicationInfo.primaryCpuAbi = abi; 9012 } else { 9013 pkg.applicationInfo.secondaryCpuAbi = abi; 9014 } 9015 } else { 9016 pkg.applicationInfo.primaryCpuAbi = abi; 9017 } 9018 } 9019 9020 } else { 9021 String[] abiList = (cpuAbiOverride != null) ? 9022 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9023 9024 // Enable gross and lame hacks for apps that are built with old 9025 // SDK tools. We must scan their APKs for renderscript bitcode and 9026 // not launch them if it's present. Don't bother checking on devices 9027 // that don't have 64 bit support. 9028 boolean needsRenderScriptOverride = false; 9029 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9030 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9031 abiList = Build.SUPPORTED_32_BIT_ABIS; 9032 needsRenderScriptOverride = true; 9033 } 9034 9035 final int copyRet; 9036 if (extractLibs) { 9037 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9038 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9039 } else { 9040 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9041 } 9042 9043 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9044 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9045 "Error unpackaging native libs for app, errorCode=" + copyRet); 9046 } 9047 9048 if (copyRet >= 0) { 9049 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9050 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9051 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9052 } else if (needsRenderScriptOverride) { 9053 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9054 } 9055 } 9056 } catch (IOException ioe) { 9057 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9058 } finally { 9059 IoUtils.closeQuietly(handle); 9060 } 9061 9062 // Now that we've calculated the ABIs and determined if it's an internal app, 9063 // we will go ahead and populate the nativeLibraryPath. 9064 setNativeLibraryPaths(pkg); 9065 } 9066 9067 /** 9068 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9069 * i.e, so that all packages can be run inside a single process if required. 9070 * 9071 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9072 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9073 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9074 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9075 * updating a package that belongs to a shared user. 9076 * 9077 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9078 * adds unnecessary complexity. 9079 */ 9080 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9081 PackageParser.Package scannedPackage, boolean bootComplete) { 9082 String requiredInstructionSet = null; 9083 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9084 requiredInstructionSet = VMRuntime.getInstructionSet( 9085 scannedPackage.applicationInfo.primaryCpuAbi); 9086 } 9087 9088 PackageSetting requirer = null; 9089 for (PackageSetting ps : packagesForUser) { 9090 // If packagesForUser contains scannedPackage, we skip it. This will happen 9091 // when scannedPackage is an update of an existing package. Without this check, 9092 // we will never be able to change the ABI of any package belonging to a shared 9093 // user, even if it's compatible with other packages. 9094 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9095 if (ps.primaryCpuAbiString == null) { 9096 continue; 9097 } 9098 9099 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9100 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9101 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9102 // this but there's not much we can do. 9103 String errorMessage = "Instruction set mismatch, " 9104 + ((requirer == null) ? "[caller]" : requirer) 9105 + " requires " + requiredInstructionSet + " whereas " + ps 9106 + " requires " + instructionSet; 9107 Slog.w(TAG, errorMessage); 9108 } 9109 9110 if (requiredInstructionSet == null) { 9111 requiredInstructionSet = instructionSet; 9112 requirer = ps; 9113 } 9114 } 9115 } 9116 9117 if (requiredInstructionSet != null) { 9118 String adjustedAbi; 9119 if (requirer != null) { 9120 // requirer != null implies that either scannedPackage was null or that scannedPackage 9121 // did not require an ABI, in which case we have to adjust scannedPackage to match 9122 // the ABI of the set (which is the same as requirer's ABI) 9123 adjustedAbi = requirer.primaryCpuAbiString; 9124 if (scannedPackage != null) { 9125 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9126 } 9127 } else { 9128 // requirer == null implies that we're updating all ABIs in the set to 9129 // match scannedPackage. 9130 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9131 } 9132 9133 for (PackageSetting ps : packagesForUser) { 9134 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9135 if (ps.primaryCpuAbiString != null) { 9136 continue; 9137 } 9138 9139 ps.primaryCpuAbiString = adjustedAbi; 9140 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9141 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9142 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9143 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9144 + " (requirer=" 9145 + (requirer == null ? "null" : requirer.pkg.packageName) 9146 + ", scannedPackage=" 9147 + (scannedPackage != null ? scannedPackage.packageName : "null") 9148 + ")"); 9149 try { 9150 mInstaller.rmdex(ps.codePathString, 9151 getDexCodeInstructionSet(getPreferredInstructionSet())); 9152 } catch (InstallerException ignored) { 9153 } 9154 } 9155 } 9156 } 9157 } 9158 } 9159 9160 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9161 synchronized (mPackages) { 9162 mResolverReplaced = true; 9163 // Set up information for custom user intent resolution activity. 9164 mResolveActivity.applicationInfo = pkg.applicationInfo; 9165 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9166 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9167 mResolveActivity.processName = pkg.applicationInfo.packageName; 9168 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9169 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9170 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9171 mResolveActivity.theme = 0; 9172 mResolveActivity.exported = true; 9173 mResolveActivity.enabled = true; 9174 mResolveInfo.activityInfo = mResolveActivity; 9175 mResolveInfo.priority = 0; 9176 mResolveInfo.preferredOrder = 0; 9177 mResolveInfo.match = 0; 9178 mResolveComponentName = mCustomResolverComponentName; 9179 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9180 mResolveComponentName); 9181 } 9182 } 9183 9184 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9185 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9186 9187 // Set up information for ephemeral installer activity 9188 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9189 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9190 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9191 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9192 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9193 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9194 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9195 mEphemeralInstallerActivity.theme = 0; 9196 mEphemeralInstallerActivity.exported = true; 9197 mEphemeralInstallerActivity.enabled = true; 9198 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9199 mEphemeralInstallerInfo.priority = 0; 9200 mEphemeralInstallerInfo.preferredOrder = 0; 9201 mEphemeralInstallerInfo.match = 0; 9202 9203 if (DEBUG_EPHEMERAL) { 9204 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9205 } 9206 } 9207 9208 private static String calculateBundledApkRoot(final String codePathString) { 9209 final File codePath = new File(codePathString); 9210 final File codeRoot; 9211 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9212 codeRoot = Environment.getRootDirectory(); 9213 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9214 codeRoot = Environment.getOemDirectory(); 9215 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9216 codeRoot = Environment.getVendorDirectory(); 9217 } else { 9218 // Unrecognized code path; take its top real segment as the apk root: 9219 // e.g. /something/app/blah.apk => /something 9220 try { 9221 File f = codePath.getCanonicalFile(); 9222 File parent = f.getParentFile(); // non-null because codePath is a file 9223 File tmp; 9224 while ((tmp = parent.getParentFile()) != null) { 9225 f = parent; 9226 parent = tmp; 9227 } 9228 codeRoot = f; 9229 Slog.w(TAG, "Unrecognized code path " 9230 + codePath + " - using " + codeRoot); 9231 } catch (IOException e) { 9232 // Can't canonicalize the code path -- shenanigans? 9233 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9234 return Environment.getRootDirectory().getPath(); 9235 } 9236 } 9237 return codeRoot.getPath(); 9238 } 9239 9240 /** 9241 * Derive and set the location of native libraries for the given package, 9242 * which varies depending on where and how the package was installed. 9243 */ 9244 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9245 final ApplicationInfo info = pkg.applicationInfo; 9246 final String codePath = pkg.codePath; 9247 final File codeFile = new File(codePath); 9248 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9249 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9250 9251 info.nativeLibraryRootDir = null; 9252 info.nativeLibraryRootRequiresIsa = false; 9253 info.nativeLibraryDir = null; 9254 info.secondaryNativeLibraryDir = null; 9255 9256 if (isApkFile(codeFile)) { 9257 // Monolithic install 9258 if (bundledApp) { 9259 // If "/system/lib64/apkname" exists, assume that is the per-package 9260 // native library directory to use; otherwise use "/system/lib/apkname". 9261 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9262 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9263 getPrimaryInstructionSet(info)); 9264 9265 // This is a bundled system app so choose the path based on the ABI. 9266 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9267 // is just the default path. 9268 final String apkName = deriveCodePathName(codePath); 9269 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9270 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9271 apkName).getAbsolutePath(); 9272 9273 if (info.secondaryCpuAbi != null) { 9274 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9275 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9276 secondaryLibDir, apkName).getAbsolutePath(); 9277 } 9278 } else if (asecApp) { 9279 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9280 .getAbsolutePath(); 9281 } else { 9282 final String apkName = deriveCodePathName(codePath); 9283 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9284 .getAbsolutePath(); 9285 } 9286 9287 info.nativeLibraryRootRequiresIsa = false; 9288 info.nativeLibraryDir = info.nativeLibraryRootDir; 9289 } else { 9290 // Cluster install 9291 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9292 info.nativeLibraryRootRequiresIsa = true; 9293 9294 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9295 getPrimaryInstructionSet(info)).getAbsolutePath(); 9296 9297 if (info.secondaryCpuAbi != null) { 9298 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9299 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9300 } 9301 } 9302 } 9303 9304 /** 9305 * Calculate the abis and roots for a bundled app. These can uniquely 9306 * be determined from the contents of the system partition, i.e whether 9307 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9308 * of this information, and instead assume that the system was built 9309 * sensibly. 9310 */ 9311 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9312 PackageSetting pkgSetting) { 9313 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9314 9315 // If "/system/lib64/apkname" exists, assume that is the per-package 9316 // native library directory to use; otherwise use "/system/lib/apkname". 9317 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9318 setBundledAppAbi(pkg, apkRoot, apkName); 9319 // pkgSetting might be null during rescan following uninstall of updates 9320 // to a bundled app, so accommodate that possibility. The settings in 9321 // that case will be established later from the parsed package. 9322 // 9323 // If the settings aren't null, sync them up with what we've just derived. 9324 // note that apkRoot isn't stored in the package settings. 9325 if (pkgSetting != null) { 9326 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9327 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9328 } 9329 } 9330 9331 /** 9332 * Deduces the ABI of a bundled app and sets the relevant fields on the 9333 * parsed pkg object. 9334 * 9335 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9336 * under which system libraries are installed. 9337 * @param apkName the name of the installed package. 9338 */ 9339 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9340 final File codeFile = new File(pkg.codePath); 9341 9342 final boolean has64BitLibs; 9343 final boolean has32BitLibs; 9344 if (isApkFile(codeFile)) { 9345 // Monolithic install 9346 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9347 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9348 } else { 9349 // Cluster install 9350 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9351 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9352 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9353 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9354 has64BitLibs = (new File(rootDir, isa)).exists(); 9355 } else { 9356 has64BitLibs = false; 9357 } 9358 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9359 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9360 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9361 has32BitLibs = (new File(rootDir, isa)).exists(); 9362 } else { 9363 has32BitLibs = false; 9364 } 9365 } 9366 9367 if (has64BitLibs && !has32BitLibs) { 9368 // The package has 64 bit libs, but not 32 bit libs. Its primary 9369 // ABI should be 64 bit. We can safely assume here that the bundled 9370 // native libraries correspond to the most preferred ABI in the list. 9371 9372 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9373 pkg.applicationInfo.secondaryCpuAbi = null; 9374 } else if (has32BitLibs && !has64BitLibs) { 9375 // The package has 32 bit libs but not 64 bit libs. Its primary 9376 // ABI should be 32 bit. 9377 9378 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9379 pkg.applicationInfo.secondaryCpuAbi = null; 9380 } else if (has32BitLibs && has64BitLibs) { 9381 // The application has both 64 and 32 bit bundled libraries. We check 9382 // here that the app declares multiArch support, and warn if it doesn't. 9383 // 9384 // We will be lenient here and record both ABIs. The primary will be the 9385 // ABI that's higher on the list, i.e, a device that's configured to prefer 9386 // 64 bit apps will see a 64 bit primary ABI, 9387 9388 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9389 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9390 } 9391 9392 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9393 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9394 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9395 } else { 9396 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9397 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9398 } 9399 } else { 9400 pkg.applicationInfo.primaryCpuAbi = null; 9401 pkg.applicationInfo.secondaryCpuAbi = null; 9402 } 9403 } 9404 9405 private void killApplication(String pkgName, int appId, String reason) { 9406 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9407 } 9408 9409 private void killApplication(String pkgName, int appId, int userId, String reason) { 9410 // Request the ActivityManager to kill the process(only for existing packages) 9411 // so that we do not end up in a confused state while the user is still using the older 9412 // version of the application while the new one gets installed. 9413 final long token = Binder.clearCallingIdentity(); 9414 try { 9415 IActivityManager am = ActivityManagerNative.getDefault(); 9416 if (am != null) { 9417 try { 9418 am.killApplication(pkgName, appId, userId, reason); 9419 } catch (RemoteException e) { 9420 } 9421 } 9422 } finally { 9423 Binder.restoreCallingIdentity(token); 9424 } 9425 } 9426 9427 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9428 // Remove the parent package setting 9429 PackageSetting ps = (PackageSetting) pkg.mExtras; 9430 if (ps != null) { 9431 removePackageLI(ps, chatty); 9432 } 9433 // Remove the child package setting 9434 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9435 for (int i = 0; i < childCount; i++) { 9436 PackageParser.Package childPkg = pkg.childPackages.get(i); 9437 ps = (PackageSetting) childPkg.mExtras; 9438 if (ps != null) { 9439 removePackageLI(ps, chatty); 9440 } 9441 } 9442 } 9443 9444 void removePackageLI(PackageSetting ps, boolean chatty) { 9445 if (DEBUG_INSTALL) { 9446 if (chatty) 9447 Log.d(TAG, "Removing package " + ps.name); 9448 } 9449 9450 // writer 9451 synchronized (mPackages) { 9452 mPackages.remove(ps.name); 9453 final PackageParser.Package pkg = ps.pkg; 9454 if (pkg != null) { 9455 cleanPackageDataStructuresLILPw(pkg, chatty); 9456 } 9457 } 9458 } 9459 9460 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9461 if (DEBUG_INSTALL) { 9462 if (chatty) 9463 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9464 } 9465 9466 // writer 9467 synchronized (mPackages) { 9468 // Remove the parent package 9469 mPackages.remove(pkg.applicationInfo.packageName); 9470 cleanPackageDataStructuresLILPw(pkg, chatty); 9471 9472 // Remove the child packages 9473 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9474 for (int i = 0; i < childCount; i++) { 9475 PackageParser.Package childPkg = pkg.childPackages.get(i); 9476 mPackages.remove(childPkg.applicationInfo.packageName); 9477 cleanPackageDataStructuresLILPw(childPkg, chatty); 9478 } 9479 } 9480 } 9481 9482 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9483 int N = pkg.providers.size(); 9484 StringBuilder r = null; 9485 int i; 9486 for (i=0; i<N; i++) { 9487 PackageParser.Provider p = pkg.providers.get(i); 9488 mProviders.removeProvider(p); 9489 if (p.info.authority == null) { 9490 9491 /* There was another ContentProvider with this authority when 9492 * this app was installed so this authority is null, 9493 * Ignore it as we don't have to unregister the provider. 9494 */ 9495 continue; 9496 } 9497 String names[] = p.info.authority.split(";"); 9498 for (int j = 0; j < names.length; j++) { 9499 if (mProvidersByAuthority.get(names[j]) == p) { 9500 mProvidersByAuthority.remove(names[j]); 9501 if (DEBUG_REMOVE) { 9502 if (chatty) 9503 Log.d(TAG, "Unregistered content provider: " + names[j] 9504 + ", className = " + p.info.name + ", isSyncable = " 9505 + p.info.isSyncable); 9506 } 9507 } 9508 } 9509 if (DEBUG_REMOVE && chatty) { 9510 if (r == null) { 9511 r = new StringBuilder(256); 9512 } else { 9513 r.append(' '); 9514 } 9515 r.append(p.info.name); 9516 } 9517 } 9518 if (r != null) { 9519 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9520 } 9521 9522 N = pkg.services.size(); 9523 r = null; 9524 for (i=0; i<N; i++) { 9525 PackageParser.Service s = pkg.services.get(i); 9526 mServices.removeService(s); 9527 if (chatty) { 9528 if (r == null) { 9529 r = new StringBuilder(256); 9530 } else { 9531 r.append(' '); 9532 } 9533 r.append(s.info.name); 9534 } 9535 } 9536 if (r != null) { 9537 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9538 } 9539 9540 N = pkg.receivers.size(); 9541 r = null; 9542 for (i=0; i<N; i++) { 9543 PackageParser.Activity a = pkg.receivers.get(i); 9544 mReceivers.removeActivity(a, "receiver"); 9545 if (DEBUG_REMOVE && chatty) { 9546 if (r == null) { 9547 r = new StringBuilder(256); 9548 } else { 9549 r.append(' '); 9550 } 9551 r.append(a.info.name); 9552 } 9553 } 9554 if (r != null) { 9555 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9556 } 9557 9558 N = pkg.activities.size(); 9559 r = null; 9560 for (i=0; i<N; i++) { 9561 PackageParser.Activity a = pkg.activities.get(i); 9562 mActivities.removeActivity(a, "activity"); 9563 if (DEBUG_REMOVE && chatty) { 9564 if (r == null) { 9565 r = new StringBuilder(256); 9566 } else { 9567 r.append(' '); 9568 } 9569 r.append(a.info.name); 9570 } 9571 } 9572 if (r != null) { 9573 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9574 } 9575 9576 N = pkg.permissions.size(); 9577 r = null; 9578 for (i=0; i<N; i++) { 9579 PackageParser.Permission p = pkg.permissions.get(i); 9580 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9581 if (bp == null) { 9582 bp = mSettings.mPermissionTrees.get(p.info.name); 9583 } 9584 if (bp != null && bp.perm == p) { 9585 bp.perm = null; 9586 if (DEBUG_REMOVE && chatty) { 9587 if (r == null) { 9588 r = new StringBuilder(256); 9589 } else { 9590 r.append(' '); 9591 } 9592 r.append(p.info.name); 9593 } 9594 } 9595 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9596 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9597 if (appOpPkgs != null) { 9598 appOpPkgs.remove(pkg.packageName); 9599 } 9600 } 9601 } 9602 if (r != null) { 9603 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9604 } 9605 9606 N = pkg.requestedPermissions.size(); 9607 r = null; 9608 for (i=0; i<N; i++) { 9609 String perm = pkg.requestedPermissions.get(i); 9610 BasePermission bp = mSettings.mPermissions.get(perm); 9611 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9612 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9613 if (appOpPkgs != null) { 9614 appOpPkgs.remove(pkg.packageName); 9615 if (appOpPkgs.isEmpty()) { 9616 mAppOpPermissionPackages.remove(perm); 9617 } 9618 } 9619 } 9620 } 9621 if (r != null) { 9622 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9623 } 9624 9625 N = pkg.instrumentation.size(); 9626 r = null; 9627 for (i=0; i<N; i++) { 9628 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9629 mInstrumentation.remove(a.getComponentName()); 9630 if (DEBUG_REMOVE && chatty) { 9631 if (r == null) { 9632 r = new StringBuilder(256); 9633 } else { 9634 r.append(' '); 9635 } 9636 r.append(a.info.name); 9637 } 9638 } 9639 if (r != null) { 9640 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9641 } 9642 9643 r = null; 9644 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9645 // Only system apps can hold shared libraries. 9646 if (pkg.libraryNames != null) { 9647 for (i=0; i<pkg.libraryNames.size(); i++) { 9648 String name = pkg.libraryNames.get(i); 9649 SharedLibraryEntry cur = mSharedLibraries.get(name); 9650 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9651 mSharedLibraries.remove(name); 9652 if (DEBUG_REMOVE && chatty) { 9653 if (r == null) { 9654 r = new StringBuilder(256); 9655 } else { 9656 r.append(' '); 9657 } 9658 r.append(name); 9659 } 9660 } 9661 } 9662 } 9663 } 9664 if (r != null) { 9665 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9666 } 9667 } 9668 9669 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9670 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9671 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9672 return true; 9673 } 9674 } 9675 return false; 9676 } 9677 9678 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9679 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9680 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9681 9682 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9683 // Update the parent permissions 9684 updatePermissionsLPw(pkg.packageName, pkg, flags); 9685 // Update the child permissions 9686 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9687 for (int i = 0; i < childCount; i++) { 9688 PackageParser.Package childPkg = pkg.childPackages.get(i); 9689 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9690 } 9691 } 9692 9693 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9694 int flags) { 9695 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9696 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9697 } 9698 9699 private void updatePermissionsLPw(String changingPkg, 9700 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9701 // Make sure there are no dangling permission trees. 9702 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9703 while (it.hasNext()) { 9704 final BasePermission bp = it.next(); 9705 if (bp.packageSetting == null) { 9706 // We may not yet have parsed the package, so just see if 9707 // we still know about its settings. 9708 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9709 } 9710 if (bp.packageSetting == null) { 9711 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9712 + " from package " + bp.sourcePackage); 9713 it.remove(); 9714 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9715 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9716 Slog.i(TAG, "Removing old permission tree: " + bp.name 9717 + " from package " + bp.sourcePackage); 9718 flags |= UPDATE_PERMISSIONS_ALL; 9719 it.remove(); 9720 } 9721 } 9722 } 9723 9724 // Make sure all dynamic permissions have been assigned to a package, 9725 // and make sure there are no dangling permissions. 9726 it = mSettings.mPermissions.values().iterator(); 9727 while (it.hasNext()) { 9728 final BasePermission bp = it.next(); 9729 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9730 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9731 + bp.name + " pkg=" + bp.sourcePackage 9732 + " info=" + bp.pendingInfo); 9733 if (bp.packageSetting == null && bp.pendingInfo != null) { 9734 final BasePermission tree = findPermissionTreeLP(bp.name); 9735 if (tree != null && tree.perm != null) { 9736 bp.packageSetting = tree.packageSetting; 9737 bp.perm = new PackageParser.Permission(tree.perm.owner, 9738 new PermissionInfo(bp.pendingInfo)); 9739 bp.perm.info.packageName = tree.perm.info.packageName; 9740 bp.perm.info.name = bp.name; 9741 bp.uid = tree.uid; 9742 } 9743 } 9744 } 9745 if (bp.packageSetting == null) { 9746 // We may not yet have parsed the package, so just see if 9747 // we still know about its settings. 9748 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9749 } 9750 if (bp.packageSetting == null) { 9751 Slog.w(TAG, "Removing dangling permission: " + bp.name 9752 + " from package " + bp.sourcePackage); 9753 it.remove(); 9754 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9755 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9756 Slog.i(TAG, "Removing old permission: " + bp.name 9757 + " from package " + bp.sourcePackage); 9758 flags |= UPDATE_PERMISSIONS_ALL; 9759 it.remove(); 9760 } 9761 } 9762 } 9763 9764 // Now update the permissions for all packages, in particular 9765 // replace the granted permissions of the system packages. 9766 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9767 for (PackageParser.Package pkg : mPackages.values()) { 9768 if (pkg != pkgInfo) { 9769 // Only replace for packages on requested volume 9770 final String volumeUuid = getVolumeUuidForPackage(pkg); 9771 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9772 && Objects.equals(replaceVolumeUuid, volumeUuid); 9773 grantPermissionsLPw(pkg, replace, changingPkg); 9774 } 9775 } 9776 } 9777 9778 if (pkgInfo != null) { 9779 // Only replace for packages on requested volume 9780 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9781 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9782 && Objects.equals(replaceVolumeUuid, volumeUuid); 9783 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9784 } 9785 } 9786 9787 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9788 String packageOfInterest) { 9789 // IMPORTANT: There are two types of permissions: install and runtime. 9790 // Install time permissions are granted when the app is installed to 9791 // all device users and users added in the future. Runtime permissions 9792 // are granted at runtime explicitly to specific users. Normal and signature 9793 // protected permissions are install time permissions. Dangerous permissions 9794 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9795 // otherwise they are runtime permissions. This function does not manage 9796 // runtime permissions except for the case an app targeting Lollipop MR1 9797 // being upgraded to target a newer SDK, in which case dangerous permissions 9798 // are transformed from install time to runtime ones. 9799 9800 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9801 if (ps == null) { 9802 return; 9803 } 9804 9805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9806 9807 PermissionsState permissionsState = ps.getPermissionsState(); 9808 PermissionsState origPermissions = permissionsState; 9809 9810 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9811 9812 boolean runtimePermissionsRevoked = false; 9813 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9814 9815 boolean changedInstallPermission = false; 9816 9817 if (replace) { 9818 ps.installPermissionsFixed = false; 9819 if (!ps.isSharedUser()) { 9820 origPermissions = new PermissionsState(permissionsState); 9821 permissionsState.reset(); 9822 } else { 9823 // We need to know only about runtime permission changes since the 9824 // calling code always writes the install permissions state but 9825 // the runtime ones are written only if changed. The only cases of 9826 // changed runtime permissions here are promotion of an install to 9827 // runtime and revocation of a runtime from a shared user. 9828 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9829 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9830 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9831 runtimePermissionsRevoked = true; 9832 } 9833 } 9834 } 9835 9836 permissionsState.setGlobalGids(mGlobalGids); 9837 9838 final int N = pkg.requestedPermissions.size(); 9839 for (int i=0; i<N; i++) { 9840 final String name = pkg.requestedPermissions.get(i); 9841 final BasePermission bp = mSettings.mPermissions.get(name); 9842 9843 if (DEBUG_INSTALL) { 9844 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9845 } 9846 9847 if (bp == null || bp.packageSetting == null) { 9848 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9849 Slog.w(TAG, "Unknown permission " + name 9850 + " in package " + pkg.packageName); 9851 } 9852 continue; 9853 } 9854 9855 final String perm = bp.name; 9856 boolean allowedSig = false; 9857 int grant = GRANT_DENIED; 9858 9859 // Keep track of app op permissions. 9860 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9861 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9862 if (pkgs == null) { 9863 pkgs = new ArraySet<>(); 9864 mAppOpPermissionPackages.put(bp.name, pkgs); 9865 } 9866 pkgs.add(pkg.packageName); 9867 } 9868 9869 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9870 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9871 >= Build.VERSION_CODES.M; 9872 switch (level) { 9873 case PermissionInfo.PROTECTION_NORMAL: { 9874 // For all apps normal permissions are install time ones. 9875 grant = GRANT_INSTALL; 9876 } break; 9877 9878 case PermissionInfo.PROTECTION_DANGEROUS: { 9879 // If a permission review is required for legacy apps we represent 9880 // their permissions as always granted runtime ones since we need 9881 // to keep the review required permission flag per user while an 9882 // install permission's state is shared across all users. 9883 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9884 // For legacy apps dangerous permissions are install time ones. 9885 grant = GRANT_INSTALL; 9886 } else if (origPermissions.hasInstallPermission(bp.name)) { 9887 // For legacy apps that became modern, install becomes runtime. 9888 grant = GRANT_UPGRADE; 9889 } else if (mPromoteSystemApps 9890 && isSystemApp(ps) 9891 && mExistingSystemPackages.contains(ps.name)) { 9892 // For legacy system apps, install becomes runtime. 9893 // We cannot check hasInstallPermission() for system apps since those 9894 // permissions were granted implicitly and not persisted pre-M. 9895 grant = GRANT_UPGRADE; 9896 } else { 9897 // For modern apps keep runtime permissions unchanged. 9898 grant = GRANT_RUNTIME; 9899 } 9900 } break; 9901 9902 case PermissionInfo.PROTECTION_SIGNATURE: { 9903 // For all apps signature permissions are install time ones. 9904 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9905 if (allowedSig) { 9906 grant = GRANT_INSTALL; 9907 } 9908 } break; 9909 } 9910 9911 if (DEBUG_INSTALL) { 9912 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9913 } 9914 9915 if (grant != GRANT_DENIED) { 9916 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9917 // If this is an existing, non-system package, then 9918 // we can't add any new permissions to it. 9919 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9920 // Except... if this is a permission that was added 9921 // to the platform (note: need to only do this when 9922 // updating the platform). 9923 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9924 grant = GRANT_DENIED; 9925 } 9926 } 9927 } 9928 9929 switch (grant) { 9930 case GRANT_INSTALL: { 9931 // Revoke this as runtime permission to handle the case of 9932 // a runtime permission being downgraded to an install one. 9933 // Also in permission review mode we keep dangerous permissions 9934 // for legacy apps 9935 for (int userId : UserManagerService.getInstance().getUserIds()) { 9936 if (origPermissions.getRuntimePermissionState( 9937 bp.name, userId) != null) { 9938 // Revoke the runtime permission and clear the flags. 9939 origPermissions.revokeRuntimePermission(bp, userId); 9940 origPermissions.updatePermissionFlags(bp, userId, 9941 PackageManager.MASK_PERMISSION_FLAGS, 0); 9942 // If we revoked a permission permission, we have to write. 9943 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9944 changedRuntimePermissionUserIds, userId); 9945 } 9946 } 9947 // Grant an install permission. 9948 if (permissionsState.grantInstallPermission(bp) != 9949 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9950 changedInstallPermission = true; 9951 } 9952 } break; 9953 9954 case GRANT_RUNTIME: { 9955 // Grant previously granted runtime permissions. 9956 for (int userId : UserManagerService.getInstance().getUserIds()) { 9957 PermissionState permissionState = origPermissions 9958 .getRuntimePermissionState(bp.name, userId); 9959 int flags = permissionState != null 9960 ? permissionState.getFlags() : 0; 9961 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9962 if (permissionsState.grantRuntimePermission(bp, userId) == 9963 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9964 // If we cannot put the permission as it was, we have to write. 9965 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9966 changedRuntimePermissionUserIds, userId); 9967 } 9968 // If the app supports runtime permissions no need for a review. 9969 if (Build.PERMISSIONS_REVIEW_REQUIRED 9970 && appSupportsRuntimePermissions 9971 && (flags & PackageManager 9972 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9973 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9974 // Since we changed the flags, we have to write. 9975 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9976 changedRuntimePermissionUserIds, userId); 9977 } 9978 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9979 && !appSupportsRuntimePermissions) { 9980 // For legacy apps that need a permission review, every new 9981 // runtime permission is granted but it is pending a review. 9982 // We also need to review only platform defined runtime 9983 // permissions as these are the only ones the platform knows 9984 // how to disable the API to simulate revocation as legacy 9985 // apps don't expect to run with revoked permissions. 9986 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9987 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9988 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9989 // We changed the flags, hence have to write. 9990 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9991 changedRuntimePermissionUserIds, userId); 9992 } 9993 } 9994 if (permissionsState.grantRuntimePermission(bp, userId) 9995 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9996 // We changed the permission, hence have to write. 9997 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9998 changedRuntimePermissionUserIds, userId); 9999 } 10000 } 10001 // Propagate the permission flags. 10002 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10003 } 10004 } break; 10005 10006 case GRANT_UPGRADE: { 10007 // Grant runtime permissions for a previously held install permission. 10008 PermissionState permissionState = origPermissions 10009 .getInstallPermissionState(bp.name); 10010 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10011 10012 if (origPermissions.revokeInstallPermission(bp) 10013 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10014 // We will be transferring the permission flags, so clear them. 10015 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10016 PackageManager.MASK_PERMISSION_FLAGS, 0); 10017 changedInstallPermission = true; 10018 } 10019 10020 // If the permission is not to be promoted to runtime we ignore it and 10021 // also its other flags as they are not applicable to install permissions. 10022 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10023 for (int userId : currentUserIds) { 10024 if (permissionsState.grantRuntimePermission(bp, userId) != 10025 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10026 // Transfer the permission flags. 10027 permissionsState.updatePermissionFlags(bp, userId, 10028 flags, flags); 10029 // If we granted the permission, we have to write. 10030 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10031 changedRuntimePermissionUserIds, userId); 10032 } 10033 } 10034 } 10035 } break; 10036 10037 default: { 10038 if (packageOfInterest == null 10039 || packageOfInterest.equals(pkg.packageName)) { 10040 Slog.w(TAG, "Not granting permission " + perm 10041 + " to package " + pkg.packageName 10042 + " because it was previously installed without"); 10043 } 10044 } break; 10045 } 10046 } else { 10047 if (permissionsState.revokeInstallPermission(bp) != 10048 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10049 // Also drop the permission flags. 10050 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10051 PackageManager.MASK_PERMISSION_FLAGS, 0); 10052 changedInstallPermission = true; 10053 Slog.i(TAG, "Un-granting permission " + perm 10054 + " from package " + pkg.packageName 10055 + " (protectionLevel=" + bp.protectionLevel 10056 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10057 + ")"); 10058 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10059 // Don't print warning for app op permissions, since it is fine for them 10060 // not to be granted, there is a UI for the user to decide. 10061 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10062 Slog.w(TAG, "Not granting permission " + perm 10063 + " to package " + pkg.packageName 10064 + " (protectionLevel=" + bp.protectionLevel 10065 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10066 + ")"); 10067 } 10068 } 10069 } 10070 } 10071 10072 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10073 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10074 // This is the first that we have heard about this package, so the 10075 // permissions we have now selected are fixed until explicitly 10076 // changed. 10077 ps.installPermissionsFixed = true; 10078 } 10079 10080 // Persist the runtime permissions state for users with changes. If permissions 10081 // were revoked because no app in the shared user declares them we have to 10082 // write synchronously to avoid losing runtime permissions state. 10083 for (int userId : changedRuntimePermissionUserIds) { 10084 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10085 } 10086 10087 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10088 } 10089 10090 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10091 boolean allowed = false; 10092 final int NP = PackageParser.NEW_PERMISSIONS.length; 10093 for (int ip=0; ip<NP; ip++) { 10094 final PackageParser.NewPermissionInfo npi 10095 = PackageParser.NEW_PERMISSIONS[ip]; 10096 if (npi.name.equals(perm) 10097 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10098 allowed = true; 10099 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10100 + pkg.packageName); 10101 break; 10102 } 10103 } 10104 return allowed; 10105 } 10106 10107 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10108 BasePermission bp, PermissionsState origPermissions) { 10109 boolean allowed; 10110 allowed = (compareSignatures( 10111 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10112 == PackageManager.SIGNATURE_MATCH) 10113 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10114 == PackageManager.SIGNATURE_MATCH); 10115 if (!allowed && (bp.protectionLevel 10116 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10117 if (isSystemApp(pkg)) { 10118 // For updated system applications, a system permission 10119 // is granted only if it had been defined by the original application. 10120 if (pkg.isUpdatedSystemApp()) { 10121 final PackageSetting sysPs = mSettings 10122 .getDisabledSystemPkgLPr(pkg.packageName); 10123 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10124 // If the original was granted this permission, we take 10125 // that grant decision as read and propagate it to the 10126 // update. 10127 if (sysPs.isPrivileged()) { 10128 allowed = true; 10129 } 10130 } else { 10131 // The system apk may have been updated with an older 10132 // version of the one on the data partition, but which 10133 // granted a new system permission that it didn't have 10134 // before. In this case we do want to allow the app to 10135 // now get the new permission if the ancestral apk is 10136 // privileged to get it. 10137 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10138 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10139 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10140 allowed = true; 10141 break; 10142 } 10143 } 10144 } 10145 // Also if a privileged parent package on the system image or any of 10146 // its children requested a privileged permission, the updated child 10147 // packages can also get the permission. 10148 if (pkg.parentPackage != null) { 10149 final PackageSetting disabledSysParentPs = mSettings 10150 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10151 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10152 && disabledSysParentPs.isPrivileged()) { 10153 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10154 allowed = true; 10155 } else if (disabledSysParentPs.pkg.childPackages != null) { 10156 final int count = disabledSysParentPs.pkg.childPackages.size(); 10157 for (int i = 0; i < count; i++) { 10158 PackageParser.Package disabledSysChildPkg = 10159 disabledSysParentPs.pkg.childPackages.get(i); 10160 if (isPackageRequestingPermission(disabledSysChildPkg, 10161 perm)) { 10162 allowed = true; 10163 break; 10164 } 10165 } 10166 } 10167 } 10168 } 10169 } 10170 } else { 10171 allowed = isPrivilegedApp(pkg); 10172 } 10173 } 10174 } 10175 if (!allowed) { 10176 if (!allowed && (bp.protectionLevel 10177 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10178 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10179 // If this was a previously normal/dangerous permission that got moved 10180 // to a system permission as part of the runtime permission redesign, then 10181 // we still want to blindly grant it to old apps. 10182 allowed = true; 10183 } 10184 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10185 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10186 // If this permission is to be granted to the system installer and 10187 // this app is an installer, then it gets the permission. 10188 allowed = true; 10189 } 10190 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10191 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10192 // If this permission is to be granted to the system verifier and 10193 // this app is a verifier, then it gets the permission. 10194 allowed = true; 10195 } 10196 if (!allowed && (bp.protectionLevel 10197 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10198 && isSystemApp(pkg)) { 10199 // Any pre-installed system app is allowed to get this permission. 10200 allowed = true; 10201 } 10202 if (!allowed && (bp.protectionLevel 10203 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10204 // For development permissions, a development permission 10205 // is granted only if it was already granted. 10206 allowed = origPermissions.hasInstallPermission(perm); 10207 } 10208 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10209 && pkg.packageName.equals(mSetupWizardPackage)) { 10210 // If this permission is to be granted to the system setup wizard and 10211 // this app is a setup wizard, then it gets the permission. 10212 allowed = true; 10213 } 10214 } 10215 return allowed; 10216 } 10217 10218 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10219 final int permCount = pkg.requestedPermissions.size(); 10220 for (int j = 0; j < permCount; j++) { 10221 String requestedPermission = pkg.requestedPermissions.get(j); 10222 if (permission.equals(requestedPermission)) { 10223 return true; 10224 } 10225 } 10226 return false; 10227 } 10228 10229 final class ActivityIntentResolver 10230 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10231 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10232 boolean defaultOnly, int userId) { 10233 if (!sUserManager.exists(userId)) return null; 10234 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10235 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10236 } 10237 10238 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10239 int userId) { 10240 if (!sUserManager.exists(userId)) return null; 10241 mFlags = flags; 10242 return super.queryIntent(intent, resolvedType, 10243 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10244 } 10245 10246 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10247 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10248 if (!sUserManager.exists(userId)) return null; 10249 if (packageActivities == null) { 10250 return null; 10251 } 10252 mFlags = flags; 10253 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10254 final int N = packageActivities.size(); 10255 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10256 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10257 10258 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10259 for (int i = 0; i < N; ++i) { 10260 intentFilters = packageActivities.get(i).intents; 10261 if (intentFilters != null && intentFilters.size() > 0) { 10262 PackageParser.ActivityIntentInfo[] array = 10263 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10264 intentFilters.toArray(array); 10265 listCut.add(array); 10266 } 10267 } 10268 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10269 } 10270 10271 /** 10272 * Finds a privileged activity that matches the specified activity names. 10273 */ 10274 private PackageParser.Activity findMatchingActivity( 10275 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10276 for (PackageParser.Activity sysActivity : activityList) { 10277 if (sysActivity.info.name.equals(activityInfo.name)) { 10278 return sysActivity; 10279 } 10280 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10281 return sysActivity; 10282 } 10283 if (sysActivity.info.targetActivity != null) { 10284 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10285 return sysActivity; 10286 } 10287 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10288 return sysActivity; 10289 } 10290 } 10291 } 10292 return null; 10293 } 10294 10295 public class IterGenerator<E> { 10296 public Iterator<E> generate(ActivityIntentInfo info) { 10297 return null; 10298 } 10299 } 10300 10301 public class ActionIterGenerator extends IterGenerator<String> { 10302 @Override 10303 public Iterator<String> generate(ActivityIntentInfo info) { 10304 return info.actionsIterator(); 10305 } 10306 } 10307 10308 public class CategoriesIterGenerator extends IterGenerator<String> { 10309 @Override 10310 public Iterator<String> generate(ActivityIntentInfo info) { 10311 return info.categoriesIterator(); 10312 } 10313 } 10314 10315 public class SchemesIterGenerator extends IterGenerator<String> { 10316 @Override 10317 public Iterator<String> generate(ActivityIntentInfo info) { 10318 return info.schemesIterator(); 10319 } 10320 } 10321 10322 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10323 @Override 10324 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10325 return info.authoritiesIterator(); 10326 } 10327 } 10328 10329 /** 10330 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10331 * MODIFIED. Do not pass in a list that should not be changed. 10332 */ 10333 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10334 IterGenerator<T> generator, Iterator<T> searchIterator) { 10335 // loop through the set of actions; every one must be found in the intent filter 10336 while (searchIterator.hasNext()) { 10337 // we must have at least one filter in the list to consider a match 10338 if (intentList.size() == 0) { 10339 break; 10340 } 10341 10342 final T searchAction = searchIterator.next(); 10343 10344 // loop through the set of intent filters 10345 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10346 while (intentIter.hasNext()) { 10347 final ActivityIntentInfo intentInfo = intentIter.next(); 10348 boolean selectionFound = false; 10349 10350 // loop through the intent filter's selection criteria; at least one 10351 // of them must match the searched criteria 10352 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10353 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10354 final T intentSelection = intentSelectionIter.next(); 10355 if (intentSelection != null && intentSelection.equals(searchAction)) { 10356 selectionFound = true; 10357 break; 10358 } 10359 } 10360 10361 // the selection criteria wasn't found in this filter's set; this filter 10362 // is not a potential match 10363 if (!selectionFound) { 10364 intentIter.remove(); 10365 } 10366 } 10367 } 10368 } 10369 10370 private boolean isProtectedAction(ActivityIntentInfo filter) { 10371 final Iterator<String> actionsIter = filter.actionsIterator(); 10372 while (actionsIter != null && actionsIter.hasNext()) { 10373 final String filterAction = actionsIter.next(); 10374 if (PROTECTED_ACTIONS.contains(filterAction)) { 10375 return true; 10376 } 10377 } 10378 return false; 10379 } 10380 10381 /** 10382 * Adjusts the priority of the given intent filter according to policy. 10383 * <p> 10384 * <ul> 10385 * <li>The priority for non privileged applications is capped to '0'</li> 10386 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10387 * <li>The priority for unbundled updates to privileged applications is capped to the 10388 * priority defined on the system partition</li> 10389 * </ul> 10390 * <p> 10391 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10392 * allowed to obtain any priority on any action. 10393 */ 10394 private void adjustPriority( 10395 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10396 // nothing to do; priority is fine as-is 10397 if (intent.getPriority() <= 0) { 10398 return; 10399 } 10400 10401 final ActivityInfo activityInfo = intent.activity.info; 10402 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10403 10404 final boolean privilegedApp = 10405 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10406 if (!privilegedApp) { 10407 // non-privileged applications can never define a priority >0 10408 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10409 + " package: " + applicationInfo.packageName 10410 + " activity: " + intent.activity.className 10411 + " origPrio: " + intent.getPriority()); 10412 intent.setPriority(0); 10413 return; 10414 } 10415 10416 if (systemActivities == null) { 10417 // the system package is not disabled; we're parsing the system partition 10418 if (isProtectedAction(intent)) { 10419 if (mDeferProtectedFilters) { 10420 // We can't deal with these just yet. No component should ever obtain a 10421 // >0 priority for a protected actions, with ONE exception -- the setup 10422 // wizard. The setup wizard, however, cannot be known until we're able to 10423 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10424 // until all intent filters have been processed. Chicken, meet egg. 10425 // Let the filter temporarily have a high priority and rectify the 10426 // priorities after all system packages have been scanned. 10427 mProtectedFilters.add(intent); 10428 if (DEBUG_FILTERS) { 10429 Slog.i(TAG, "Protected action; save for later;" 10430 + " package: " + applicationInfo.packageName 10431 + " activity: " + intent.activity.className 10432 + " origPrio: " + intent.getPriority()); 10433 } 10434 return; 10435 } else { 10436 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10437 Slog.i(TAG, "No setup wizard;" 10438 + " All protected intents capped to priority 0"); 10439 } 10440 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10441 if (DEBUG_FILTERS) { 10442 Slog.i(TAG, "Found setup wizard;" 10443 + " allow priority " + intent.getPriority() + ";" 10444 + " package: " + intent.activity.info.packageName 10445 + " activity: " + intent.activity.className 10446 + " priority: " + intent.getPriority()); 10447 } 10448 // setup wizard gets whatever it wants 10449 return; 10450 } 10451 Slog.w(TAG, "Protected action; cap priority to 0;" 10452 + " package: " + intent.activity.info.packageName 10453 + " activity: " + intent.activity.className 10454 + " origPrio: " + intent.getPriority()); 10455 intent.setPriority(0); 10456 return; 10457 } 10458 } 10459 // privileged apps on the system image get whatever priority they request 10460 return; 10461 } 10462 10463 // privileged app unbundled update ... try to find the same activity 10464 final PackageParser.Activity foundActivity = 10465 findMatchingActivity(systemActivities, activityInfo); 10466 if (foundActivity == null) { 10467 // this is a new activity; it cannot obtain >0 priority 10468 if (DEBUG_FILTERS) { 10469 Slog.i(TAG, "New activity; cap priority to 0;" 10470 + " package: " + applicationInfo.packageName 10471 + " activity: " + intent.activity.className 10472 + " origPrio: " + intent.getPriority()); 10473 } 10474 intent.setPriority(0); 10475 return; 10476 } 10477 10478 // found activity, now check for filter equivalence 10479 10480 // a shallow copy is enough; we modify the list, not its contents 10481 final List<ActivityIntentInfo> intentListCopy = 10482 new ArrayList<>(foundActivity.intents); 10483 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10484 10485 // find matching action subsets 10486 final Iterator<String> actionsIterator = intent.actionsIterator(); 10487 if (actionsIterator != null) { 10488 getIntentListSubset( 10489 intentListCopy, new ActionIterGenerator(), actionsIterator); 10490 if (intentListCopy.size() == 0) { 10491 // no more intents to match; we're not equivalent 10492 if (DEBUG_FILTERS) { 10493 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10494 + " package: " + applicationInfo.packageName 10495 + " activity: " + intent.activity.className 10496 + " origPrio: " + intent.getPriority()); 10497 } 10498 intent.setPriority(0); 10499 return; 10500 } 10501 } 10502 10503 // find matching category subsets 10504 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10505 if (categoriesIterator != null) { 10506 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10507 categoriesIterator); 10508 if (intentListCopy.size() == 0) { 10509 // no more intents to match; we're not equivalent 10510 if (DEBUG_FILTERS) { 10511 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10512 + " package: " + applicationInfo.packageName 10513 + " activity: " + intent.activity.className 10514 + " origPrio: " + intent.getPriority()); 10515 } 10516 intent.setPriority(0); 10517 return; 10518 } 10519 } 10520 10521 // find matching schemes subsets 10522 final Iterator<String> schemesIterator = intent.schemesIterator(); 10523 if (schemesIterator != null) { 10524 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10525 schemesIterator); 10526 if (intentListCopy.size() == 0) { 10527 // no more intents to match; we're not equivalent 10528 if (DEBUG_FILTERS) { 10529 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10530 + " package: " + applicationInfo.packageName 10531 + " activity: " + intent.activity.className 10532 + " origPrio: " + intent.getPriority()); 10533 } 10534 intent.setPriority(0); 10535 return; 10536 } 10537 } 10538 10539 // find matching authorities subsets 10540 final Iterator<IntentFilter.AuthorityEntry> 10541 authoritiesIterator = intent.authoritiesIterator(); 10542 if (authoritiesIterator != null) { 10543 getIntentListSubset(intentListCopy, 10544 new AuthoritiesIterGenerator(), 10545 authoritiesIterator); 10546 if (intentListCopy.size() == 0) { 10547 // no more intents to match; we're not equivalent 10548 if (DEBUG_FILTERS) { 10549 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10550 + " package: " + applicationInfo.packageName 10551 + " activity: " + intent.activity.className 10552 + " origPrio: " + intent.getPriority()); 10553 } 10554 intent.setPriority(0); 10555 return; 10556 } 10557 } 10558 10559 // we found matching filter(s); app gets the max priority of all intents 10560 int cappedPriority = 0; 10561 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10562 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10563 } 10564 if (intent.getPriority() > cappedPriority) { 10565 if (DEBUG_FILTERS) { 10566 Slog.i(TAG, "Found matching filter(s);" 10567 + " cap priority to " + cappedPriority + ";" 10568 + " package: " + applicationInfo.packageName 10569 + " activity: " + intent.activity.className 10570 + " origPrio: " + intent.getPriority()); 10571 } 10572 intent.setPriority(cappedPriority); 10573 return; 10574 } 10575 // all this for nothing; the requested priority was <= what was on the system 10576 } 10577 10578 public final void addActivity(PackageParser.Activity a, String type) { 10579 mActivities.put(a.getComponentName(), a); 10580 if (DEBUG_SHOW_INFO) 10581 Log.v( 10582 TAG, " " + type + " " + 10583 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10584 if (DEBUG_SHOW_INFO) 10585 Log.v(TAG, " Class=" + a.info.name); 10586 final int NI = a.intents.size(); 10587 for (int j=0; j<NI; j++) { 10588 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10589 if ("activity".equals(type)) { 10590 final PackageSetting ps = 10591 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10592 final List<PackageParser.Activity> systemActivities = 10593 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10594 adjustPriority(systemActivities, intent); 10595 } 10596 if (DEBUG_SHOW_INFO) { 10597 Log.v(TAG, " IntentFilter:"); 10598 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10599 } 10600 if (!intent.debugCheck()) { 10601 Log.w(TAG, "==> For Activity " + a.info.name); 10602 } 10603 addFilter(intent); 10604 } 10605 } 10606 10607 public final void removeActivity(PackageParser.Activity a, String type) { 10608 mActivities.remove(a.getComponentName()); 10609 if (DEBUG_SHOW_INFO) { 10610 Log.v(TAG, " " + type + " " 10611 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10612 : a.info.name) + ":"); 10613 Log.v(TAG, " Class=" + a.info.name); 10614 } 10615 final int NI = a.intents.size(); 10616 for (int j=0; j<NI; j++) { 10617 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10618 if (DEBUG_SHOW_INFO) { 10619 Log.v(TAG, " IntentFilter:"); 10620 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10621 } 10622 removeFilter(intent); 10623 } 10624 } 10625 10626 @Override 10627 protected boolean allowFilterResult( 10628 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10629 ActivityInfo filterAi = filter.activity.info; 10630 for (int i=dest.size()-1; i>=0; i--) { 10631 ActivityInfo destAi = dest.get(i).activityInfo; 10632 if (destAi.name == filterAi.name 10633 && destAi.packageName == filterAi.packageName) { 10634 return false; 10635 } 10636 } 10637 return true; 10638 } 10639 10640 @Override 10641 protected ActivityIntentInfo[] newArray(int size) { 10642 return new ActivityIntentInfo[size]; 10643 } 10644 10645 @Override 10646 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10647 if (!sUserManager.exists(userId)) return true; 10648 PackageParser.Package p = filter.activity.owner; 10649 if (p != null) { 10650 PackageSetting ps = (PackageSetting)p.mExtras; 10651 if (ps != null) { 10652 // System apps are never considered stopped for purposes of 10653 // filtering, because there may be no way for the user to 10654 // actually re-launch them. 10655 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10656 && ps.getStopped(userId); 10657 } 10658 } 10659 return false; 10660 } 10661 10662 @Override 10663 protected boolean isPackageForFilter(String packageName, 10664 PackageParser.ActivityIntentInfo info) { 10665 return packageName.equals(info.activity.owner.packageName); 10666 } 10667 10668 @Override 10669 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10670 int match, int userId) { 10671 if (!sUserManager.exists(userId)) return null; 10672 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10673 return null; 10674 } 10675 final PackageParser.Activity activity = info.activity; 10676 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10677 if (ps == null) { 10678 return null; 10679 } 10680 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10681 ps.readUserState(userId), userId); 10682 if (ai == null) { 10683 return null; 10684 } 10685 final ResolveInfo res = new ResolveInfo(); 10686 res.activityInfo = ai; 10687 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10688 res.filter = info; 10689 } 10690 if (info != null) { 10691 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10692 } 10693 res.priority = info.getPriority(); 10694 res.preferredOrder = activity.owner.mPreferredOrder; 10695 //System.out.println("Result: " + res.activityInfo.className + 10696 // " = " + res.priority); 10697 res.match = match; 10698 res.isDefault = info.hasDefault; 10699 res.labelRes = info.labelRes; 10700 res.nonLocalizedLabel = info.nonLocalizedLabel; 10701 if (userNeedsBadging(userId)) { 10702 res.noResourceId = true; 10703 } else { 10704 res.icon = info.icon; 10705 } 10706 res.iconResourceId = info.icon; 10707 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10708 return res; 10709 } 10710 10711 @Override 10712 protected void sortResults(List<ResolveInfo> results) { 10713 Collections.sort(results, mResolvePrioritySorter); 10714 } 10715 10716 @Override 10717 protected void dumpFilter(PrintWriter out, String prefix, 10718 PackageParser.ActivityIntentInfo filter) { 10719 out.print(prefix); out.print( 10720 Integer.toHexString(System.identityHashCode(filter.activity))); 10721 out.print(' '); 10722 filter.activity.printComponentShortName(out); 10723 out.print(" filter "); 10724 out.println(Integer.toHexString(System.identityHashCode(filter))); 10725 } 10726 10727 @Override 10728 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10729 return filter.activity; 10730 } 10731 10732 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10733 PackageParser.Activity activity = (PackageParser.Activity)label; 10734 out.print(prefix); out.print( 10735 Integer.toHexString(System.identityHashCode(activity))); 10736 out.print(' '); 10737 activity.printComponentShortName(out); 10738 if (count > 1) { 10739 out.print(" ("); out.print(count); out.print(" filters)"); 10740 } 10741 out.println(); 10742 } 10743 10744 // Keys are String (activity class name), values are Activity. 10745 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10746 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10747 private int mFlags; 10748 } 10749 10750 private final class ServiceIntentResolver 10751 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10752 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10753 boolean defaultOnly, int userId) { 10754 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10755 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10756 } 10757 10758 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10759 int userId) { 10760 if (!sUserManager.exists(userId)) return null; 10761 mFlags = flags; 10762 return super.queryIntent(intent, resolvedType, 10763 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10764 } 10765 10766 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10767 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10768 if (!sUserManager.exists(userId)) return null; 10769 if (packageServices == null) { 10770 return null; 10771 } 10772 mFlags = flags; 10773 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10774 final int N = packageServices.size(); 10775 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10776 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10777 10778 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10779 for (int i = 0; i < N; ++i) { 10780 intentFilters = packageServices.get(i).intents; 10781 if (intentFilters != null && intentFilters.size() > 0) { 10782 PackageParser.ServiceIntentInfo[] array = 10783 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10784 intentFilters.toArray(array); 10785 listCut.add(array); 10786 } 10787 } 10788 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10789 } 10790 10791 public final void addService(PackageParser.Service s) { 10792 mServices.put(s.getComponentName(), s); 10793 if (DEBUG_SHOW_INFO) { 10794 Log.v(TAG, " " 10795 + (s.info.nonLocalizedLabel != null 10796 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10797 Log.v(TAG, " Class=" + s.info.name); 10798 } 10799 final int NI = s.intents.size(); 10800 int j; 10801 for (j=0; j<NI; j++) { 10802 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10803 if (DEBUG_SHOW_INFO) { 10804 Log.v(TAG, " IntentFilter:"); 10805 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10806 } 10807 if (!intent.debugCheck()) { 10808 Log.w(TAG, "==> For Service " + s.info.name); 10809 } 10810 addFilter(intent); 10811 } 10812 } 10813 10814 public final void removeService(PackageParser.Service s) { 10815 mServices.remove(s.getComponentName()); 10816 if (DEBUG_SHOW_INFO) { 10817 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10818 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10819 Log.v(TAG, " Class=" + s.info.name); 10820 } 10821 final int NI = s.intents.size(); 10822 int j; 10823 for (j=0; j<NI; j++) { 10824 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10825 if (DEBUG_SHOW_INFO) { 10826 Log.v(TAG, " IntentFilter:"); 10827 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10828 } 10829 removeFilter(intent); 10830 } 10831 } 10832 10833 @Override 10834 protected boolean allowFilterResult( 10835 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10836 ServiceInfo filterSi = filter.service.info; 10837 for (int i=dest.size()-1; i>=0; i--) { 10838 ServiceInfo destAi = dest.get(i).serviceInfo; 10839 if (destAi.name == filterSi.name 10840 && destAi.packageName == filterSi.packageName) { 10841 return false; 10842 } 10843 } 10844 return true; 10845 } 10846 10847 @Override 10848 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10849 return new PackageParser.ServiceIntentInfo[size]; 10850 } 10851 10852 @Override 10853 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10854 if (!sUserManager.exists(userId)) return true; 10855 PackageParser.Package p = filter.service.owner; 10856 if (p != null) { 10857 PackageSetting ps = (PackageSetting)p.mExtras; 10858 if (ps != null) { 10859 // System apps are never considered stopped for purposes of 10860 // filtering, because there may be no way for the user to 10861 // actually re-launch them. 10862 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10863 && ps.getStopped(userId); 10864 } 10865 } 10866 return false; 10867 } 10868 10869 @Override 10870 protected boolean isPackageForFilter(String packageName, 10871 PackageParser.ServiceIntentInfo info) { 10872 return packageName.equals(info.service.owner.packageName); 10873 } 10874 10875 @Override 10876 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10877 int match, int userId) { 10878 if (!sUserManager.exists(userId)) return null; 10879 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10880 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10881 return null; 10882 } 10883 final PackageParser.Service service = info.service; 10884 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10885 if (ps == null) { 10886 return null; 10887 } 10888 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10889 ps.readUserState(userId), userId); 10890 if (si == null) { 10891 return null; 10892 } 10893 final ResolveInfo res = new ResolveInfo(); 10894 res.serviceInfo = si; 10895 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10896 res.filter = filter; 10897 } 10898 res.priority = info.getPriority(); 10899 res.preferredOrder = service.owner.mPreferredOrder; 10900 res.match = match; 10901 res.isDefault = info.hasDefault; 10902 res.labelRes = info.labelRes; 10903 res.nonLocalizedLabel = info.nonLocalizedLabel; 10904 res.icon = info.icon; 10905 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10906 return res; 10907 } 10908 10909 @Override 10910 protected void sortResults(List<ResolveInfo> results) { 10911 Collections.sort(results, mResolvePrioritySorter); 10912 } 10913 10914 @Override 10915 protected void dumpFilter(PrintWriter out, String prefix, 10916 PackageParser.ServiceIntentInfo filter) { 10917 out.print(prefix); out.print( 10918 Integer.toHexString(System.identityHashCode(filter.service))); 10919 out.print(' '); 10920 filter.service.printComponentShortName(out); 10921 out.print(" filter "); 10922 out.println(Integer.toHexString(System.identityHashCode(filter))); 10923 } 10924 10925 @Override 10926 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10927 return filter.service; 10928 } 10929 10930 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10931 PackageParser.Service service = (PackageParser.Service)label; 10932 out.print(prefix); out.print( 10933 Integer.toHexString(System.identityHashCode(service))); 10934 out.print(' '); 10935 service.printComponentShortName(out); 10936 if (count > 1) { 10937 out.print(" ("); out.print(count); out.print(" filters)"); 10938 } 10939 out.println(); 10940 } 10941 10942// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10943// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10944// final List<ResolveInfo> retList = Lists.newArrayList(); 10945// while (i.hasNext()) { 10946// final ResolveInfo resolveInfo = (ResolveInfo) i; 10947// if (isEnabledLP(resolveInfo.serviceInfo)) { 10948// retList.add(resolveInfo); 10949// } 10950// } 10951// return retList; 10952// } 10953 10954 // Keys are String (activity class name), values are Activity. 10955 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10956 = new ArrayMap<ComponentName, PackageParser.Service>(); 10957 private int mFlags; 10958 }; 10959 10960 private final class ProviderIntentResolver 10961 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10962 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10963 boolean defaultOnly, int userId) { 10964 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10965 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10966 } 10967 10968 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10969 int userId) { 10970 if (!sUserManager.exists(userId)) 10971 return null; 10972 mFlags = flags; 10973 return super.queryIntent(intent, resolvedType, 10974 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10975 } 10976 10977 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10978 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10979 if (!sUserManager.exists(userId)) 10980 return null; 10981 if (packageProviders == null) { 10982 return null; 10983 } 10984 mFlags = flags; 10985 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10986 final int N = packageProviders.size(); 10987 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10988 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10989 10990 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10991 for (int i = 0; i < N; ++i) { 10992 intentFilters = packageProviders.get(i).intents; 10993 if (intentFilters != null && intentFilters.size() > 0) { 10994 PackageParser.ProviderIntentInfo[] array = 10995 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10996 intentFilters.toArray(array); 10997 listCut.add(array); 10998 } 10999 } 11000 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11001 } 11002 11003 public final void addProvider(PackageParser.Provider p) { 11004 if (mProviders.containsKey(p.getComponentName())) { 11005 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11006 return; 11007 } 11008 11009 mProviders.put(p.getComponentName(), p); 11010 if (DEBUG_SHOW_INFO) { 11011 Log.v(TAG, " " 11012 + (p.info.nonLocalizedLabel != null 11013 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11014 Log.v(TAG, " Class=" + p.info.name); 11015 } 11016 final int NI = p.intents.size(); 11017 int j; 11018 for (j = 0; j < NI; j++) { 11019 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11020 if (DEBUG_SHOW_INFO) { 11021 Log.v(TAG, " IntentFilter:"); 11022 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11023 } 11024 if (!intent.debugCheck()) { 11025 Log.w(TAG, "==> For Provider " + p.info.name); 11026 } 11027 addFilter(intent); 11028 } 11029 } 11030 11031 public final void removeProvider(PackageParser.Provider p) { 11032 mProviders.remove(p.getComponentName()); 11033 if (DEBUG_SHOW_INFO) { 11034 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11035 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11036 Log.v(TAG, " Class=" + p.info.name); 11037 } 11038 final int NI = p.intents.size(); 11039 int j; 11040 for (j = 0; j < NI; j++) { 11041 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11042 if (DEBUG_SHOW_INFO) { 11043 Log.v(TAG, " IntentFilter:"); 11044 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11045 } 11046 removeFilter(intent); 11047 } 11048 } 11049 11050 @Override 11051 protected boolean allowFilterResult( 11052 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11053 ProviderInfo filterPi = filter.provider.info; 11054 for (int i = dest.size() - 1; i >= 0; i--) { 11055 ProviderInfo destPi = dest.get(i).providerInfo; 11056 if (destPi.name == filterPi.name 11057 && destPi.packageName == filterPi.packageName) { 11058 return false; 11059 } 11060 } 11061 return true; 11062 } 11063 11064 @Override 11065 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11066 return new PackageParser.ProviderIntentInfo[size]; 11067 } 11068 11069 @Override 11070 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11071 if (!sUserManager.exists(userId)) 11072 return true; 11073 PackageParser.Package p = filter.provider.owner; 11074 if (p != null) { 11075 PackageSetting ps = (PackageSetting) p.mExtras; 11076 if (ps != null) { 11077 // System apps are never considered stopped for purposes of 11078 // filtering, because there may be no way for the user to 11079 // actually re-launch them. 11080 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11081 && ps.getStopped(userId); 11082 } 11083 } 11084 return false; 11085 } 11086 11087 @Override 11088 protected boolean isPackageForFilter(String packageName, 11089 PackageParser.ProviderIntentInfo info) { 11090 return packageName.equals(info.provider.owner.packageName); 11091 } 11092 11093 @Override 11094 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11095 int match, int userId) { 11096 if (!sUserManager.exists(userId)) 11097 return null; 11098 final PackageParser.ProviderIntentInfo info = filter; 11099 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11100 return null; 11101 } 11102 final PackageParser.Provider provider = info.provider; 11103 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11104 if (ps == null) { 11105 return null; 11106 } 11107 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11108 ps.readUserState(userId), userId); 11109 if (pi == null) { 11110 return null; 11111 } 11112 final ResolveInfo res = new ResolveInfo(); 11113 res.providerInfo = pi; 11114 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11115 res.filter = filter; 11116 } 11117 res.priority = info.getPriority(); 11118 res.preferredOrder = provider.owner.mPreferredOrder; 11119 res.match = match; 11120 res.isDefault = info.hasDefault; 11121 res.labelRes = info.labelRes; 11122 res.nonLocalizedLabel = info.nonLocalizedLabel; 11123 res.icon = info.icon; 11124 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11125 return res; 11126 } 11127 11128 @Override 11129 protected void sortResults(List<ResolveInfo> results) { 11130 Collections.sort(results, mResolvePrioritySorter); 11131 } 11132 11133 @Override 11134 protected void dumpFilter(PrintWriter out, String prefix, 11135 PackageParser.ProviderIntentInfo filter) { 11136 out.print(prefix); 11137 out.print( 11138 Integer.toHexString(System.identityHashCode(filter.provider))); 11139 out.print(' '); 11140 filter.provider.printComponentShortName(out); 11141 out.print(" filter "); 11142 out.println(Integer.toHexString(System.identityHashCode(filter))); 11143 } 11144 11145 @Override 11146 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11147 return filter.provider; 11148 } 11149 11150 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11151 PackageParser.Provider provider = (PackageParser.Provider)label; 11152 out.print(prefix); out.print( 11153 Integer.toHexString(System.identityHashCode(provider))); 11154 out.print(' '); 11155 provider.printComponentShortName(out); 11156 if (count > 1) { 11157 out.print(" ("); out.print(count); out.print(" filters)"); 11158 } 11159 out.println(); 11160 } 11161 11162 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11163 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11164 private int mFlags; 11165 } 11166 11167 private static final class EphemeralIntentResolver 11168 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11169 @Override 11170 protected EphemeralResolveIntentInfo[] newArray(int size) { 11171 return new EphemeralResolveIntentInfo[size]; 11172 } 11173 11174 @Override 11175 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11176 return true; 11177 } 11178 11179 @Override 11180 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11181 int userId) { 11182 if (!sUserManager.exists(userId)) { 11183 return null; 11184 } 11185 return info.getEphemeralResolveInfo(); 11186 } 11187 } 11188 11189 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11190 new Comparator<ResolveInfo>() { 11191 public int compare(ResolveInfo r1, ResolveInfo r2) { 11192 int v1 = r1.priority; 11193 int v2 = r2.priority; 11194 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11195 if (v1 != v2) { 11196 return (v1 > v2) ? -1 : 1; 11197 } 11198 v1 = r1.preferredOrder; 11199 v2 = r2.preferredOrder; 11200 if (v1 != v2) { 11201 return (v1 > v2) ? -1 : 1; 11202 } 11203 if (r1.isDefault != r2.isDefault) { 11204 return r1.isDefault ? -1 : 1; 11205 } 11206 v1 = r1.match; 11207 v2 = r2.match; 11208 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11209 if (v1 != v2) { 11210 return (v1 > v2) ? -1 : 1; 11211 } 11212 if (r1.system != r2.system) { 11213 return r1.system ? -1 : 1; 11214 } 11215 if (r1.activityInfo != null) { 11216 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11217 } 11218 if (r1.serviceInfo != null) { 11219 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11220 } 11221 if (r1.providerInfo != null) { 11222 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11223 } 11224 return 0; 11225 } 11226 }; 11227 11228 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11229 new Comparator<ProviderInfo>() { 11230 public int compare(ProviderInfo p1, ProviderInfo p2) { 11231 final int v1 = p1.initOrder; 11232 final int v2 = p2.initOrder; 11233 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11234 } 11235 }; 11236 11237 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11238 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11239 final int[] userIds) { 11240 mHandler.post(new Runnable() { 11241 @Override 11242 public void run() { 11243 try { 11244 final IActivityManager am = ActivityManagerNative.getDefault(); 11245 if (am == null) return; 11246 final int[] resolvedUserIds; 11247 if (userIds == null) { 11248 resolvedUserIds = am.getRunningUserIds(); 11249 } else { 11250 resolvedUserIds = userIds; 11251 } 11252 for (int id : resolvedUserIds) { 11253 final Intent intent = new Intent(action, 11254 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11255 if (extras != null) { 11256 intent.putExtras(extras); 11257 } 11258 if (targetPkg != null) { 11259 intent.setPackage(targetPkg); 11260 } 11261 // Modify the UID when posting to other users 11262 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11263 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11264 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11265 intent.putExtra(Intent.EXTRA_UID, uid); 11266 } 11267 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11268 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11269 if (DEBUG_BROADCASTS) { 11270 RuntimeException here = new RuntimeException("here"); 11271 here.fillInStackTrace(); 11272 Slog.d(TAG, "Sending to user " + id + ": " 11273 + intent.toShortString(false, true, false, false) 11274 + " " + intent.getExtras(), here); 11275 } 11276 am.broadcastIntent(null, intent, null, finishedReceiver, 11277 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11278 null, finishedReceiver != null, false, id); 11279 } 11280 } catch (RemoteException ex) { 11281 } 11282 } 11283 }); 11284 } 11285 11286 /** 11287 * Check if the external storage media is available. This is true if there 11288 * is a mounted external storage medium or if the external storage is 11289 * emulated. 11290 */ 11291 private boolean isExternalMediaAvailable() { 11292 return mMediaMounted || Environment.isExternalStorageEmulated(); 11293 } 11294 11295 @Override 11296 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11297 // writer 11298 synchronized (mPackages) { 11299 if (!isExternalMediaAvailable()) { 11300 // If the external storage is no longer mounted at this point, 11301 // the caller may not have been able to delete all of this 11302 // packages files and can not delete any more. Bail. 11303 return null; 11304 } 11305 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11306 if (lastPackage != null) { 11307 pkgs.remove(lastPackage); 11308 } 11309 if (pkgs.size() > 0) { 11310 return pkgs.get(0); 11311 } 11312 } 11313 return null; 11314 } 11315 11316 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11317 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11318 userId, andCode ? 1 : 0, packageName); 11319 if (mSystemReady) { 11320 msg.sendToTarget(); 11321 } else { 11322 if (mPostSystemReadyMessages == null) { 11323 mPostSystemReadyMessages = new ArrayList<>(); 11324 } 11325 mPostSystemReadyMessages.add(msg); 11326 } 11327 } 11328 11329 void startCleaningPackages() { 11330 // reader 11331 if (!isExternalMediaAvailable()) { 11332 return; 11333 } 11334 synchronized (mPackages) { 11335 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11336 return; 11337 } 11338 } 11339 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11340 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11341 IActivityManager am = ActivityManagerNative.getDefault(); 11342 if (am != null) { 11343 try { 11344 am.startService(null, intent, null, mContext.getOpPackageName(), 11345 UserHandle.USER_SYSTEM); 11346 } catch (RemoteException e) { 11347 } 11348 } 11349 } 11350 11351 @Override 11352 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11353 int installFlags, String installerPackageName, int userId) { 11354 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11355 11356 final int callingUid = Binder.getCallingUid(); 11357 enforceCrossUserPermission(callingUid, userId, 11358 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11359 11360 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11361 try { 11362 if (observer != null) { 11363 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11364 } 11365 } catch (RemoteException re) { 11366 } 11367 return; 11368 } 11369 11370 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11371 installFlags |= PackageManager.INSTALL_FROM_ADB; 11372 11373 } else { 11374 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11375 // about installerPackageName. 11376 11377 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11378 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11379 } 11380 11381 UserHandle user; 11382 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11383 user = UserHandle.ALL; 11384 } else { 11385 user = new UserHandle(userId); 11386 } 11387 11388 // Only system components can circumvent runtime permissions when installing. 11389 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11390 && mContext.checkCallingOrSelfPermission(Manifest.permission 11391 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11392 throw new SecurityException("You need the " 11393 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11394 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11395 } 11396 11397 final File originFile = new File(originPath); 11398 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11399 11400 final Message msg = mHandler.obtainMessage(INIT_COPY); 11401 final VerificationInfo verificationInfo = new VerificationInfo( 11402 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11403 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11404 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11405 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11406 null /*certificates*/); 11407 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11408 msg.obj = params; 11409 11410 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11411 System.identityHashCode(msg.obj)); 11412 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11413 System.identityHashCode(msg.obj)); 11414 11415 mHandler.sendMessage(msg); 11416 } 11417 11418 void installStage(String packageName, File stagedDir, String stagedCid, 11419 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11420 String installerPackageName, int installerUid, UserHandle user, 11421 Certificate[][] certificates) { 11422 if (DEBUG_EPHEMERAL) { 11423 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11424 Slog.d(TAG, "Ephemeral install of " + packageName); 11425 } 11426 } 11427 final VerificationInfo verificationInfo = new VerificationInfo( 11428 sessionParams.originatingUri, sessionParams.referrerUri, 11429 sessionParams.originatingUid, installerUid); 11430 11431 final OriginInfo origin; 11432 if (stagedDir != null) { 11433 origin = OriginInfo.fromStagedFile(stagedDir); 11434 } else { 11435 origin = OriginInfo.fromStagedContainer(stagedCid); 11436 } 11437 11438 final Message msg = mHandler.obtainMessage(INIT_COPY); 11439 final InstallParams params = new InstallParams(origin, null, observer, 11440 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11441 verificationInfo, user, sessionParams.abiOverride, 11442 sessionParams.grantedRuntimePermissions, certificates); 11443 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11444 msg.obj = params; 11445 11446 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11447 System.identityHashCode(msg.obj)); 11448 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11449 System.identityHashCode(msg.obj)); 11450 11451 mHandler.sendMessage(msg); 11452 } 11453 11454 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11455 int userId) { 11456 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11457 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11458 } 11459 11460 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11461 int appId, int userId) { 11462 Bundle extras = new Bundle(1); 11463 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11464 11465 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11466 packageName, extras, 0, null, null, new int[] {userId}); 11467 try { 11468 IActivityManager am = ActivityManagerNative.getDefault(); 11469 if (isSystem && am.isUserRunning(userId, 0)) { 11470 // The just-installed/enabled app is bundled on the system, so presumed 11471 // to be able to run automatically without needing an explicit launch. 11472 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11473 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11474 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11475 .setPackage(packageName); 11476 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11477 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11478 } 11479 } catch (RemoteException e) { 11480 // shouldn't happen 11481 Slog.w(TAG, "Unable to bootstrap installed package", e); 11482 } 11483 } 11484 11485 @Override 11486 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11487 int userId) { 11488 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11489 PackageSetting pkgSetting; 11490 final int uid = Binder.getCallingUid(); 11491 enforceCrossUserPermission(uid, userId, 11492 true /* requireFullPermission */, true /* checkShell */, 11493 "setApplicationHiddenSetting for user " + userId); 11494 11495 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11496 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11497 return false; 11498 } 11499 11500 long callingId = Binder.clearCallingIdentity(); 11501 try { 11502 boolean sendAdded = false; 11503 boolean sendRemoved = false; 11504 // writer 11505 synchronized (mPackages) { 11506 pkgSetting = mSettings.mPackages.get(packageName); 11507 if (pkgSetting == null) { 11508 return false; 11509 } 11510 // Do not allow "android" is being disabled 11511 if ("android".equals(packageName)) { 11512 Slog.w(TAG, "Cannot hide package: android"); 11513 return false; 11514 } 11515 // Only allow protected packages to hide themselves. 11516 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11517 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11518 Slog.w(TAG, "Not hiding protected package: " + packageName); 11519 return false; 11520 } 11521 11522 if (pkgSetting.getHidden(userId) != hidden) { 11523 pkgSetting.setHidden(hidden, userId); 11524 mSettings.writePackageRestrictionsLPr(userId); 11525 if (hidden) { 11526 sendRemoved = true; 11527 } else { 11528 sendAdded = true; 11529 } 11530 } 11531 } 11532 if (sendAdded) { 11533 sendPackageAddedForUser(packageName, pkgSetting, userId); 11534 return true; 11535 } 11536 if (sendRemoved) { 11537 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11538 "hiding pkg"); 11539 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11540 return true; 11541 } 11542 } finally { 11543 Binder.restoreCallingIdentity(callingId); 11544 } 11545 return false; 11546 } 11547 11548 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11549 int userId) { 11550 final PackageRemovedInfo info = new PackageRemovedInfo(); 11551 info.removedPackage = packageName; 11552 info.removedUsers = new int[] {userId}; 11553 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11554 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11555 } 11556 11557 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11558 if (pkgList.length > 0) { 11559 Bundle extras = new Bundle(1); 11560 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11561 11562 sendPackageBroadcast( 11563 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11564 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11565 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11566 new int[] {userId}); 11567 } 11568 } 11569 11570 /** 11571 * Returns true if application is not found or there was an error. Otherwise it returns 11572 * the hidden state of the package for the given user. 11573 */ 11574 @Override 11575 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11576 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11577 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11578 true /* requireFullPermission */, false /* checkShell */, 11579 "getApplicationHidden for user " + userId); 11580 PackageSetting pkgSetting; 11581 long callingId = Binder.clearCallingIdentity(); 11582 try { 11583 // writer 11584 synchronized (mPackages) { 11585 pkgSetting = mSettings.mPackages.get(packageName); 11586 if (pkgSetting == null) { 11587 return true; 11588 } 11589 return pkgSetting.getHidden(userId); 11590 } 11591 } finally { 11592 Binder.restoreCallingIdentity(callingId); 11593 } 11594 } 11595 11596 /** 11597 * @hide 11598 */ 11599 @Override 11600 public int installExistingPackageAsUser(String packageName, int userId) { 11601 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11602 null); 11603 PackageSetting pkgSetting; 11604 final int uid = Binder.getCallingUid(); 11605 enforceCrossUserPermission(uid, userId, 11606 true /* requireFullPermission */, true /* checkShell */, 11607 "installExistingPackage for user " + userId); 11608 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11609 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11610 } 11611 11612 long callingId = Binder.clearCallingIdentity(); 11613 try { 11614 boolean installed = false; 11615 11616 // writer 11617 synchronized (mPackages) { 11618 pkgSetting = mSettings.mPackages.get(packageName); 11619 if (pkgSetting == null) { 11620 return PackageManager.INSTALL_FAILED_INVALID_URI; 11621 } 11622 if (!pkgSetting.getInstalled(userId)) { 11623 pkgSetting.setInstalled(true, userId); 11624 pkgSetting.setHidden(false, userId); 11625 mSettings.writePackageRestrictionsLPr(userId); 11626 installed = true; 11627 } 11628 } 11629 11630 if (installed) { 11631 if (pkgSetting.pkg != null) { 11632 synchronized (mInstallLock) { 11633 // We don't need to freeze for a brand new install 11634 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11635 } 11636 } 11637 sendPackageAddedForUser(packageName, pkgSetting, userId); 11638 } 11639 } finally { 11640 Binder.restoreCallingIdentity(callingId); 11641 } 11642 11643 return PackageManager.INSTALL_SUCCEEDED; 11644 } 11645 11646 boolean isUserRestricted(int userId, String restrictionKey) { 11647 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11648 if (restrictions.getBoolean(restrictionKey, false)) { 11649 Log.w(TAG, "User is restricted: " + restrictionKey); 11650 return true; 11651 } 11652 return false; 11653 } 11654 11655 @Override 11656 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11657 int userId) { 11658 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11659 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11660 true /* requireFullPermission */, true /* checkShell */, 11661 "setPackagesSuspended for user " + userId); 11662 11663 if (ArrayUtils.isEmpty(packageNames)) { 11664 return packageNames; 11665 } 11666 11667 // List of package names for whom the suspended state has changed. 11668 List<String> changedPackages = new ArrayList<>(packageNames.length); 11669 // List of package names for whom the suspended state is not set as requested in this 11670 // method. 11671 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11672 long callingId = Binder.clearCallingIdentity(); 11673 try { 11674 for (int i = 0; i < packageNames.length; i++) { 11675 String packageName = packageNames[i]; 11676 boolean changed = false; 11677 final int appId; 11678 synchronized (mPackages) { 11679 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11680 if (pkgSetting == null) { 11681 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11682 + "\". Skipping suspending/un-suspending."); 11683 unactionedPackages.add(packageName); 11684 continue; 11685 } 11686 appId = pkgSetting.appId; 11687 if (pkgSetting.getSuspended(userId) != suspended) { 11688 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11689 unactionedPackages.add(packageName); 11690 continue; 11691 } 11692 pkgSetting.setSuspended(suspended, userId); 11693 mSettings.writePackageRestrictionsLPr(userId); 11694 changed = true; 11695 changedPackages.add(packageName); 11696 } 11697 } 11698 11699 if (changed && suspended) { 11700 killApplication(packageName, UserHandle.getUid(userId, appId), 11701 "suspending package"); 11702 } 11703 } 11704 } finally { 11705 Binder.restoreCallingIdentity(callingId); 11706 } 11707 11708 if (!changedPackages.isEmpty()) { 11709 sendPackagesSuspendedForUser(changedPackages.toArray( 11710 new String[changedPackages.size()]), userId, suspended); 11711 } 11712 11713 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11714 } 11715 11716 @Override 11717 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11718 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11719 true /* requireFullPermission */, false /* checkShell */, 11720 "isPackageSuspendedForUser for user " + userId); 11721 synchronized (mPackages) { 11722 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11723 if (pkgSetting == null) { 11724 throw new IllegalArgumentException("Unknown target package: " + packageName); 11725 } 11726 return pkgSetting.getSuspended(userId); 11727 } 11728 } 11729 11730 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11731 if (isPackageDeviceAdmin(packageName, userId)) { 11732 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11733 + "\": has an active device admin"); 11734 return false; 11735 } 11736 11737 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11738 if (packageName.equals(activeLauncherPackageName)) { 11739 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11740 + "\": contains the active launcher"); 11741 return false; 11742 } 11743 11744 if (packageName.equals(mRequiredInstallerPackage)) { 11745 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11746 + "\": required for package installation"); 11747 return false; 11748 } 11749 11750 if (packageName.equals(mRequiredVerifierPackage)) { 11751 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11752 + "\": required for package verification"); 11753 return false; 11754 } 11755 11756 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11757 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11758 + "\": is the default dialer"); 11759 return false; 11760 } 11761 11762 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11763 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11764 + "\": protected package"); 11765 return false; 11766 } 11767 11768 return true; 11769 } 11770 11771 private String getActiveLauncherPackageName(int userId) { 11772 Intent intent = new Intent(Intent.ACTION_MAIN); 11773 intent.addCategory(Intent.CATEGORY_HOME); 11774 ResolveInfo resolveInfo = resolveIntent( 11775 intent, 11776 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11777 PackageManager.MATCH_DEFAULT_ONLY, 11778 userId); 11779 11780 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11781 } 11782 11783 private String getDefaultDialerPackageName(int userId) { 11784 synchronized (mPackages) { 11785 return mSettings.getDefaultDialerPackageNameLPw(userId); 11786 } 11787 } 11788 11789 @Override 11790 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11791 mContext.enforceCallingOrSelfPermission( 11792 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11793 "Only package verification agents can verify applications"); 11794 11795 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11796 final PackageVerificationResponse response = new PackageVerificationResponse( 11797 verificationCode, Binder.getCallingUid()); 11798 msg.arg1 = id; 11799 msg.obj = response; 11800 mHandler.sendMessage(msg); 11801 } 11802 11803 @Override 11804 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11805 long millisecondsToDelay) { 11806 mContext.enforceCallingOrSelfPermission( 11807 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11808 "Only package verification agents can extend verification timeouts"); 11809 11810 final PackageVerificationState state = mPendingVerification.get(id); 11811 final PackageVerificationResponse response = new PackageVerificationResponse( 11812 verificationCodeAtTimeout, Binder.getCallingUid()); 11813 11814 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11815 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11816 } 11817 if (millisecondsToDelay < 0) { 11818 millisecondsToDelay = 0; 11819 } 11820 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11821 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11822 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11823 } 11824 11825 if ((state != null) && !state.timeoutExtended()) { 11826 state.extendTimeout(); 11827 11828 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11829 msg.arg1 = id; 11830 msg.obj = response; 11831 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11832 } 11833 } 11834 11835 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11836 int verificationCode, UserHandle user) { 11837 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11838 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11839 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11840 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11841 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11842 11843 mContext.sendBroadcastAsUser(intent, user, 11844 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11845 } 11846 11847 private ComponentName matchComponentForVerifier(String packageName, 11848 List<ResolveInfo> receivers) { 11849 ActivityInfo targetReceiver = null; 11850 11851 final int NR = receivers.size(); 11852 for (int i = 0; i < NR; i++) { 11853 final ResolveInfo info = receivers.get(i); 11854 if (info.activityInfo == null) { 11855 continue; 11856 } 11857 11858 if (packageName.equals(info.activityInfo.packageName)) { 11859 targetReceiver = info.activityInfo; 11860 break; 11861 } 11862 } 11863 11864 if (targetReceiver == null) { 11865 return null; 11866 } 11867 11868 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11869 } 11870 11871 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11872 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11873 if (pkgInfo.verifiers.length == 0) { 11874 return null; 11875 } 11876 11877 final int N = pkgInfo.verifiers.length; 11878 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11879 for (int i = 0; i < N; i++) { 11880 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11881 11882 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11883 receivers); 11884 if (comp == null) { 11885 continue; 11886 } 11887 11888 final int verifierUid = getUidForVerifier(verifierInfo); 11889 if (verifierUid == -1) { 11890 continue; 11891 } 11892 11893 if (DEBUG_VERIFY) { 11894 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11895 + " with the correct signature"); 11896 } 11897 sufficientVerifiers.add(comp); 11898 verificationState.addSufficientVerifier(verifierUid); 11899 } 11900 11901 return sufficientVerifiers; 11902 } 11903 11904 private int getUidForVerifier(VerifierInfo verifierInfo) { 11905 synchronized (mPackages) { 11906 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11907 if (pkg == null) { 11908 return -1; 11909 } else if (pkg.mSignatures.length != 1) { 11910 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11911 + " has more than one signature; ignoring"); 11912 return -1; 11913 } 11914 11915 /* 11916 * If the public key of the package's signature does not match 11917 * our expected public key, then this is a different package and 11918 * we should skip. 11919 */ 11920 11921 final byte[] expectedPublicKey; 11922 try { 11923 final Signature verifierSig = pkg.mSignatures[0]; 11924 final PublicKey publicKey = verifierSig.getPublicKey(); 11925 expectedPublicKey = publicKey.getEncoded(); 11926 } catch (CertificateException e) { 11927 return -1; 11928 } 11929 11930 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11931 11932 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11933 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11934 + " does not have the expected public key; ignoring"); 11935 return -1; 11936 } 11937 11938 return pkg.applicationInfo.uid; 11939 } 11940 } 11941 11942 @Override 11943 public void finishPackageInstall(int token, boolean didLaunch) { 11944 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11945 11946 if (DEBUG_INSTALL) { 11947 Slog.v(TAG, "BM finishing package install for " + token); 11948 } 11949 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11950 11951 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11952 mHandler.sendMessage(msg); 11953 } 11954 11955 /** 11956 * Get the verification agent timeout. 11957 * 11958 * @return verification timeout in milliseconds 11959 */ 11960 private long getVerificationTimeout() { 11961 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11962 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11963 DEFAULT_VERIFICATION_TIMEOUT); 11964 } 11965 11966 /** 11967 * Get the default verification agent response code. 11968 * 11969 * @return default verification response code 11970 */ 11971 private int getDefaultVerificationResponse() { 11972 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11973 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11974 DEFAULT_VERIFICATION_RESPONSE); 11975 } 11976 11977 /** 11978 * Check whether or not package verification has been enabled. 11979 * 11980 * @return true if verification should be performed 11981 */ 11982 private boolean isVerificationEnabled(int userId, int installFlags) { 11983 if (!DEFAULT_VERIFY_ENABLE) { 11984 return false; 11985 } 11986 // Ephemeral apps don't get the full verification treatment 11987 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11988 if (DEBUG_EPHEMERAL) { 11989 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11990 } 11991 return false; 11992 } 11993 11994 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11995 11996 // Check if installing from ADB 11997 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11998 // Do not run verification in a test harness environment 11999 if (ActivityManager.isRunningInTestHarness()) { 12000 return false; 12001 } 12002 if (ensureVerifyAppsEnabled) { 12003 return true; 12004 } 12005 // Check if the developer does not want package verification for ADB installs 12006 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12007 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12008 return false; 12009 } 12010 } 12011 12012 if (ensureVerifyAppsEnabled) { 12013 return true; 12014 } 12015 12016 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12017 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12018 } 12019 12020 @Override 12021 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12022 throws RemoteException { 12023 mContext.enforceCallingOrSelfPermission( 12024 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12025 "Only intentfilter verification agents can verify applications"); 12026 12027 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12028 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12029 Binder.getCallingUid(), verificationCode, failedDomains); 12030 msg.arg1 = id; 12031 msg.obj = response; 12032 mHandler.sendMessage(msg); 12033 } 12034 12035 @Override 12036 public int getIntentVerificationStatus(String packageName, int userId) { 12037 synchronized (mPackages) { 12038 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12039 } 12040 } 12041 12042 @Override 12043 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12044 mContext.enforceCallingOrSelfPermission( 12045 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12046 12047 boolean result = false; 12048 synchronized (mPackages) { 12049 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12050 } 12051 if (result) { 12052 scheduleWritePackageRestrictionsLocked(userId); 12053 } 12054 return result; 12055 } 12056 12057 @Override 12058 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12059 String packageName) { 12060 synchronized (mPackages) { 12061 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12062 } 12063 } 12064 12065 @Override 12066 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12067 if (TextUtils.isEmpty(packageName)) { 12068 return ParceledListSlice.emptyList(); 12069 } 12070 synchronized (mPackages) { 12071 PackageParser.Package pkg = mPackages.get(packageName); 12072 if (pkg == null || pkg.activities == null) { 12073 return ParceledListSlice.emptyList(); 12074 } 12075 final int count = pkg.activities.size(); 12076 ArrayList<IntentFilter> result = new ArrayList<>(); 12077 for (int n=0; n<count; n++) { 12078 PackageParser.Activity activity = pkg.activities.get(n); 12079 if (activity.intents != null && activity.intents.size() > 0) { 12080 result.addAll(activity.intents); 12081 } 12082 } 12083 return new ParceledListSlice<>(result); 12084 } 12085 } 12086 12087 @Override 12088 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12089 mContext.enforceCallingOrSelfPermission( 12090 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12091 12092 synchronized (mPackages) { 12093 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12094 if (packageName != null) { 12095 result |= updateIntentVerificationStatus(packageName, 12096 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12097 userId); 12098 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12099 packageName, userId); 12100 } 12101 return result; 12102 } 12103 } 12104 12105 @Override 12106 public String getDefaultBrowserPackageName(int userId) { 12107 synchronized (mPackages) { 12108 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12109 } 12110 } 12111 12112 /** 12113 * Get the "allow unknown sources" setting. 12114 * 12115 * @return the current "allow unknown sources" setting 12116 */ 12117 private int getUnknownSourcesSettings() { 12118 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12119 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12120 -1); 12121 } 12122 12123 @Override 12124 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12125 final int uid = Binder.getCallingUid(); 12126 // writer 12127 synchronized (mPackages) { 12128 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12129 if (targetPackageSetting == null) { 12130 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12131 } 12132 12133 PackageSetting installerPackageSetting; 12134 if (installerPackageName != null) { 12135 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12136 if (installerPackageSetting == null) { 12137 throw new IllegalArgumentException("Unknown installer package: " 12138 + installerPackageName); 12139 } 12140 } else { 12141 installerPackageSetting = null; 12142 } 12143 12144 Signature[] callerSignature; 12145 Object obj = mSettings.getUserIdLPr(uid); 12146 if (obj != null) { 12147 if (obj instanceof SharedUserSetting) { 12148 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12149 } else if (obj instanceof PackageSetting) { 12150 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12151 } else { 12152 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12153 } 12154 } else { 12155 throw new SecurityException("Unknown calling UID: " + uid); 12156 } 12157 12158 // Verify: can't set installerPackageName to a package that is 12159 // not signed with the same cert as the caller. 12160 if (installerPackageSetting != null) { 12161 if (compareSignatures(callerSignature, 12162 installerPackageSetting.signatures.mSignatures) 12163 != PackageManager.SIGNATURE_MATCH) { 12164 throw new SecurityException( 12165 "Caller does not have same cert as new installer package " 12166 + installerPackageName); 12167 } 12168 } 12169 12170 // Verify: if target already has an installer package, it must 12171 // be signed with the same cert as the caller. 12172 if (targetPackageSetting.installerPackageName != null) { 12173 PackageSetting setting = mSettings.mPackages.get( 12174 targetPackageSetting.installerPackageName); 12175 // If the currently set package isn't valid, then it's always 12176 // okay to change it. 12177 if (setting != null) { 12178 if (compareSignatures(callerSignature, 12179 setting.signatures.mSignatures) 12180 != PackageManager.SIGNATURE_MATCH) { 12181 throw new SecurityException( 12182 "Caller does not have same cert as old installer package " 12183 + targetPackageSetting.installerPackageName); 12184 } 12185 } 12186 } 12187 12188 // Okay! 12189 targetPackageSetting.installerPackageName = installerPackageName; 12190 if (installerPackageName != null) { 12191 mSettings.mInstallerPackages.add(installerPackageName); 12192 } 12193 scheduleWriteSettingsLocked(); 12194 } 12195 } 12196 12197 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12198 // Queue up an async operation since the package installation may take a little while. 12199 mHandler.post(new Runnable() { 12200 public void run() { 12201 mHandler.removeCallbacks(this); 12202 // Result object to be returned 12203 PackageInstalledInfo res = new PackageInstalledInfo(); 12204 res.setReturnCode(currentStatus); 12205 res.uid = -1; 12206 res.pkg = null; 12207 res.removedInfo = null; 12208 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12209 args.doPreInstall(res.returnCode); 12210 synchronized (mInstallLock) { 12211 installPackageTracedLI(args, res); 12212 } 12213 args.doPostInstall(res.returnCode, res.uid); 12214 } 12215 12216 // A restore should be performed at this point if (a) the install 12217 // succeeded, (b) the operation is not an update, and (c) the new 12218 // package has not opted out of backup participation. 12219 final boolean update = res.removedInfo != null 12220 && res.removedInfo.removedPackage != null; 12221 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12222 boolean doRestore = !update 12223 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12224 12225 // Set up the post-install work request bookkeeping. This will be used 12226 // and cleaned up by the post-install event handling regardless of whether 12227 // there's a restore pass performed. Token values are >= 1. 12228 int token; 12229 if (mNextInstallToken < 0) mNextInstallToken = 1; 12230 token = mNextInstallToken++; 12231 12232 PostInstallData data = new PostInstallData(args, res); 12233 mRunningInstalls.put(token, data); 12234 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12235 12236 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12237 // Pass responsibility to the Backup Manager. It will perform a 12238 // restore if appropriate, then pass responsibility back to the 12239 // Package Manager to run the post-install observer callbacks 12240 // and broadcasts. 12241 IBackupManager bm = IBackupManager.Stub.asInterface( 12242 ServiceManager.getService(Context.BACKUP_SERVICE)); 12243 if (bm != null) { 12244 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12245 + " to BM for possible restore"); 12246 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12247 try { 12248 // TODO: http://b/22388012 12249 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12250 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12251 } else { 12252 doRestore = false; 12253 } 12254 } catch (RemoteException e) { 12255 // can't happen; the backup manager is local 12256 } catch (Exception e) { 12257 Slog.e(TAG, "Exception trying to enqueue restore", e); 12258 doRestore = false; 12259 } 12260 } else { 12261 Slog.e(TAG, "Backup Manager not found!"); 12262 doRestore = false; 12263 } 12264 } 12265 12266 if (!doRestore) { 12267 // No restore possible, or the Backup Manager was mysteriously not 12268 // available -- just fire the post-install work request directly. 12269 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12270 12271 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12272 12273 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12274 mHandler.sendMessage(msg); 12275 } 12276 } 12277 }); 12278 } 12279 12280 /** 12281 * Callback from PackageSettings whenever an app is first transitioned out of the 12282 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12283 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12284 * here whether the app is the target of an ongoing install, and only send the 12285 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12286 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12287 * handling. 12288 */ 12289 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12290 // Serialize this with the rest of the install-process message chain. In the 12291 // restore-at-install case, this Runnable will necessarily run before the 12292 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12293 // are coherent. In the non-restore case, the app has already completed install 12294 // and been launched through some other means, so it is not in a problematic 12295 // state for observers to see the FIRST_LAUNCH signal. 12296 mHandler.post(new Runnable() { 12297 @Override 12298 public void run() { 12299 for (int i = 0; i < mRunningInstalls.size(); i++) { 12300 final PostInstallData data = mRunningInstalls.valueAt(i); 12301 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12302 // right package; but is it for the right user? 12303 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12304 if (userId == data.res.newUsers[uIndex]) { 12305 if (DEBUG_BACKUP) { 12306 Slog.i(TAG, "Package " + pkgName 12307 + " being restored so deferring FIRST_LAUNCH"); 12308 } 12309 return; 12310 } 12311 } 12312 } 12313 } 12314 // didn't find it, so not being restored 12315 if (DEBUG_BACKUP) { 12316 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12317 } 12318 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12319 } 12320 }); 12321 } 12322 12323 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12324 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12325 installerPkg, null, userIds); 12326 } 12327 12328 private abstract class HandlerParams { 12329 private static final int MAX_RETRIES = 4; 12330 12331 /** 12332 * Number of times startCopy() has been attempted and had a non-fatal 12333 * error. 12334 */ 12335 private int mRetries = 0; 12336 12337 /** User handle for the user requesting the information or installation. */ 12338 private final UserHandle mUser; 12339 String traceMethod; 12340 int traceCookie; 12341 12342 HandlerParams(UserHandle user) { 12343 mUser = user; 12344 } 12345 12346 UserHandle getUser() { 12347 return mUser; 12348 } 12349 12350 HandlerParams setTraceMethod(String traceMethod) { 12351 this.traceMethod = traceMethod; 12352 return this; 12353 } 12354 12355 HandlerParams setTraceCookie(int traceCookie) { 12356 this.traceCookie = traceCookie; 12357 return this; 12358 } 12359 12360 final boolean startCopy() { 12361 boolean res; 12362 try { 12363 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12364 12365 if (++mRetries > MAX_RETRIES) { 12366 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12367 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12368 handleServiceError(); 12369 return false; 12370 } else { 12371 handleStartCopy(); 12372 res = true; 12373 } 12374 } catch (RemoteException e) { 12375 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12376 mHandler.sendEmptyMessage(MCS_RECONNECT); 12377 res = false; 12378 } 12379 handleReturnCode(); 12380 return res; 12381 } 12382 12383 final void serviceError() { 12384 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12385 handleServiceError(); 12386 handleReturnCode(); 12387 } 12388 12389 abstract void handleStartCopy() throws RemoteException; 12390 abstract void handleServiceError(); 12391 abstract void handleReturnCode(); 12392 } 12393 12394 class MeasureParams extends HandlerParams { 12395 private final PackageStats mStats; 12396 private boolean mSuccess; 12397 12398 private final IPackageStatsObserver mObserver; 12399 12400 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12401 super(new UserHandle(stats.userHandle)); 12402 mObserver = observer; 12403 mStats = stats; 12404 } 12405 12406 @Override 12407 public String toString() { 12408 return "MeasureParams{" 12409 + Integer.toHexString(System.identityHashCode(this)) 12410 + " " + mStats.packageName + "}"; 12411 } 12412 12413 @Override 12414 void handleStartCopy() throws RemoteException { 12415 synchronized (mInstallLock) { 12416 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12417 } 12418 12419 if (mSuccess) { 12420 boolean mounted = false; 12421 try { 12422 final String status = Environment.getExternalStorageState(); 12423 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12424 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12425 } catch (Exception e) { 12426 } 12427 12428 if (mounted) { 12429 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12430 12431 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12432 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12433 12434 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12435 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12436 12437 // Always subtract cache size, since it's a subdirectory 12438 mStats.externalDataSize -= mStats.externalCacheSize; 12439 12440 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12441 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12442 12443 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12444 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12445 } 12446 } 12447 } 12448 12449 @Override 12450 void handleReturnCode() { 12451 if (mObserver != null) { 12452 try { 12453 mObserver.onGetStatsCompleted(mStats, mSuccess); 12454 } catch (RemoteException e) { 12455 Slog.i(TAG, "Observer no longer exists."); 12456 } 12457 } 12458 } 12459 12460 @Override 12461 void handleServiceError() { 12462 Slog.e(TAG, "Could not measure application " + mStats.packageName 12463 + " external storage"); 12464 } 12465 } 12466 12467 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12468 throws RemoteException { 12469 long result = 0; 12470 for (File path : paths) { 12471 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12472 } 12473 return result; 12474 } 12475 12476 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12477 for (File path : paths) { 12478 try { 12479 mcs.clearDirectory(path.getAbsolutePath()); 12480 } catch (RemoteException e) { 12481 } 12482 } 12483 } 12484 12485 static class OriginInfo { 12486 /** 12487 * Location where install is coming from, before it has been 12488 * copied/renamed into place. This could be a single monolithic APK 12489 * file, or a cluster directory. This location may be untrusted. 12490 */ 12491 final File file; 12492 final String cid; 12493 12494 /** 12495 * Flag indicating that {@link #file} or {@link #cid} has already been 12496 * staged, meaning downstream users don't need to defensively copy the 12497 * contents. 12498 */ 12499 final boolean staged; 12500 12501 /** 12502 * Flag indicating that {@link #file} or {@link #cid} is an already 12503 * installed app that is being moved. 12504 */ 12505 final boolean existing; 12506 12507 final String resolvedPath; 12508 final File resolvedFile; 12509 12510 static OriginInfo fromNothing() { 12511 return new OriginInfo(null, null, false, false); 12512 } 12513 12514 static OriginInfo fromUntrustedFile(File file) { 12515 return new OriginInfo(file, null, false, false); 12516 } 12517 12518 static OriginInfo fromExistingFile(File file) { 12519 return new OriginInfo(file, null, false, true); 12520 } 12521 12522 static OriginInfo fromStagedFile(File file) { 12523 return new OriginInfo(file, null, true, false); 12524 } 12525 12526 static OriginInfo fromStagedContainer(String cid) { 12527 return new OriginInfo(null, cid, true, false); 12528 } 12529 12530 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12531 this.file = file; 12532 this.cid = cid; 12533 this.staged = staged; 12534 this.existing = existing; 12535 12536 if (cid != null) { 12537 resolvedPath = PackageHelper.getSdDir(cid); 12538 resolvedFile = new File(resolvedPath); 12539 } else if (file != null) { 12540 resolvedPath = file.getAbsolutePath(); 12541 resolvedFile = file; 12542 } else { 12543 resolvedPath = null; 12544 resolvedFile = null; 12545 } 12546 } 12547 } 12548 12549 static class MoveInfo { 12550 final int moveId; 12551 final String fromUuid; 12552 final String toUuid; 12553 final String packageName; 12554 final String dataAppName; 12555 final int appId; 12556 final String seinfo; 12557 final int targetSdkVersion; 12558 12559 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12560 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12561 this.moveId = moveId; 12562 this.fromUuid = fromUuid; 12563 this.toUuid = toUuid; 12564 this.packageName = packageName; 12565 this.dataAppName = dataAppName; 12566 this.appId = appId; 12567 this.seinfo = seinfo; 12568 this.targetSdkVersion = targetSdkVersion; 12569 } 12570 } 12571 12572 static class VerificationInfo { 12573 /** A constant used to indicate that a uid value is not present. */ 12574 public static final int NO_UID = -1; 12575 12576 /** URI referencing where the package was downloaded from. */ 12577 final Uri originatingUri; 12578 12579 /** HTTP referrer URI associated with the originatingURI. */ 12580 final Uri referrer; 12581 12582 /** UID of the application that the install request originated from. */ 12583 final int originatingUid; 12584 12585 /** UID of application requesting the install */ 12586 final int installerUid; 12587 12588 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12589 this.originatingUri = originatingUri; 12590 this.referrer = referrer; 12591 this.originatingUid = originatingUid; 12592 this.installerUid = installerUid; 12593 } 12594 } 12595 12596 class InstallParams extends HandlerParams { 12597 final OriginInfo origin; 12598 final MoveInfo move; 12599 final IPackageInstallObserver2 observer; 12600 int installFlags; 12601 final String installerPackageName; 12602 final String volumeUuid; 12603 private InstallArgs mArgs; 12604 private int mRet; 12605 final String packageAbiOverride; 12606 final String[] grantedRuntimePermissions; 12607 final VerificationInfo verificationInfo; 12608 final Certificate[][] certificates; 12609 12610 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12611 int installFlags, String installerPackageName, String volumeUuid, 12612 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12613 String[] grantedPermissions, Certificate[][] certificates) { 12614 super(user); 12615 this.origin = origin; 12616 this.move = move; 12617 this.observer = observer; 12618 this.installFlags = installFlags; 12619 this.installerPackageName = installerPackageName; 12620 this.volumeUuid = volumeUuid; 12621 this.verificationInfo = verificationInfo; 12622 this.packageAbiOverride = packageAbiOverride; 12623 this.grantedRuntimePermissions = grantedPermissions; 12624 this.certificates = certificates; 12625 } 12626 12627 @Override 12628 public String toString() { 12629 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12630 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12631 } 12632 12633 private int installLocationPolicy(PackageInfoLite pkgLite) { 12634 String packageName = pkgLite.packageName; 12635 int installLocation = pkgLite.installLocation; 12636 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12637 // reader 12638 synchronized (mPackages) { 12639 // Currently installed package which the new package is attempting to replace or 12640 // null if no such package is installed. 12641 PackageParser.Package installedPkg = mPackages.get(packageName); 12642 // Package which currently owns the data which the new package will own if installed. 12643 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12644 // will be null whereas dataOwnerPkg will contain information about the package 12645 // which was uninstalled while keeping its data. 12646 PackageParser.Package dataOwnerPkg = installedPkg; 12647 if (dataOwnerPkg == null) { 12648 PackageSetting ps = mSettings.mPackages.get(packageName); 12649 if (ps != null) { 12650 dataOwnerPkg = ps.pkg; 12651 } 12652 } 12653 12654 if (dataOwnerPkg != null) { 12655 // If installed, the package will get access to data left on the device by its 12656 // predecessor. As a security measure, this is permited only if this is not a 12657 // version downgrade or if the predecessor package is marked as debuggable and 12658 // a downgrade is explicitly requested. 12659 // 12660 // On debuggable platform builds, downgrades are permitted even for 12661 // non-debuggable packages to make testing easier. Debuggable platform builds do 12662 // not offer security guarantees and thus it's OK to disable some security 12663 // mechanisms to make debugging/testing easier on those builds. However, even on 12664 // debuggable builds downgrades of packages are permitted only if requested via 12665 // installFlags. This is because we aim to keep the behavior of debuggable 12666 // platform builds as close as possible to the behavior of non-debuggable 12667 // platform builds. 12668 final boolean downgradeRequested = 12669 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12670 final boolean packageDebuggable = 12671 (dataOwnerPkg.applicationInfo.flags 12672 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12673 final boolean downgradePermitted = 12674 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12675 if (!downgradePermitted) { 12676 try { 12677 checkDowngrade(dataOwnerPkg, pkgLite); 12678 } catch (PackageManagerException e) { 12679 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12680 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12681 } 12682 } 12683 } 12684 12685 if (installedPkg != null) { 12686 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12687 // Check for updated system application. 12688 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12689 if (onSd) { 12690 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12691 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12692 } 12693 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12694 } else { 12695 if (onSd) { 12696 // Install flag overrides everything. 12697 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12698 } 12699 // If current upgrade specifies particular preference 12700 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12701 // Application explicitly specified internal. 12702 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12703 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12704 // App explictly prefers external. Let policy decide 12705 } else { 12706 // Prefer previous location 12707 if (isExternal(installedPkg)) { 12708 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12709 } 12710 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12711 } 12712 } 12713 } else { 12714 // Invalid install. Return error code 12715 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12716 } 12717 } 12718 } 12719 // All the special cases have been taken care of. 12720 // Return result based on recommended install location. 12721 if (onSd) { 12722 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12723 } 12724 return pkgLite.recommendedInstallLocation; 12725 } 12726 12727 /* 12728 * Invoke remote method to get package information and install 12729 * location values. Override install location based on default 12730 * policy if needed and then create install arguments based 12731 * on the install location. 12732 */ 12733 public void handleStartCopy() throws RemoteException { 12734 int ret = PackageManager.INSTALL_SUCCEEDED; 12735 12736 // If we're already staged, we've firmly committed to an install location 12737 if (origin.staged) { 12738 if (origin.file != null) { 12739 installFlags |= PackageManager.INSTALL_INTERNAL; 12740 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12741 } else if (origin.cid != null) { 12742 installFlags |= PackageManager.INSTALL_EXTERNAL; 12743 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12744 } else { 12745 throw new IllegalStateException("Invalid stage location"); 12746 } 12747 } 12748 12749 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12750 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12751 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12752 PackageInfoLite pkgLite = null; 12753 12754 if (onInt && onSd) { 12755 // Check if both bits are set. 12756 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12757 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12758 } else if (onSd && ephemeral) { 12759 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12760 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12761 } else { 12762 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12763 packageAbiOverride); 12764 12765 if (DEBUG_EPHEMERAL && ephemeral) { 12766 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12767 } 12768 12769 /* 12770 * If we have too little free space, try to free cache 12771 * before giving up. 12772 */ 12773 if (!origin.staged && pkgLite.recommendedInstallLocation 12774 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12775 // TODO: focus freeing disk space on the target device 12776 final StorageManager storage = StorageManager.from(mContext); 12777 final long lowThreshold = storage.getStorageLowBytes( 12778 Environment.getDataDirectory()); 12779 12780 final long sizeBytes = mContainerService.calculateInstalledSize( 12781 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12782 12783 try { 12784 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12785 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12786 installFlags, packageAbiOverride); 12787 } catch (InstallerException e) { 12788 Slog.w(TAG, "Failed to free cache", e); 12789 } 12790 12791 /* 12792 * The cache free must have deleted the file we 12793 * downloaded to install. 12794 * 12795 * TODO: fix the "freeCache" call to not delete 12796 * the file we care about. 12797 */ 12798 if (pkgLite.recommendedInstallLocation 12799 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12800 pkgLite.recommendedInstallLocation 12801 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12802 } 12803 } 12804 } 12805 12806 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12807 int loc = pkgLite.recommendedInstallLocation; 12808 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12809 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12810 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12811 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12812 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12813 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12814 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12815 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12816 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12817 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12818 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12819 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12820 } else { 12821 // Override with defaults if needed. 12822 loc = installLocationPolicy(pkgLite); 12823 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12824 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12825 } else if (!onSd && !onInt) { 12826 // Override install location with flags 12827 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12828 // Set the flag to install on external media. 12829 installFlags |= PackageManager.INSTALL_EXTERNAL; 12830 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12831 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12832 if (DEBUG_EPHEMERAL) { 12833 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12834 } 12835 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12836 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12837 |PackageManager.INSTALL_INTERNAL); 12838 } else { 12839 // Make sure the flag for installing on external 12840 // media is unset 12841 installFlags |= PackageManager.INSTALL_INTERNAL; 12842 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12843 } 12844 } 12845 } 12846 } 12847 12848 final InstallArgs args = createInstallArgs(this); 12849 mArgs = args; 12850 12851 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12852 // TODO: http://b/22976637 12853 // Apps installed for "all" users use the device owner to verify the app 12854 UserHandle verifierUser = getUser(); 12855 if (verifierUser == UserHandle.ALL) { 12856 verifierUser = UserHandle.SYSTEM; 12857 } 12858 12859 /* 12860 * Determine if we have any installed package verifiers. If we 12861 * do, then we'll defer to them to verify the packages. 12862 */ 12863 final int requiredUid = mRequiredVerifierPackage == null ? -1 12864 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12865 verifierUser.getIdentifier()); 12866 if (!origin.existing && requiredUid != -1 12867 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12868 final Intent verification = new Intent( 12869 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12870 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12871 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12872 PACKAGE_MIME_TYPE); 12873 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12874 12875 // Query all live verifiers based on current user state 12876 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12877 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12878 12879 if (DEBUG_VERIFY) { 12880 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12881 + verification.toString() + " with " + pkgLite.verifiers.length 12882 + " optional verifiers"); 12883 } 12884 12885 final int verificationId = mPendingVerificationToken++; 12886 12887 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12888 12889 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12890 installerPackageName); 12891 12892 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12893 installFlags); 12894 12895 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12896 pkgLite.packageName); 12897 12898 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12899 pkgLite.versionCode); 12900 12901 if (verificationInfo != null) { 12902 if (verificationInfo.originatingUri != null) { 12903 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12904 verificationInfo.originatingUri); 12905 } 12906 if (verificationInfo.referrer != null) { 12907 verification.putExtra(Intent.EXTRA_REFERRER, 12908 verificationInfo.referrer); 12909 } 12910 if (verificationInfo.originatingUid >= 0) { 12911 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12912 verificationInfo.originatingUid); 12913 } 12914 if (verificationInfo.installerUid >= 0) { 12915 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12916 verificationInfo.installerUid); 12917 } 12918 } 12919 12920 final PackageVerificationState verificationState = new PackageVerificationState( 12921 requiredUid, args); 12922 12923 mPendingVerification.append(verificationId, verificationState); 12924 12925 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12926 receivers, verificationState); 12927 12928 /* 12929 * If any sufficient verifiers were listed in the package 12930 * manifest, attempt to ask them. 12931 */ 12932 if (sufficientVerifiers != null) { 12933 final int N = sufficientVerifiers.size(); 12934 if (N == 0) { 12935 Slog.i(TAG, "Additional verifiers required, but none installed."); 12936 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12937 } else { 12938 for (int i = 0; i < N; i++) { 12939 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12940 12941 final Intent sufficientIntent = new Intent(verification); 12942 sufficientIntent.setComponent(verifierComponent); 12943 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12944 } 12945 } 12946 } 12947 12948 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12949 mRequiredVerifierPackage, receivers); 12950 if (ret == PackageManager.INSTALL_SUCCEEDED 12951 && mRequiredVerifierPackage != null) { 12952 Trace.asyncTraceBegin( 12953 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12954 /* 12955 * Send the intent to the required verification agent, 12956 * but only start the verification timeout after the 12957 * target BroadcastReceivers have run. 12958 */ 12959 verification.setComponent(requiredVerifierComponent); 12960 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12961 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12962 new BroadcastReceiver() { 12963 @Override 12964 public void onReceive(Context context, Intent intent) { 12965 final Message msg = mHandler 12966 .obtainMessage(CHECK_PENDING_VERIFICATION); 12967 msg.arg1 = verificationId; 12968 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12969 } 12970 }, null, 0, null, null); 12971 12972 /* 12973 * We don't want the copy to proceed until verification 12974 * succeeds, so null out this field. 12975 */ 12976 mArgs = null; 12977 } 12978 } else { 12979 /* 12980 * No package verification is enabled, so immediately start 12981 * the remote call to initiate copy using temporary file. 12982 */ 12983 ret = args.copyApk(mContainerService, true); 12984 } 12985 } 12986 12987 mRet = ret; 12988 } 12989 12990 @Override 12991 void handleReturnCode() { 12992 // If mArgs is null, then MCS couldn't be reached. When it 12993 // reconnects, it will try again to install. At that point, this 12994 // will succeed. 12995 if (mArgs != null) { 12996 processPendingInstall(mArgs, mRet); 12997 } 12998 } 12999 13000 @Override 13001 void handleServiceError() { 13002 mArgs = createInstallArgs(this); 13003 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13004 } 13005 13006 public boolean isForwardLocked() { 13007 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13008 } 13009 } 13010 13011 /** 13012 * Used during creation of InstallArgs 13013 * 13014 * @param installFlags package installation flags 13015 * @return true if should be installed on external storage 13016 */ 13017 private static boolean installOnExternalAsec(int installFlags) { 13018 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13019 return false; 13020 } 13021 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13022 return true; 13023 } 13024 return false; 13025 } 13026 13027 /** 13028 * Used during creation of InstallArgs 13029 * 13030 * @param installFlags package installation flags 13031 * @return true if should be installed as forward locked 13032 */ 13033 private static boolean installForwardLocked(int installFlags) { 13034 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13035 } 13036 13037 private InstallArgs createInstallArgs(InstallParams params) { 13038 if (params.move != null) { 13039 return new MoveInstallArgs(params); 13040 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13041 return new AsecInstallArgs(params); 13042 } else { 13043 return new FileInstallArgs(params); 13044 } 13045 } 13046 13047 /** 13048 * Create args that describe an existing installed package. Typically used 13049 * when cleaning up old installs, or used as a move source. 13050 */ 13051 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13052 String resourcePath, String[] instructionSets) { 13053 final boolean isInAsec; 13054 if (installOnExternalAsec(installFlags)) { 13055 /* Apps on SD card are always in ASEC containers. */ 13056 isInAsec = true; 13057 } else if (installForwardLocked(installFlags) 13058 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13059 /* 13060 * Forward-locked apps are only in ASEC containers if they're the 13061 * new style 13062 */ 13063 isInAsec = true; 13064 } else { 13065 isInAsec = false; 13066 } 13067 13068 if (isInAsec) { 13069 return new AsecInstallArgs(codePath, instructionSets, 13070 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13071 } else { 13072 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13073 } 13074 } 13075 13076 static abstract class InstallArgs { 13077 /** @see InstallParams#origin */ 13078 final OriginInfo origin; 13079 /** @see InstallParams#move */ 13080 final MoveInfo move; 13081 13082 final IPackageInstallObserver2 observer; 13083 // Always refers to PackageManager flags only 13084 final int installFlags; 13085 final String installerPackageName; 13086 final String volumeUuid; 13087 final UserHandle user; 13088 final String abiOverride; 13089 final String[] installGrantPermissions; 13090 /** If non-null, drop an async trace when the install completes */ 13091 final String traceMethod; 13092 final int traceCookie; 13093 final Certificate[][] certificates; 13094 13095 // The list of instruction sets supported by this app. This is currently 13096 // only used during the rmdex() phase to clean up resources. We can get rid of this 13097 // if we move dex files under the common app path. 13098 /* nullable */ String[] instructionSets; 13099 13100 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13101 int installFlags, String installerPackageName, String volumeUuid, 13102 UserHandle user, String[] instructionSets, 13103 String abiOverride, String[] installGrantPermissions, 13104 String traceMethod, int traceCookie, Certificate[][] certificates) { 13105 this.origin = origin; 13106 this.move = move; 13107 this.installFlags = installFlags; 13108 this.observer = observer; 13109 this.installerPackageName = installerPackageName; 13110 this.volumeUuid = volumeUuid; 13111 this.user = user; 13112 this.instructionSets = instructionSets; 13113 this.abiOverride = abiOverride; 13114 this.installGrantPermissions = installGrantPermissions; 13115 this.traceMethod = traceMethod; 13116 this.traceCookie = traceCookie; 13117 this.certificates = certificates; 13118 } 13119 13120 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13121 abstract int doPreInstall(int status); 13122 13123 /** 13124 * Rename package into final resting place. All paths on the given 13125 * scanned package should be updated to reflect the rename. 13126 */ 13127 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13128 abstract int doPostInstall(int status, int uid); 13129 13130 /** @see PackageSettingBase#codePathString */ 13131 abstract String getCodePath(); 13132 /** @see PackageSettingBase#resourcePathString */ 13133 abstract String getResourcePath(); 13134 13135 // Need installer lock especially for dex file removal. 13136 abstract void cleanUpResourcesLI(); 13137 abstract boolean doPostDeleteLI(boolean delete); 13138 13139 /** 13140 * Called before the source arguments are copied. This is used mostly 13141 * for MoveParams when it needs to read the source file to put it in the 13142 * destination. 13143 */ 13144 int doPreCopy() { 13145 return PackageManager.INSTALL_SUCCEEDED; 13146 } 13147 13148 /** 13149 * Called after the source arguments are copied. This is used mostly for 13150 * MoveParams when it needs to read the source file to put it in the 13151 * destination. 13152 */ 13153 int doPostCopy(int uid) { 13154 return PackageManager.INSTALL_SUCCEEDED; 13155 } 13156 13157 protected boolean isFwdLocked() { 13158 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13159 } 13160 13161 protected boolean isExternalAsec() { 13162 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13163 } 13164 13165 protected boolean isEphemeral() { 13166 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13167 } 13168 13169 UserHandle getUser() { 13170 return user; 13171 } 13172 } 13173 13174 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13175 if (!allCodePaths.isEmpty()) { 13176 if (instructionSets == null) { 13177 throw new IllegalStateException("instructionSet == null"); 13178 } 13179 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13180 for (String codePath : allCodePaths) { 13181 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13182 try { 13183 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13184 } catch (InstallerException ignored) { 13185 } 13186 } 13187 } 13188 } 13189 } 13190 13191 /** 13192 * Logic to handle installation of non-ASEC applications, including copying 13193 * and renaming logic. 13194 */ 13195 class FileInstallArgs extends InstallArgs { 13196 private File codeFile; 13197 private File resourceFile; 13198 13199 // Example topology: 13200 // /data/app/com.example/base.apk 13201 // /data/app/com.example/split_foo.apk 13202 // /data/app/com.example/lib/arm/libfoo.so 13203 // /data/app/com.example/lib/arm64/libfoo.so 13204 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13205 13206 /** New install */ 13207 FileInstallArgs(InstallParams params) { 13208 super(params.origin, params.move, params.observer, params.installFlags, 13209 params.installerPackageName, params.volumeUuid, 13210 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13211 params.grantedRuntimePermissions, 13212 params.traceMethod, params.traceCookie, params.certificates); 13213 if (isFwdLocked()) { 13214 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13215 } 13216 } 13217 13218 /** Existing install */ 13219 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13220 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13221 null, null, null, 0, null /*certificates*/); 13222 this.codeFile = (codePath != null) ? new File(codePath) : null; 13223 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13224 } 13225 13226 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13228 try { 13229 return doCopyApk(imcs, temp); 13230 } finally { 13231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13232 } 13233 } 13234 13235 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13236 if (origin.staged) { 13237 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13238 codeFile = origin.file; 13239 resourceFile = origin.file; 13240 return PackageManager.INSTALL_SUCCEEDED; 13241 } 13242 13243 try { 13244 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13245 final File tempDir = 13246 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13247 codeFile = tempDir; 13248 resourceFile = tempDir; 13249 } catch (IOException e) { 13250 Slog.w(TAG, "Failed to create copy file: " + e); 13251 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13252 } 13253 13254 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13255 @Override 13256 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13257 if (!FileUtils.isValidExtFilename(name)) { 13258 throw new IllegalArgumentException("Invalid filename: " + name); 13259 } 13260 try { 13261 final File file = new File(codeFile, name); 13262 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13263 O_RDWR | O_CREAT, 0644); 13264 Os.chmod(file.getAbsolutePath(), 0644); 13265 return new ParcelFileDescriptor(fd); 13266 } catch (ErrnoException e) { 13267 throw new RemoteException("Failed to open: " + e.getMessage()); 13268 } 13269 } 13270 }; 13271 13272 int ret = PackageManager.INSTALL_SUCCEEDED; 13273 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13274 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13275 Slog.e(TAG, "Failed to copy package"); 13276 return ret; 13277 } 13278 13279 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13280 NativeLibraryHelper.Handle handle = null; 13281 try { 13282 handle = NativeLibraryHelper.Handle.create(codeFile); 13283 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13284 abiOverride); 13285 } catch (IOException e) { 13286 Slog.e(TAG, "Copying native libraries failed", e); 13287 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13288 } finally { 13289 IoUtils.closeQuietly(handle); 13290 } 13291 13292 return ret; 13293 } 13294 13295 int doPreInstall(int status) { 13296 if (status != PackageManager.INSTALL_SUCCEEDED) { 13297 cleanUp(); 13298 } 13299 return status; 13300 } 13301 13302 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13303 if (status != PackageManager.INSTALL_SUCCEEDED) { 13304 cleanUp(); 13305 return false; 13306 } 13307 13308 final File targetDir = codeFile.getParentFile(); 13309 final File beforeCodeFile = codeFile; 13310 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13311 13312 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13313 try { 13314 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13315 } catch (ErrnoException e) { 13316 Slog.w(TAG, "Failed to rename", e); 13317 return false; 13318 } 13319 13320 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13321 Slog.w(TAG, "Failed to restorecon"); 13322 return false; 13323 } 13324 13325 // Reflect the rename internally 13326 codeFile = afterCodeFile; 13327 resourceFile = afterCodeFile; 13328 13329 // Reflect the rename in scanned details 13330 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13331 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13332 afterCodeFile, pkg.baseCodePath)); 13333 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13334 afterCodeFile, pkg.splitCodePaths)); 13335 13336 // Reflect the rename in app info 13337 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13338 pkg.setApplicationInfoCodePath(pkg.codePath); 13339 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13340 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13341 pkg.setApplicationInfoResourcePath(pkg.codePath); 13342 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13343 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13344 13345 return true; 13346 } 13347 13348 int doPostInstall(int status, int uid) { 13349 if (status != PackageManager.INSTALL_SUCCEEDED) { 13350 cleanUp(); 13351 } 13352 return status; 13353 } 13354 13355 @Override 13356 String getCodePath() { 13357 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13358 } 13359 13360 @Override 13361 String getResourcePath() { 13362 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13363 } 13364 13365 private boolean cleanUp() { 13366 if (codeFile == null || !codeFile.exists()) { 13367 return false; 13368 } 13369 13370 removeCodePathLI(codeFile); 13371 13372 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13373 resourceFile.delete(); 13374 } 13375 13376 return true; 13377 } 13378 13379 void cleanUpResourcesLI() { 13380 // Try enumerating all code paths before deleting 13381 List<String> allCodePaths = Collections.EMPTY_LIST; 13382 if (codeFile != null && codeFile.exists()) { 13383 try { 13384 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13385 allCodePaths = pkg.getAllCodePaths(); 13386 } catch (PackageParserException e) { 13387 // Ignored; we tried our best 13388 } 13389 } 13390 13391 cleanUp(); 13392 removeDexFiles(allCodePaths, instructionSets); 13393 } 13394 13395 boolean doPostDeleteLI(boolean delete) { 13396 // XXX err, shouldn't we respect the delete flag? 13397 cleanUpResourcesLI(); 13398 return true; 13399 } 13400 } 13401 13402 private boolean isAsecExternal(String cid) { 13403 final String asecPath = PackageHelper.getSdFilesystem(cid); 13404 return !asecPath.startsWith(mAsecInternalPath); 13405 } 13406 13407 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13408 PackageManagerException { 13409 if (copyRet < 0) { 13410 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13411 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13412 throw new PackageManagerException(copyRet, message); 13413 } 13414 } 13415 } 13416 13417 /** 13418 * Extract the MountService "container ID" from the full code path of an 13419 * .apk. 13420 */ 13421 static String cidFromCodePath(String fullCodePath) { 13422 int eidx = fullCodePath.lastIndexOf("/"); 13423 String subStr1 = fullCodePath.substring(0, eidx); 13424 int sidx = subStr1.lastIndexOf("/"); 13425 return subStr1.substring(sidx+1, eidx); 13426 } 13427 13428 /** 13429 * Logic to handle installation of ASEC applications, including copying and 13430 * renaming logic. 13431 */ 13432 class AsecInstallArgs extends InstallArgs { 13433 static final String RES_FILE_NAME = "pkg.apk"; 13434 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13435 13436 String cid; 13437 String packagePath; 13438 String resourcePath; 13439 13440 /** New install */ 13441 AsecInstallArgs(InstallParams params) { 13442 super(params.origin, params.move, params.observer, params.installFlags, 13443 params.installerPackageName, params.volumeUuid, 13444 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13445 params.grantedRuntimePermissions, 13446 params.traceMethod, params.traceCookie, params.certificates); 13447 } 13448 13449 /** Existing install */ 13450 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13451 boolean isExternal, boolean isForwardLocked) { 13452 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13453 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13454 instructionSets, null, null, null, 0, null /*certificates*/); 13455 // Hackily pretend we're still looking at a full code path 13456 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13457 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13458 } 13459 13460 // Extract cid from fullCodePath 13461 int eidx = fullCodePath.lastIndexOf("/"); 13462 String subStr1 = fullCodePath.substring(0, eidx); 13463 int sidx = subStr1.lastIndexOf("/"); 13464 cid = subStr1.substring(sidx+1, eidx); 13465 setMountPath(subStr1); 13466 } 13467 13468 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13469 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13470 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13471 instructionSets, null, null, null, 0, null /*certificates*/); 13472 this.cid = cid; 13473 setMountPath(PackageHelper.getSdDir(cid)); 13474 } 13475 13476 void createCopyFile() { 13477 cid = mInstallerService.allocateExternalStageCidLegacy(); 13478 } 13479 13480 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13481 if (origin.staged && origin.cid != null) { 13482 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13483 cid = origin.cid; 13484 setMountPath(PackageHelper.getSdDir(cid)); 13485 return PackageManager.INSTALL_SUCCEEDED; 13486 } 13487 13488 if (temp) { 13489 createCopyFile(); 13490 } else { 13491 /* 13492 * Pre-emptively destroy the container since it's destroyed if 13493 * copying fails due to it existing anyway. 13494 */ 13495 PackageHelper.destroySdDir(cid); 13496 } 13497 13498 final String newMountPath = imcs.copyPackageToContainer( 13499 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13500 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13501 13502 if (newMountPath != null) { 13503 setMountPath(newMountPath); 13504 return PackageManager.INSTALL_SUCCEEDED; 13505 } else { 13506 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13507 } 13508 } 13509 13510 @Override 13511 String getCodePath() { 13512 return packagePath; 13513 } 13514 13515 @Override 13516 String getResourcePath() { 13517 return resourcePath; 13518 } 13519 13520 int doPreInstall(int status) { 13521 if (status != PackageManager.INSTALL_SUCCEEDED) { 13522 // Destroy container 13523 PackageHelper.destroySdDir(cid); 13524 } else { 13525 boolean mounted = PackageHelper.isContainerMounted(cid); 13526 if (!mounted) { 13527 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13528 Process.SYSTEM_UID); 13529 if (newMountPath != null) { 13530 setMountPath(newMountPath); 13531 } else { 13532 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13533 } 13534 } 13535 } 13536 return status; 13537 } 13538 13539 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13540 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13541 String newMountPath = null; 13542 if (PackageHelper.isContainerMounted(cid)) { 13543 // Unmount the container 13544 if (!PackageHelper.unMountSdDir(cid)) { 13545 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13546 return false; 13547 } 13548 } 13549 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13550 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13551 " which might be stale. Will try to clean up."); 13552 // Clean up the stale container and proceed to recreate. 13553 if (!PackageHelper.destroySdDir(newCacheId)) { 13554 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13555 return false; 13556 } 13557 // Successfully cleaned up stale container. Try to rename again. 13558 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13559 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13560 + " inspite of cleaning it up."); 13561 return false; 13562 } 13563 } 13564 if (!PackageHelper.isContainerMounted(newCacheId)) { 13565 Slog.w(TAG, "Mounting container " + newCacheId); 13566 newMountPath = PackageHelper.mountSdDir(newCacheId, 13567 getEncryptKey(), Process.SYSTEM_UID); 13568 } else { 13569 newMountPath = PackageHelper.getSdDir(newCacheId); 13570 } 13571 if (newMountPath == null) { 13572 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13573 return false; 13574 } 13575 Log.i(TAG, "Succesfully renamed " + cid + 13576 " to " + newCacheId + 13577 " at new path: " + newMountPath); 13578 cid = newCacheId; 13579 13580 final File beforeCodeFile = new File(packagePath); 13581 setMountPath(newMountPath); 13582 final File afterCodeFile = new File(packagePath); 13583 13584 // Reflect the rename in scanned details 13585 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13586 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13587 afterCodeFile, pkg.baseCodePath)); 13588 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13589 afterCodeFile, pkg.splitCodePaths)); 13590 13591 // Reflect the rename in app info 13592 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13593 pkg.setApplicationInfoCodePath(pkg.codePath); 13594 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13595 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13596 pkg.setApplicationInfoResourcePath(pkg.codePath); 13597 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13598 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13599 13600 return true; 13601 } 13602 13603 private void setMountPath(String mountPath) { 13604 final File mountFile = new File(mountPath); 13605 13606 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13607 if (monolithicFile.exists()) { 13608 packagePath = monolithicFile.getAbsolutePath(); 13609 if (isFwdLocked()) { 13610 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13611 } else { 13612 resourcePath = packagePath; 13613 } 13614 } else { 13615 packagePath = mountFile.getAbsolutePath(); 13616 resourcePath = packagePath; 13617 } 13618 } 13619 13620 int doPostInstall(int status, int uid) { 13621 if (status != PackageManager.INSTALL_SUCCEEDED) { 13622 cleanUp(); 13623 } else { 13624 final int groupOwner; 13625 final String protectedFile; 13626 if (isFwdLocked()) { 13627 groupOwner = UserHandle.getSharedAppGid(uid); 13628 protectedFile = RES_FILE_NAME; 13629 } else { 13630 groupOwner = -1; 13631 protectedFile = null; 13632 } 13633 13634 if (uid < Process.FIRST_APPLICATION_UID 13635 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13636 Slog.e(TAG, "Failed to finalize " + cid); 13637 PackageHelper.destroySdDir(cid); 13638 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13639 } 13640 13641 boolean mounted = PackageHelper.isContainerMounted(cid); 13642 if (!mounted) { 13643 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13644 } 13645 } 13646 return status; 13647 } 13648 13649 private void cleanUp() { 13650 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13651 13652 // Destroy secure container 13653 PackageHelper.destroySdDir(cid); 13654 } 13655 13656 private List<String> getAllCodePaths() { 13657 final File codeFile = new File(getCodePath()); 13658 if (codeFile != null && codeFile.exists()) { 13659 try { 13660 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13661 return pkg.getAllCodePaths(); 13662 } catch (PackageParserException e) { 13663 // Ignored; we tried our best 13664 } 13665 } 13666 return Collections.EMPTY_LIST; 13667 } 13668 13669 void cleanUpResourcesLI() { 13670 // Enumerate all code paths before deleting 13671 cleanUpResourcesLI(getAllCodePaths()); 13672 } 13673 13674 private void cleanUpResourcesLI(List<String> allCodePaths) { 13675 cleanUp(); 13676 removeDexFiles(allCodePaths, instructionSets); 13677 } 13678 13679 String getPackageName() { 13680 return getAsecPackageName(cid); 13681 } 13682 13683 boolean doPostDeleteLI(boolean delete) { 13684 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13685 final List<String> allCodePaths = getAllCodePaths(); 13686 boolean mounted = PackageHelper.isContainerMounted(cid); 13687 if (mounted) { 13688 // Unmount first 13689 if (PackageHelper.unMountSdDir(cid)) { 13690 mounted = false; 13691 } 13692 } 13693 if (!mounted && delete) { 13694 cleanUpResourcesLI(allCodePaths); 13695 } 13696 return !mounted; 13697 } 13698 13699 @Override 13700 int doPreCopy() { 13701 if (isFwdLocked()) { 13702 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13703 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13704 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13705 } 13706 } 13707 13708 return PackageManager.INSTALL_SUCCEEDED; 13709 } 13710 13711 @Override 13712 int doPostCopy(int uid) { 13713 if (isFwdLocked()) { 13714 if (uid < Process.FIRST_APPLICATION_UID 13715 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13716 RES_FILE_NAME)) { 13717 Slog.e(TAG, "Failed to finalize " + cid); 13718 PackageHelper.destroySdDir(cid); 13719 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13720 } 13721 } 13722 13723 return PackageManager.INSTALL_SUCCEEDED; 13724 } 13725 } 13726 13727 /** 13728 * Logic to handle movement of existing installed applications. 13729 */ 13730 class MoveInstallArgs extends InstallArgs { 13731 private File codeFile; 13732 private File resourceFile; 13733 13734 /** New install */ 13735 MoveInstallArgs(InstallParams params) { 13736 super(params.origin, params.move, params.observer, params.installFlags, 13737 params.installerPackageName, params.volumeUuid, 13738 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13739 params.grantedRuntimePermissions, 13740 params.traceMethod, params.traceCookie, params.certificates); 13741 } 13742 13743 int copyApk(IMediaContainerService imcs, boolean temp) { 13744 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13745 + move.fromUuid + " to " + move.toUuid); 13746 synchronized (mInstaller) { 13747 try { 13748 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13749 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13750 } catch (InstallerException e) { 13751 Slog.w(TAG, "Failed to move app", e); 13752 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13753 } 13754 } 13755 13756 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13757 resourceFile = codeFile; 13758 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13759 13760 return PackageManager.INSTALL_SUCCEEDED; 13761 } 13762 13763 int doPreInstall(int status) { 13764 if (status != PackageManager.INSTALL_SUCCEEDED) { 13765 cleanUp(move.toUuid); 13766 } 13767 return status; 13768 } 13769 13770 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13771 if (status != PackageManager.INSTALL_SUCCEEDED) { 13772 cleanUp(move.toUuid); 13773 return false; 13774 } 13775 13776 // Reflect the move in app info 13777 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13778 pkg.setApplicationInfoCodePath(pkg.codePath); 13779 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13780 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13781 pkg.setApplicationInfoResourcePath(pkg.codePath); 13782 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13783 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13784 13785 return true; 13786 } 13787 13788 int doPostInstall(int status, int uid) { 13789 if (status == PackageManager.INSTALL_SUCCEEDED) { 13790 cleanUp(move.fromUuid); 13791 } else { 13792 cleanUp(move.toUuid); 13793 } 13794 return status; 13795 } 13796 13797 @Override 13798 String getCodePath() { 13799 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13800 } 13801 13802 @Override 13803 String getResourcePath() { 13804 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13805 } 13806 13807 private boolean cleanUp(String volumeUuid) { 13808 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13809 move.dataAppName); 13810 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13811 final int[] userIds = sUserManager.getUserIds(); 13812 synchronized (mInstallLock) { 13813 // Clean up both app data and code 13814 // All package moves are frozen until finished 13815 for (int userId : userIds) { 13816 try { 13817 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13818 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13819 } catch (InstallerException e) { 13820 Slog.w(TAG, String.valueOf(e)); 13821 } 13822 } 13823 removeCodePathLI(codeFile); 13824 } 13825 return true; 13826 } 13827 13828 void cleanUpResourcesLI() { 13829 throw new UnsupportedOperationException(); 13830 } 13831 13832 boolean doPostDeleteLI(boolean delete) { 13833 throw new UnsupportedOperationException(); 13834 } 13835 } 13836 13837 static String getAsecPackageName(String packageCid) { 13838 int idx = packageCid.lastIndexOf("-"); 13839 if (idx == -1) { 13840 return packageCid; 13841 } 13842 return packageCid.substring(0, idx); 13843 } 13844 13845 // Utility method used to create code paths based on package name and available index. 13846 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13847 String idxStr = ""; 13848 int idx = 1; 13849 // Fall back to default value of idx=1 if prefix is not 13850 // part of oldCodePath 13851 if (oldCodePath != null) { 13852 String subStr = oldCodePath; 13853 // Drop the suffix right away 13854 if (suffix != null && subStr.endsWith(suffix)) { 13855 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13856 } 13857 // If oldCodePath already contains prefix find out the 13858 // ending index to either increment or decrement. 13859 int sidx = subStr.lastIndexOf(prefix); 13860 if (sidx != -1) { 13861 subStr = subStr.substring(sidx + prefix.length()); 13862 if (subStr != null) { 13863 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13864 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13865 } 13866 try { 13867 idx = Integer.parseInt(subStr); 13868 if (idx <= 1) { 13869 idx++; 13870 } else { 13871 idx--; 13872 } 13873 } catch(NumberFormatException e) { 13874 } 13875 } 13876 } 13877 } 13878 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13879 return prefix + idxStr; 13880 } 13881 13882 private File getNextCodePath(File targetDir, String packageName) { 13883 int suffix = 1; 13884 File result; 13885 do { 13886 result = new File(targetDir, packageName + "-" + suffix); 13887 suffix++; 13888 } while (result.exists()); 13889 return result; 13890 } 13891 13892 // Utility method that returns the relative package path with respect 13893 // to the installation directory. Like say for /data/data/com.test-1.apk 13894 // string com.test-1 is returned. 13895 static String deriveCodePathName(String codePath) { 13896 if (codePath == null) { 13897 return null; 13898 } 13899 final File codeFile = new File(codePath); 13900 final String name = codeFile.getName(); 13901 if (codeFile.isDirectory()) { 13902 return name; 13903 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13904 final int lastDot = name.lastIndexOf('.'); 13905 return name.substring(0, lastDot); 13906 } else { 13907 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13908 return null; 13909 } 13910 } 13911 13912 static class PackageInstalledInfo { 13913 String name; 13914 int uid; 13915 // The set of users that originally had this package installed. 13916 int[] origUsers; 13917 // The set of users that now have this package installed. 13918 int[] newUsers; 13919 PackageParser.Package pkg; 13920 int returnCode; 13921 String returnMsg; 13922 PackageRemovedInfo removedInfo; 13923 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13924 13925 public void setError(int code, String msg) { 13926 setReturnCode(code); 13927 setReturnMessage(msg); 13928 Slog.w(TAG, msg); 13929 } 13930 13931 public void setError(String msg, PackageParserException e) { 13932 setReturnCode(e.error); 13933 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13934 Slog.w(TAG, msg, e); 13935 } 13936 13937 public void setError(String msg, PackageManagerException e) { 13938 returnCode = e.error; 13939 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13940 Slog.w(TAG, msg, e); 13941 } 13942 13943 public void setReturnCode(int returnCode) { 13944 this.returnCode = returnCode; 13945 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13946 for (int i = 0; i < childCount; i++) { 13947 addedChildPackages.valueAt(i).returnCode = returnCode; 13948 } 13949 } 13950 13951 private void setReturnMessage(String returnMsg) { 13952 this.returnMsg = returnMsg; 13953 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13954 for (int i = 0; i < childCount; i++) { 13955 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13956 } 13957 } 13958 13959 // In some error cases we want to convey more info back to the observer 13960 String origPackage; 13961 String origPermission; 13962 } 13963 13964 /* 13965 * Install a non-existing package. 13966 */ 13967 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13968 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13969 PackageInstalledInfo res) { 13970 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13971 13972 // Remember this for later, in case we need to rollback this install 13973 String pkgName = pkg.packageName; 13974 13975 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13976 13977 synchronized(mPackages) { 13978 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13979 // A package with the same name is already installed, though 13980 // it has been renamed to an older name. The package we 13981 // are trying to install should be installed as an update to 13982 // the existing one, but that has not been requested, so bail. 13983 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13984 + " without first uninstalling package running as " 13985 + mSettings.mRenamedPackages.get(pkgName)); 13986 return; 13987 } 13988 if (mPackages.containsKey(pkgName)) { 13989 // Don't allow installation over an existing package with the same name. 13990 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13991 + " without first uninstalling."); 13992 return; 13993 } 13994 } 13995 13996 try { 13997 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13998 System.currentTimeMillis(), user); 13999 14000 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14001 14002 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14003 prepareAppDataAfterInstallLIF(newPackage); 14004 14005 } else { 14006 // Remove package from internal structures, but keep around any 14007 // data that might have already existed 14008 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14009 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14010 } 14011 } catch (PackageManagerException e) { 14012 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14013 } 14014 14015 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14016 } 14017 14018 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14019 // Can't rotate keys during boot or if sharedUser. 14020 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14021 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14022 return false; 14023 } 14024 // app is using upgradeKeySets; make sure all are valid 14025 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14026 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14027 for (int i = 0; i < upgradeKeySets.length; i++) { 14028 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14029 Slog.wtf(TAG, "Package " 14030 + (oldPs.name != null ? oldPs.name : "<null>") 14031 + " contains upgrade-key-set reference to unknown key-set: " 14032 + upgradeKeySets[i] 14033 + " reverting to signatures check."); 14034 return false; 14035 } 14036 } 14037 return true; 14038 } 14039 14040 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14041 // Upgrade keysets are being used. Determine if new package has a superset of the 14042 // required keys. 14043 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14044 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14045 for (int i = 0; i < upgradeKeySets.length; i++) { 14046 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14047 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14048 return true; 14049 } 14050 } 14051 return false; 14052 } 14053 14054 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14055 try (DigestInputStream digestStream = 14056 new DigestInputStream(new FileInputStream(file), digest)) { 14057 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14058 } 14059 } 14060 14061 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14062 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14063 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14064 14065 final PackageParser.Package oldPackage; 14066 final String pkgName = pkg.packageName; 14067 final int[] allUsers; 14068 final int[] installedUsers; 14069 14070 synchronized(mPackages) { 14071 oldPackage = mPackages.get(pkgName); 14072 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14073 14074 // don't allow upgrade to target a release SDK from a pre-release SDK 14075 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14076 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14077 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14078 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14079 if (oldTargetsPreRelease 14080 && !newTargetsPreRelease 14081 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14082 Slog.w(TAG, "Can't install package targeting released sdk"); 14083 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14084 return; 14085 } 14086 14087 // don't allow an upgrade from full to ephemeral 14088 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14089 if (isEphemeral && !oldIsEphemeral) { 14090 // can't downgrade from full to ephemeral 14091 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14092 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14093 return; 14094 } 14095 14096 // verify signatures are valid 14097 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14098 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14099 if (!checkUpgradeKeySetLP(ps, pkg)) { 14100 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14101 "New package not signed by keys specified by upgrade-keysets: " 14102 + pkgName); 14103 return; 14104 } 14105 } else { 14106 // default to original signature matching 14107 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14108 != PackageManager.SIGNATURE_MATCH) { 14109 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14110 "New package has a different signature: " + pkgName); 14111 return; 14112 } 14113 } 14114 14115 // don't allow a system upgrade unless the upgrade hash matches 14116 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14117 byte[] digestBytes = null; 14118 try { 14119 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14120 updateDigest(digest, new File(pkg.baseCodePath)); 14121 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14122 for (String path : pkg.splitCodePaths) { 14123 updateDigest(digest, new File(path)); 14124 } 14125 } 14126 digestBytes = digest.digest(); 14127 } catch (NoSuchAlgorithmException | IOException e) { 14128 res.setError(INSTALL_FAILED_INVALID_APK, 14129 "Could not compute hash: " + pkgName); 14130 return; 14131 } 14132 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14133 res.setError(INSTALL_FAILED_INVALID_APK, 14134 "New package fails restrict-update check: " + pkgName); 14135 return; 14136 } 14137 // retain upgrade restriction 14138 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14139 } 14140 14141 // Check for shared user id changes 14142 String invalidPackageName = 14143 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14144 if (invalidPackageName != null) { 14145 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14146 "Package " + invalidPackageName + " tried to change user " 14147 + oldPackage.mSharedUserId); 14148 return; 14149 } 14150 14151 // In case of rollback, remember per-user/profile install state 14152 allUsers = sUserManager.getUserIds(); 14153 installedUsers = ps.queryInstalledUsers(allUsers, true); 14154 } 14155 14156 // Update what is removed 14157 res.removedInfo = new PackageRemovedInfo(); 14158 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14159 res.removedInfo.removedPackage = oldPackage.packageName; 14160 res.removedInfo.isUpdate = true; 14161 res.removedInfo.origUsers = installedUsers; 14162 final int childCount = (oldPackage.childPackages != null) 14163 ? oldPackage.childPackages.size() : 0; 14164 for (int i = 0; i < childCount; i++) { 14165 boolean childPackageUpdated = false; 14166 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14167 if (res.addedChildPackages != null) { 14168 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14169 if (childRes != null) { 14170 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14171 childRes.removedInfo.removedPackage = childPkg.packageName; 14172 childRes.removedInfo.isUpdate = true; 14173 childPackageUpdated = true; 14174 } 14175 } 14176 if (!childPackageUpdated) { 14177 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14178 childRemovedRes.removedPackage = childPkg.packageName; 14179 childRemovedRes.isUpdate = false; 14180 childRemovedRes.dataRemoved = true; 14181 synchronized (mPackages) { 14182 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14183 if (childPs != null) { 14184 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14185 } 14186 } 14187 if (res.removedInfo.removedChildPackages == null) { 14188 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14189 } 14190 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14191 } 14192 } 14193 14194 boolean sysPkg = (isSystemApp(oldPackage)); 14195 if (sysPkg) { 14196 // Set the system/privileged flags as needed 14197 final boolean privileged = 14198 (oldPackage.applicationInfo.privateFlags 14199 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14200 final int systemPolicyFlags = policyFlags 14201 | PackageParser.PARSE_IS_SYSTEM 14202 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14203 14204 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14205 user, allUsers, installerPackageName, res); 14206 } else { 14207 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14208 user, allUsers, installerPackageName, res); 14209 } 14210 } 14211 14212 public List<String> getPreviousCodePaths(String packageName) { 14213 final PackageSetting ps = mSettings.mPackages.get(packageName); 14214 final List<String> result = new ArrayList<String>(); 14215 if (ps != null && ps.oldCodePaths != null) { 14216 result.addAll(ps.oldCodePaths); 14217 } 14218 return result; 14219 } 14220 14221 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14222 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14223 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14224 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14225 + deletedPackage); 14226 14227 String pkgName = deletedPackage.packageName; 14228 boolean deletedPkg = true; 14229 boolean addedPkg = false; 14230 boolean updatedSettings = false; 14231 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14232 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14233 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14234 14235 final long origUpdateTime = (pkg.mExtras != null) 14236 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14237 14238 // First delete the existing package while retaining the data directory 14239 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14240 res.removedInfo, true, pkg)) { 14241 // If the existing package wasn't successfully deleted 14242 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14243 deletedPkg = false; 14244 } else { 14245 // Successfully deleted the old package; proceed with replace. 14246 14247 // If deleted package lived in a container, give users a chance to 14248 // relinquish resources before killing. 14249 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14250 if (DEBUG_INSTALL) { 14251 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14252 } 14253 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14254 final ArrayList<String> pkgList = new ArrayList<String>(1); 14255 pkgList.add(deletedPackage.applicationInfo.packageName); 14256 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14257 } 14258 14259 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14260 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14261 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14262 14263 try { 14264 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14265 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14266 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14267 14268 // Update the in-memory copy of the previous code paths. 14269 PackageSetting ps = mSettings.mPackages.get(pkgName); 14270 if (!killApp) { 14271 if (ps.oldCodePaths == null) { 14272 ps.oldCodePaths = new ArraySet<>(); 14273 } 14274 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14275 if (deletedPackage.splitCodePaths != null) { 14276 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14277 } 14278 } else { 14279 ps.oldCodePaths = null; 14280 } 14281 if (ps.childPackageNames != null) { 14282 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14283 final String childPkgName = ps.childPackageNames.get(i); 14284 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14285 childPs.oldCodePaths = ps.oldCodePaths; 14286 } 14287 } 14288 prepareAppDataAfterInstallLIF(newPackage); 14289 addedPkg = true; 14290 } catch (PackageManagerException e) { 14291 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14292 } 14293 } 14294 14295 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14296 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14297 14298 // Revert all internal state mutations and added folders for the failed install 14299 if (addedPkg) { 14300 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14301 res.removedInfo, true, null); 14302 } 14303 14304 // Restore the old package 14305 if (deletedPkg) { 14306 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14307 File restoreFile = new File(deletedPackage.codePath); 14308 // Parse old package 14309 boolean oldExternal = isExternal(deletedPackage); 14310 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14311 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14312 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14313 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14314 try { 14315 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14316 null); 14317 } catch (PackageManagerException e) { 14318 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14319 + e.getMessage()); 14320 return; 14321 } 14322 14323 synchronized (mPackages) { 14324 // Ensure the installer package name up to date 14325 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14326 14327 // Update permissions for restored package 14328 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14329 14330 mSettings.writeLPr(); 14331 } 14332 14333 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14334 } 14335 } else { 14336 synchronized (mPackages) { 14337 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14338 if (ps != null) { 14339 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14340 if (res.removedInfo.removedChildPackages != null) { 14341 final int childCount = res.removedInfo.removedChildPackages.size(); 14342 // Iterate in reverse as we may modify the collection 14343 for (int i = childCount - 1; i >= 0; i--) { 14344 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14345 if (res.addedChildPackages.containsKey(childPackageName)) { 14346 res.removedInfo.removedChildPackages.removeAt(i); 14347 } else { 14348 PackageRemovedInfo childInfo = res.removedInfo 14349 .removedChildPackages.valueAt(i); 14350 childInfo.removedForAllUsers = mPackages.get( 14351 childInfo.removedPackage) == null; 14352 } 14353 } 14354 } 14355 } 14356 } 14357 } 14358 } 14359 14360 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14361 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14362 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14363 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14364 + ", old=" + deletedPackage); 14365 14366 final boolean disabledSystem; 14367 14368 // Remove existing system package 14369 removePackageLI(deletedPackage, true); 14370 14371 synchronized (mPackages) { 14372 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14373 } 14374 if (!disabledSystem) { 14375 // We didn't need to disable the .apk as a current system package, 14376 // which means we are replacing another update that is already 14377 // installed. We need to make sure to delete the older one's .apk. 14378 res.removedInfo.args = createInstallArgsForExisting(0, 14379 deletedPackage.applicationInfo.getCodePath(), 14380 deletedPackage.applicationInfo.getResourcePath(), 14381 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14382 } else { 14383 res.removedInfo.args = null; 14384 } 14385 14386 // Successfully disabled the old package. Now proceed with re-installation 14387 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14388 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14389 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14390 14391 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14392 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14393 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14394 14395 PackageParser.Package newPackage = null; 14396 try { 14397 // Add the package to the internal data structures 14398 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14399 14400 // Set the update and install times 14401 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14402 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14403 System.currentTimeMillis()); 14404 14405 // Update the package dynamic state if succeeded 14406 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14407 // Now that the install succeeded make sure we remove data 14408 // directories for any child package the update removed. 14409 final int deletedChildCount = (deletedPackage.childPackages != null) 14410 ? deletedPackage.childPackages.size() : 0; 14411 final int newChildCount = (newPackage.childPackages != null) 14412 ? newPackage.childPackages.size() : 0; 14413 for (int i = 0; i < deletedChildCount; i++) { 14414 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14415 boolean childPackageDeleted = true; 14416 for (int j = 0; j < newChildCount; j++) { 14417 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14418 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14419 childPackageDeleted = false; 14420 break; 14421 } 14422 } 14423 if (childPackageDeleted) { 14424 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14425 deletedChildPkg.packageName); 14426 if (ps != null && res.removedInfo.removedChildPackages != null) { 14427 PackageRemovedInfo removedChildRes = res.removedInfo 14428 .removedChildPackages.get(deletedChildPkg.packageName); 14429 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14430 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14431 } 14432 } 14433 } 14434 14435 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14436 prepareAppDataAfterInstallLIF(newPackage); 14437 } 14438 } catch (PackageManagerException e) { 14439 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14440 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14441 } 14442 14443 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14444 // Re installation failed. Restore old information 14445 // Remove new pkg information 14446 if (newPackage != null) { 14447 removeInstalledPackageLI(newPackage, true); 14448 } 14449 // Add back the old system package 14450 try { 14451 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14452 } catch (PackageManagerException e) { 14453 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14454 } 14455 14456 synchronized (mPackages) { 14457 if (disabledSystem) { 14458 enableSystemPackageLPw(deletedPackage); 14459 } 14460 14461 // Ensure the installer package name up to date 14462 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14463 14464 // Update permissions for restored package 14465 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14466 14467 mSettings.writeLPr(); 14468 } 14469 14470 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14471 + " after failed upgrade"); 14472 } 14473 } 14474 14475 /** 14476 * Checks whether the parent or any of the child packages have a change shared 14477 * user. For a package to be a valid update the shred users of the parent and 14478 * the children should match. We may later support changing child shared users. 14479 * @param oldPkg The updated package. 14480 * @param newPkg The update package. 14481 * @return The shared user that change between the versions. 14482 */ 14483 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14484 PackageParser.Package newPkg) { 14485 // Check parent shared user 14486 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14487 return newPkg.packageName; 14488 } 14489 // Check child shared users 14490 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14491 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14492 for (int i = 0; i < newChildCount; i++) { 14493 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14494 // If this child was present, did it have the same shared user? 14495 for (int j = 0; j < oldChildCount; j++) { 14496 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14497 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14498 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14499 return newChildPkg.packageName; 14500 } 14501 } 14502 } 14503 return null; 14504 } 14505 14506 private void removeNativeBinariesLI(PackageSetting ps) { 14507 // Remove the lib path for the parent package 14508 if (ps != null) { 14509 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14510 // Remove the lib path for the child packages 14511 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14512 for (int i = 0; i < childCount; i++) { 14513 PackageSetting childPs = null; 14514 synchronized (mPackages) { 14515 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14516 } 14517 if (childPs != null) { 14518 NativeLibraryHelper.removeNativeBinariesLI(childPs 14519 .legacyNativeLibraryPathString); 14520 } 14521 } 14522 } 14523 } 14524 14525 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14526 // Enable the parent package 14527 mSettings.enableSystemPackageLPw(pkg.packageName); 14528 // Enable the child packages 14529 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14530 for (int i = 0; i < childCount; i++) { 14531 PackageParser.Package childPkg = pkg.childPackages.get(i); 14532 mSettings.enableSystemPackageLPw(childPkg.packageName); 14533 } 14534 } 14535 14536 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14537 PackageParser.Package newPkg) { 14538 // Disable the parent package (parent always replaced) 14539 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14540 // Disable the child packages 14541 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14542 for (int i = 0; i < childCount; i++) { 14543 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14544 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14545 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14546 } 14547 return disabled; 14548 } 14549 14550 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14551 String installerPackageName) { 14552 // Enable the parent package 14553 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14554 // Enable the child packages 14555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14556 for (int i = 0; i < childCount; i++) { 14557 PackageParser.Package childPkg = pkg.childPackages.get(i); 14558 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14559 } 14560 } 14561 14562 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14563 // Collect all used permissions in the UID 14564 ArraySet<String> usedPermissions = new ArraySet<>(); 14565 final int packageCount = su.packages.size(); 14566 for (int i = 0; i < packageCount; i++) { 14567 PackageSetting ps = su.packages.valueAt(i); 14568 if (ps.pkg == null) { 14569 continue; 14570 } 14571 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14572 for (int j = 0; j < requestedPermCount; j++) { 14573 String permission = ps.pkg.requestedPermissions.get(j); 14574 BasePermission bp = mSettings.mPermissions.get(permission); 14575 if (bp != null) { 14576 usedPermissions.add(permission); 14577 } 14578 } 14579 } 14580 14581 PermissionsState permissionsState = su.getPermissionsState(); 14582 // Prune install permissions 14583 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14584 final int installPermCount = installPermStates.size(); 14585 for (int i = installPermCount - 1; i >= 0; i--) { 14586 PermissionState permissionState = installPermStates.get(i); 14587 if (!usedPermissions.contains(permissionState.getName())) { 14588 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14589 if (bp != null) { 14590 permissionsState.revokeInstallPermission(bp); 14591 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14592 PackageManager.MASK_PERMISSION_FLAGS, 0); 14593 } 14594 } 14595 } 14596 14597 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14598 14599 // Prune runtime permissions 14600 for (int userId : allUserIds) { 14601 List<PermissionState> runtimePermStates = permissionsState 14602 .getRuntimePermissionStates(userId); 14603 final int runtimePermCount = runtimePermStates.size(); 14604 for (int i = runtimePermCount - 1; i >= 0; i--) { 14605 PermissionState permissionState = runtimePermStates.get(i); 14606 if (!usedPermissions.contains(permissionState.getName())) { 14607 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14608 if (bp != null) { 14609 permissionsState.revokeRuntimePermission(bp, userId); 14610 permissionsState.updatePermissionFlags(bp, userId, 14611 PackageManager.MASK_PERMISSION_FLAGS, 0); 14612 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14613 runtimePermissionChangedUserIds, userId); 14614 } 14615 } 14616 } 14617 } 14618 14619 return runtimePermissionChangedUserIds; 14620 } 14621 14622 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14623 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14624 // Update the parent package setting 14625 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14626 res, user); 14627 // Update the child packages setting 14628 final int childCount = (newPackage.childPackages != null) 14629 ? newPackage.childPackages.size() : 0; 14630 for (int i = 0; i < childCount; i++) { 14631 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14632 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14633 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14634 childRes.origUsers, childRes, user); 14635 } 14636 } 14637 14638 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14639 String installerPackageName, int[] allUsers, int[] installedForUsers, 14640 PackageInstalledInfo res, UserHandle user) { 14641 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14642 14643 String pkgName = newPackage.packageName; 14644 synchronized (mPackages) { 14645 //write settings. the installStatus will be incomplete at this stage. 14646 //note that the new package setting would have already been 14647 //added to mPackages. It hasn't been persisted yet. 14648 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14649 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14650 mSettings.writeLPr(); 14651 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14652 } 14653 14654 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14655 synchronized (mPackages) { 14656 updatePermissionsLPw(newPackage.packageName, newPackage, 14657 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14658 ? UPDATE_PERMISSIONS_ALL : 0)); 14659 // For system-bundled packages, we assume that installing an upgraded version 14660 // of the package implies that the user actually wants to run that new code, 14661 // so we enable the package. 14662 PackageSetting ps = mSettings.mPackages.get(pkgName); 14663 final int userId = user.getIdentifier(); 14664 if (ps != null) { 14665 if (isSystemApp(newPackage)) { 14666 if (DEBUG_INSTALL) { 14667 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14668 } 14669 // Enable system package for requested users 14670 if (res.origUsers != null) { 14671 for (int origUserId : res.origUsers) { 14672 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14673 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14674 origUserId, installerPackageName); 14675 } 14676 } 14677 } 14678 // Also convey the prior install/uninstall state 14679 if (allUsers != null && installedForUsers != null) { 14680 for (int currentUserId : allUsers) { 14681 final boolean installed = ArrayUtils.contains( 14682 installedForUsers, currentUserId); 14683 if (DEBUG_INSTALL) { 14684 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14685 } 14686 ps.setInstalled(installed, currentUserId); 14687 } 14688 // these install state changes will be persisted in the 14689 // upcoming call to mSettings.writeLPr(). 14690 } 14691 } 14692 // It's implied that when a user requests installation, they want the app to be 14693 // installed and enabled. 14694 if (userId != UserHandle.USER_ALL) { 14695 ps.setInstalled(true, userId); 14696 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14697 } 14698 } 14699 res.name = pkgName; 14700 res.uid = newPackage.applicationInfo.uid; 14701 res.pkg = newPackage; 14702 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14703 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14704 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14705 //to update install status 14706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14707 mSettings.writeLPr(); 14708 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14709 } 14710 14711 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14712 } 14713 14714 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14715 try { 14716 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14717 installPackageLI(args, res); 14718 } finally { 14719 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14720 } 14721 } 14722 14723 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14724 final int installFlags = args.installFlags; 14725 final String installerPackageName = args.installerPackageName; 14726 final String volumeUuid = args.volumeUuid; 14727 final File tmpPackageFile = new File(args.getCodePath()); 14728 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14729 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14730 || (args.volumeUuid != null)); 14731 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14732 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14733 boolean replace = false; 14734 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14735 if (args.move != null) { 14736 // moving a complete application; perform an initial scan on the new install location 14737 scanFlags |= SCAN_INITIAL; 14738 } 14739 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14740 scanFlags |= SCAN_DONT_KILL_APP; 14741 } 14742 14743 // Result object to be returned 14744 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14745 14746 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14747 14748 // Sanity check 14749 if (ephemeral && (forwardLocked || onExternal)) { 14750 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14751 + " external=" + onExternal); 14752 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14753 return; 14754 } 14755 14756 // Retrieve PackageSettings and parse package 14757 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14758 | PackageParser.PARSE_ENFORCE_CODE 14759 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14760 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14761 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14762 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14763 PackageParser pp = new PackageParser(); 14764 pp.setSeparateProcesses(mSeparateProcesses); 14765 pp.setDisplayMetrics(mMetrics); 14766 14767 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14768 final PackageParser.Package pkg; 14769 try { 14770 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14771 } catch (PackageParserException e) { 14772 res.setError("Failed parse during installPackageLI", e); 14773 return; 14774 } finally { 14775 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14776 } 14777 14778 // If we are installing a clustered package add results for the children 14779 if (pkg.childPackages != null) { 14780 synchronized (mPackages) { 14781 final int childCount = pkg.childPackages.size(); 14782 for (int i = 0; i < childCount; i++) { 14783 PackageParser.Package childPkg = pkg.childPackages.get(i); 14784 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14785 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14786 childRes.pkg = childPkg; 14787 childRes.name = childPkg.packageName; 14788 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14789 if (childPs != null) { 14790 childRes.origUsers = childPs.queryInstalledUsers( 14791 sUserManager.getUserIds(), true); 14792 } 14793 if ((mPackages.containsKey(childPkg.packageName))) { 14794 childRes.removedInfo = new PackageRemovedInfo(); 14795 childRes.removedInfo.removedPackage = childPkg.packageName; 14796 } 14797 if (res.addedChildPackages == null) { 14798 res.addedChildPackages = new ArrayMap<>(); 14799 } 14800 res.addedChildPackages.put(childPkg.packageName, childRes); 14801 } 14802 } 14803 } 14804 14805 // If package doesn't declare API override, mark that we have an install 14806 // time CPU ABI override. 14807 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14808 pkg.cpuAbiOverride = args.abiOverride; 14809 } 14810 14811 String pkgName = res.name = pkg.packageName; 14812 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14813 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14814 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14815 return; 14816 } 14817 } 14818 14819 try { 14820 // either use what we've been given or parse directly from the APK 14821 if (args.certificates != null) { 14822 try { 14823 PackageParser.populateCertificates(pkg, args.certificates); 14824 } catch (PackageParserException e) { 14825 // there was something wrong with the certificates we were given; 14826 // try to pull them from the APK 14827 PackageParser.collectCertificates(pkg, parseFlags); 14828 } 14829 } else { 14830 PackageParser.collectCertificates(pkg, parseFlags); 14831 } 14832 } catch (PackageParserException e) { 14833 res.setError("Failed collect during installPackageLI", e); 14834 return; 14835 } 14836 14837 // Get rid of all references to package scan path via parser. 14838 pp = null; 14839 String oldCodePath = null; 14840 boolean systemApp = false; 14841 synchronized (mPackages) { 14842 // Check if installing already existing package 14843 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14844 String oldName = mSettings.mRenamedPackages.get(pkgName); 14845 if (pkg.mOriginalPackages != null 14846 && pkg.mOriginalPackages.contains(oldName) 14847 && mPackages.containsKey(oldName)) { 14848 // This package is derived from an original package, 14849 // and this device has been updating from that original 14850 // name. We must continue using the original name, so 14851 // rename the new package here. 14852 pkg.setPackageName(oldName); 14853 pkgName = pkg.packageName; 14854 replace = true; 14855 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14856 + oldName + " pkgName=" + pkgName); 14857 } else if (mPackages.containsKey(pkgName)) { 14858 // This package, under its official name, already exists 14859 // on the device; we should replace it. 14860 replace = true; 14861 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14862 } 14863 14864 // Child packages are installed through the parent package 14865 if (pkg.parentPackage != null) { 14866 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14867 "Package " + pkg.packageName + " is child of package " 14868 + pkg.parentPackage.parentPackage + ". Child packages " 14869 + "can be updated only through the parent package."); 14870 return; 14871 } 14872 14873 if (replace) { 14874 // Prevent apps opting out from runtime permissions 14875 PackageParser.Package oldPackage = mPackages.get(pkgName); 14876 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14877 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14878 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14879 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14880 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14881 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14882 + " doesn't support runtime permissions but the old" 14883 + " target SDK " + oldTargetSdk + " does."); 14884 return; 14885 } 14886 14887 // Prevent installing of child packages 14888 if (oldPackage.parentPackage != null) { 14889 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14890 "Package " + pkg.packageName + " is child of package " 14891 + oldPackage.parentPackage + ". Child packages " 14892 + "can be updated only through the parent package."); 14893 return; 14894 } 14895 } 14896 } 14897 14898 PackageSetting ps = mSettings.mPackages.get(pkgName); 14899 if (ps != null) { 14900 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14901 14902 // Quick sanity check that we're signed correctly if updating; 14903 // we'll check this again later when scanning, but we want to 14904 // bail early here before tripping over redefined permissions. 14905 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14906 if (!checkUpgradeKeySetLP(ps, pkg)) { 14907 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14908 + pkg.packageName + " upgrade keys do not match the " 14909 + "previously installed version"); 14910 return; 14911 } 14912 } else { 14913 try { 14914 verifySignaturesLP(ps, pkg); 14915 } catch (PackageManagerException e) { 14916 res.setError(e.error, e.getMessage()); 14917 return; 14918 } 14919 } 14920 14921 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14922 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14923 systemApp = (ps.pkg.applicationInfo.flags & 14924 ApplicationInfo.FLAG_SYSTEM) != 0; 14925 } 14926 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14927 } 14928 14929 // Check whether the newly-scanned package wants to define an already-defined perm 14930 int N = pkg.permissions.size(); 14931 for (int i = N-1; i >= 0; i--) { 14932 PackageParser.Permission perm = pkg.permissions.get(i); 14933 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14934 if (bp != null) { 14935 // If the defining package is signed with our cert, it's okay. This 14936 // also includes the "updating the same package" case, of course. 14937 // "updating same package" could also involve key-rotation. 14938 final boolean sigsOk; 14939 if (bp.sourcePackage.equals(pkg.packageName) 14940 && (bp.packageSetting instanceof PackageSetting) 14941 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14942 scanFlags))) { 14943 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14944 } else { 14945 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14946 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14947 } 14948 if (!sigsOk) { 14949 // If the owning package is the system itself, we log but allow 14950 // install to proceed; we fail the install on all other permission 14951 // redefinitions. 14952 if (!bp.sourcePackage.equals("android")) { 14953 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14954 + pkg.packageName + " attempting to redeclare permission " 14955 + perm.info.name + " already owned by " + bp.sourcePackage); 14956 res.origPermission = perm.info.name; 14957 res.origPackage = bp.sourcePackage; 14958 return; 14959 } else { 14960 Slog.w(TAG, "Package " + pkg.packageName 14961 + " attempting to redeclare system permission " 14962 + perm.info.name + "; ignoring new declaration"); 14963 pkg.permissions.remove(i); 14964 } 14965 } 14966 } 14967 } 14968 } 14969 14970 if (systemApp) { 14971 if (onExternal) { 14972 // Abort update; system app can't be replaced with app on sdcard 14973 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14974 "Cannot install updates to system apps on sdcard"); 14975 return; 14976 } else if (ephemeral) { 14977 // Abort update; system app can't be replaced with an ephemeral app 14978 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14979 "Cannot update a system app with an ephemeral app"); 14980 return; 14981 } 14982 } 14983 14984 if (args.move != null) { 14985 // We did an in-place move, so dex is ready to roll 14986 scanFlags |= SCAN_NO_DEX; 14987 scanFlags |= SCAN_MOVE; 14988 14989 synchronized (mPackages) { 14990 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14991 if (ps == null) { 14992 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14993 "Missing settings for moved package " + pkgName); 14994 } 14995 14996 // We moved the entire application as-is, so bring over the 14997 // previously derived ABI information. 14998 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14999 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15000 } 15001 15002 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15003 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15004 scanFlags |= SCAN_NO_DEX; 15005 15006 try { 15007 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15008 args.abiOverride : pkg.cpuAbiOverride); 15009 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15010 true /* extract libs */); 15011 } catch (PackageManagerException pme) { 15012 Slog.e(TAG, "Error deriving application ABI", pme); 15013 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15014 return; 15015 } 15016 15017 // Shared libraries for the package need to be updated. 15018 synchronized (mPackages) { 15019 try { 15020 updateSharedLibrariesLPw(pkg, null); 15021 } catch (PackageManagerException e) { 15022 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15023 } 15024 } 15025 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15026 // Do not run PackageDexOptimizer through the local performDexOpt 15027 // method because `pkg` may not be in `mPackages` yet. 15028 // 15029 // Also, don't fail application installs if the dexopt step fails. 15030 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15031 null /* instructionSets */, false /* checkProfiles */, 15032 getCompilerFilterForReason(REASON_INSTALL), 15033 getOrCreateCompilerPackageStats(pkg)); 15034 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15035 15036 // Notify BackgroundDexOptService that the package has been changed. 15037 // If this is an update of a package which used to fail to compile, 15038 // BDOS will remove it from its blacklist. 15039 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15040 } 15041 15042 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15043 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15044 return; 15045 } 15046 15047 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15048 15049 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15050 "installPackageLI")) { 15051 if (replace) { 15052 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15053 installerPackageName, res); 15054 } else { 15055 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15056 args.user, installerPackageName, volumeUuid, res); 15057 } 15058 } 15059 synchronized (mPackages) { 15060 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15061 if (ps != null) { 15062 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15063 } 15064 15065 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15066 for (int i = 0; i < childCount; i++) { 15067 PackageParser.Package childPkg = pkg.childPackages.get(i); 15068 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15069 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15070 if (childPs != null) { 15071 childRes.newUsers = childPs.queryInstalledUsers( 15072 sUserManager.getUserIds(), true); 15073 } 15074 } 15075 } 15076 } 15077 15078 private void startIntentFilterVerifications(int userId, boolean replacing, 15079 PackageParser.Package pkg) { 15080 if (mIntentFilterVerifierComponent == null) { 15081 Slog.w(TAG, "No IntentFilter verification will not be done as " 15082 + "there is no IntentFilterVerifier available!"); 15083 return; 15084 } 15085 15086 final int verifierUid = getPackageUid( 15087 mIntentFilterVerifierComponent.getPackageName(), 15088 MATCH_DEBUG_TRIAGED_MISSING, 15089 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15090 15091 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15092 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15093 mHandler.sendMessage(msg); 15094 15095 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15096 for (int i = 0; i < childCount; i++) { 15097 PackageParser.Package childPkg = pkg.childPackages.get(i); 15098 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15099 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15100 mHandler.sendMessage(msg); 15101 } 15102 } 15103 15104 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15105 PackageParser.Package pkg) { 15106 int size = pkg.activities.size(); 15107 if (size == 0) { 15108 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15109 "No activity, so no need to verify any IntentFilter!"); 15110 return; 15111 } 15112 15113 final boolean hasDomainURLs = hasDomainURLs(pkg); 15114 if (!hasDomainURLs) { 15115 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15116 "No domain URLs, so no need to verify any IntentFilter!"); 15117 return; 15118 } 15119 15120 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15121 + " if any IntentFilter from the " + size 15122 + " Activities needs verification ..."); 15123 15124 int count = 0; 15125 final String packageName = pkg.packageName; 15126 15127 synchronized (mPackages) { 15128 // If this is a new install and we see that we've already run verification for this 15129 // package, we have nothing to do: it means the state was restored from backup. 15130 if (!replacing) { 15131 IntentFilterVerificationInfo ivi = 15132 mSettings.getIntentFilterVerificationLPr(packageName); 15133 if (ivi != null) { 15134 if (DEBUG_DOMAIN_VERIFICATION) { 15135 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15136 + ivi.getStatusString()); 15137 } 15138 return; 15139 } 15140 } 15141 15142 // If any filters need to be verified, then all need to be. 15143 boolean needToVerify = false; 15144 for (PackageParser.Activity a : pkg.activities) { 15145 for (ActivityIntentInfo filter : a.intents) { 15146 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15147 if (DEBUG_DOMAIN_VERIFICATION) { 15148 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15149 } 15150 needToVerify = true; 15151 break; 15152 } 15153 } 15154 } 15155 15156 if (needToVerify) { 15157 final int verificationId = mIntentFilterVerificationToken++; 15158 for (PackageParser.Activity a : pkg.activities) { 15159 for (ActivityIntentInfo filter : a.intents) { 15160 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15161 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15162 "Verification needed for IntentFilter:" + filter.toString()); 15163 mIntentFilterVerifier.addOneIntentFilterVerification( 15164 verifierUid, userId, verificationId, filter, packageName); 15165 count++; 15166 } 15167 } 15168 } 15169 } 15170 } 15171 15172 if (count > 0) { 15173 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15174 + " IntentFilter verification" + (count > 1 ? "s" : "") 15175 + " for userId:" + userId); 15176 mIntentFilterVerifier.startVerifications(userId); 15177 } else { 15178 if (DEBUG_DOMAIN_VERIFICATION) { 15179 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15180 } 15181 } 15182 } 15183 15184 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15185 final ComponentName cn = filter.activity.getComponentName(); 15186 final String packageName = cn.getPackageName(); 15187 15188 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15189 packageName); 15190 if (ivi == null) { 15191 return true; 15192 } 15193 int status = ivi.getStatus(); 15194 switch (status) { 15195 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15196 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15197 return true; 15198 15199 default: 15200 // Nothing to do 15201 return false; 15202 } 15203 } 15204 15205 private static boolean isMultiArch(ApplicationInfo info) { 15206 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15207 } 15208 15209 private static boolean isExternal(PackageParser.Package pkg) { 15210 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15211 } 15212 15213 private static boolean isExternal(PackageSetting ps) { 15214 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15215 } 15216 15217 private static boolean isEphemeral(PackageParser.Package pkg) { 15218 return pkg.applicationInfo.isEphemeralApp(); 15219 } 15220 15221 private static boolean isEphemeral(PackageSetting ps) { 15222 return ps.pkg != null && isEphemeral(ps.pkg); 15223 } 15224 15225 private static boolean isSystemApp(PackageParser.Package pkg) { 15226 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15227 } 15228 15229 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15230 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15231 } 15232 15233 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15234 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15235 } 15236 15237 private static boolean isSystemApp(PackageSetting ps) { 15238 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15239 } 15240 15241 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15242 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15243 } 15244 15245 private int packageFlagsToInstallFlags(PackageSetting ps) { 15246 int installFlags = 0; 15247 if (isEphemeral(ps)) { 15248 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15249 } 15250 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15251 // This existing package was an external ASEC install when we have 15252 // the external flag without a UUID 15253 installFlags |= PackageManager.INSTALL_EXTERNAL; 15254 } 15255 if (ps.isForwardLocked()) { 15256 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15257 } 15258 return installFlags; 15259 } 15260 15261 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15262 if (isExternal(pkg)) { 15263 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15264 return StorageManager.UUID_PRIMARY_PHYSICAL; 15265 } else { 15266 return pkg.volumeUuid; 15267 } 15268 } else { 15269 return StorageManager.UUID_PRIVATE_INTERNAL; 15270 } 15271 } 15272 15273 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15274 if (isExternal(pkg)) { 15275 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15276 return mSettings.getExternalVersion(); 15277 } else { 15278 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15279 } 15280 } else { 15281 return mSettings.getInternalVersion(); 15282 } 15283 } 15284 15285 private void deleteTempPackageFiles() { 15286 final FilenameFilter filter = new FilenameFilter() { 15287 public boolean accept(File dir, String name) { 15288 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15289 } 15290 }; 15291 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15292 file.delete(); 15293 } 15294 } 15295 15296 @Override 15297 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15298 int flags) { 15299 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15300 flags); 15301 } 15302 15303 @Override 15304 public void deletePackage(final String packageName, 15305 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15306 mContext.enforceCallingOrSelfPermission( 15307 android.Manifest.permission.DELETE_PACKAGES, null); 15308 Preconditions.checkNotNull(packageName); 15309 Preconditions.checkNotNull(observer); 15310 final int uid = Binder.getCallingUid(); 15311 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15312 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15313 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15314 mContext.enforceCallingOrSelfPermission( 15315 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15316 "deletePackage for user " + userId); 15317 } 15318 15319 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15320 try { 15321 observer.onPackageDeleted(packageName, 15322 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15323 } catch (RemoteException re) { 15324 } 15325 return; 15326 } 15327 15328 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15329 try { 15330 observer.onPackageDeleted(packageName, 15331 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15332 } catch (RemoteException re) { 15333 } 15334 return; 15335 } 15336 15337 if (DEBUG_REMOVE) { 15338 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15339 + " deleteAllUsers: " + deleteAllUsers ); 15340 } 15341 // Queue up an async operation since the package deletion may take a little while. 15342 mHandler.post(new Runnable() { 15343 public void run() { 15344 mHandler.removeCallbacks(this); 15345 int returnCode; 15346 if (!deleteAllUsers) { 15347 returnCode = deletePackageX(packageName, userId, deleteFlags); 15348 } else { 15349 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15350 // If nobody is blocking uninstall, proceed with delete for all users 15351 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15352 returnCode = deletePackageX(packageName, userId, deleteFlags); 15353 } else { 15354 // Otherwise uninstall individually for users with blockUninstalls=false 15355 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15356 for (int userId : users) { 15357 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15358 returnCode = deletePackageX(packageName, userId, userFlags); 15359 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15360 Slog.w(TAG, "Package delete failed for user " + userId 15361 + ", returnCode " + returnCode); 15362 } 15363 } 15364 } 15365 // The app has only been marked uninstalled for certain users. 15366 // We still need to report that delete was blocked 15367 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15368 } 15369 } 15370 try { 15371 observer.onPackageDeleted(packageName, returnCode, null); 15372 } catch (RemoteException e) { 15373 Log.i(TAG, "Observer no longer exists."); 15374 } //end catch 15375 } //end run 15376 }); 15377 } 15378 15379 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15380 int[] result = EMPTY_INT_ARRAY; 15381 for (int userId : userIds) { 15382 if (getBlockUninstallForUser(packageName, userId)) { 15383 result = ArrayUtils.appendInt(result, userId); 15384 } 15385 } 15386 return result; 15387 } 15388 15389 @Override 15390 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15391 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15392 } 15393 15394 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15395 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15396 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15397 try { 15398 if (dpm != null) { 15399 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15400 /* callingUserOnly =*/ false); 15401 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15402 : deviceOwnerComponentName.getPackageName(); 15403 // Does the package contains the device owner? 15404 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15405 // this check is probably not needed, since DO should be registered as a device 15406 // admin on some user too. (Original bug for this: b/17657954) 15407 if (packageName.equals(deviceOwnerPackageName)) { 15408 return true; 15409 } 15410 // Does it contain a device admin for any user? 15411 int[] users; 15412 if (userId == UserHandle.USER_ALL) { 15413 users = sUserManager.getUserIds(); 15414 } else { 15415 users = new int[]{userId}; 15416 } 15417 for (int i = 0; i < users.length; ++i) { 15418 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15419 return true; 15420 } 15421 } 15422 } 15423 } catch (RemoteException e) { 15424 } 15425 return false; 15426 } 15427 15428 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15429 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15430 } 15431 15432 /** 15433 * This method is an internal method that could be get invoked either 15434 * to delete an installed package or to clean up a failed installation. 15435 * After deleting an installed package, a broadcast is sent to notify any 15436 * listeners that the package has been removed. For cleaning up a failed 15437 * installation, the broadcast is not necessary since the package's 15438 * installation wouldn't have sent the initial broadcast either 15439 * The key steps in deleting a package are 15440 * deleting the package information in internal structures like mPackages, 15441 * deleting the packages base directories through installd 15442 * updating mSettings to reflect current status 15443 * persisting settings for later use 15444 * sending a broadcast if necessary 15445 */ 15446 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15447 final PackageRemovedInfo info = new PackageRemovedInfo(); 15448 final boolean res; 15449 15450 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15451 ? UserHandle.USER_ALL : userId; 15452 15453 if (isPackageDeviceAdmin(packageName, removeUser)) { 15454 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15455 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15456 } 15457 15458 PackageSetting uninstalledPs = null; 15459 15460 // for the uninstall-updates case and restricted profiles, remember the per- 15461 // user handle installed state 15462 int[] allUsers; 15463 synchronized (mPackages) { 15464 uninstalledPs = mSettings.mPackages.get(packageName); 15465 if (uninstalledPs == null) { 15466 Slog.w(TAG, "Not removing non-existent package " + packageName); 15467 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15468 } 15469 allUsers = sUserManager.getUserIds(); 15470 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15471 } 15472 15473 final int freezeUser; 15474 if (isUpdatedSystemApp(uninstalledPs) 15475 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15476 // We're downgrading a system app, which will apply to all users, so 15477 // freeze them all during the downgrade 15478 freezeUser = UserHandle.USER_ALL; 15479 } else { 15480 freezeUser = removeUser; 15481 } 15482 15483 synchronized (mInstallLock) { 15484 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15485 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15486 deleteFlags, "deletePackageX")) { 15487 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15488 deleteFlags | REMOVE_CHATTY, info, true, null); 15489 } 15490 synchronized (mPackages) { 15491 if (res) { 15492 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15493 } 15494 } 15495 } 15496 15497 if (res) { 15498 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15499 info.sendPackageRemovedBroadcasts(killApp); 15500 info.sendSystemPackageUpdatedBroadcasts(); 15501 info.sendSystemPackageAppearedBroadcasts(); 15502 } 15503 // Force a gc here. 15504 Runtime.getRuntime().gc(); 15505 // Delete the resources here after sending the broadcast to let 15506 // other processes clean up before deleting resources. 15507 if (info.args != null) { 15508 synchronized (mInstallLock) { 15509 info.args.doPostDeleteLI(true); 15510 } 15511 } 15512 15513 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15514 } 15515 15516 class PackageRemovedInfo { 15517 String removedPackage; 15518 int uid = -1; 15519 int removedAppId = -1; 15520 int[] origUsers; 15521 int[] removedUsers = null; 15522 boolean isRemovedPackageSystemUpdate = false; 15523 boolean isUpdate; 15524 boolean dataRemoved; 15525 boolean removedForAllUsers; 15526 // Clean up resources deleted packages. 15527 InstallArgs args = null; 15528 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15529 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15530 15531 void sendPackageRemovedBroadcasts(boolean killApp) { 15532 sendPackageRemovedBroadcastInternal(killApp); 15533 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15534 for (int i = 0; i < childCount; i++) { 15535 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15536 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15537 } 15538 } 15539 15540 void sendSystemPackageUpdatedBroadcasts() { 15541 if (isRemovedPackageSystemUpdate) { 15542 sendSystemPackageUpdatedBroadcastsInternal(); 15543 final int childCount = (removedChildPackages != null) 15544 ? removedChildPackages.size() : 0; 15545 for (int i = 0; i < childCount; i++) { 15546 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15547 if (childInfo.isRemovedPackageSystemUpdate) { 15548 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15549 } 15550 } 15551 } 15552 } 15553 15554 void sendSystemPackageAppearedBroadcasts() { 15555 final int packageCount = (appearedChildPackages != null) 15556 ? appearedChildPackages.size() : 0; 15557 for (int i = 0; i < packageCount; i++) { 15558 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15559 for (int userId : installedInfo.newUsers) { 15560 sendPackageAddedForUser(installedInfo.name, true, 15561 UserHandle.getAppId(installedInfo.uid), userId); 15562 } 15563 } 15564 } 15565 15566 private void sendSystemPackageUpdatedBroadcastsInternal() { 15567 Bundle extras = new Bundle(2); 15568 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15569 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15570 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15571 extras, 0, null, null, null); 15572 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15573 extras, 0, null, null, null); 15574 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15575 null, 0, removedPackage, null, null); 15576 } 15577 15578 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15579 Bundle extras = new Bundle(2); 15580 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15581 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15582 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15583 if (isUpdate || isRemovedPackageSystemUpdate) { 15584 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15585 } 15586 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15587 if (removedPackage != null) { 15588 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15589 extras, 0, null, null, removedUsers); 15590 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15591 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15592 removedPackage, extras, 0, null, null, removedUsers); 15593 } 15594 } 15595 if (removedAppId >= 0) { 15596 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15597 removedUsers); 15598 } 15599 } 15600 } 15601 15602 /* 15603 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15604 * flag is not set, the data directory is removed as well. 15605 * make sure this flag is set for partially installed apps. If not its meaningless to 15606 * delete a partially installed application. 15607 */ 15608 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15609 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15610 String packageName = ps.name; 15611 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15612 // Retrieve object to delete permissions for shared user later on 15613 final PackageParser.Package deletedPkg; 15614 final PackageSetting deletedPs; 15615 // reader 15616 synchronized (mPackages) { 15617 deletedPkg = mPackages.get(packageName); 15618 deletedPs = mSettings.mPackages.get(packageName); 15619 if (outInfo != null) { 15620 outInfo.removedPackage = packageName; 15621 outInfo.removedUsers = deletedPs != null 15622 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15623 : null; 15624 } 15625 } 15626 15627 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15628 15629 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15630 final PackageParser.Package resolvedPkg; 15631 if (deletedPkg != null) { 15632 resolvedPkg = deletedPkg; 15633 } else { 15634 // We don't have a parsed package when it lives on an ejected 15635 // adopted storage device, so fake something together 15636 resolvedPkg = new PackageParser.Package(ps.name); 15637 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15638 } 15639 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15640 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15641 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15642 if (outInfo != null) { 15643 outInfo.dataRemoved = true; 15644 } 15645 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15646 } 15647 15648 // writer 15649 synchronized (mPackages) { 15650 if (deletedPs != null) { 15651 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15652 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15653 clearDefaultBrowserIfNeeded(packageName); 15654 if (outInfo != null) { 15655 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15656 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15657 } 15658 updatePermissionsLPw(deletedPs.name, null, 0); 15659 if (deletedPs.sharedUser != null) { 15660 // Remove permissions associated with package. Since runtime 15661 // permissions are per user we have to kill the removed package 15662 // or packages running under the shared user of the removed 15663 // package if revoking the permissions requested only by the removed 15664 // package is successful and this causes a change in gids. 15665 for (int userId : UserManagerService.getInstance().getUserIds()) { 15666 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15667 userId); 15668 if (userIdToKill == UserHandle.USER_ALL 15669 || userIdToKill >= UserHandle.USER_SYSTEM) { 15670 // If gids changed for this user, kill all affected packages. 15671 mHandler.post(new Runnable() { 15672 @Override 15673 public void run() { 15674 // This has to happen with no lock held. 15675 killApplication(deletedPs.name, deletedPs.appId, 15676 KILL_APP_REASON_GIDS_CHANGED); 15677 } 15678 }); 15679 break; 15680 } 15681 } 15682 } 15683 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15684 } 15685 // make sure to preserve per-user disabled state if this removal was just 15686 // a downgrade of a system app to the factory package 15687 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15688 if (DEBUG_REMOVE) { 15689 Slog.d(TAG, "Propagating install state across downgrade"); 15690 } 15691 for (int userId : allUserHandles) { 15692 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15693 if (DEBUG_REMOVE) { 15694 Slog.d(TAG, " user " + userId + " => " + installed); 15695 } 15696 ps.setInstalled(installed, userId); 15697 } 15698 } 15699 } 15700 // can downgrade to reader 15701 if (writeSettings) { 15702 // Save settings now 15703 mSettings.writeLPr(); 15704 } 15705 } 15706 if (outInfo != null) { 15707 // A user ID was deleted here. Go through all users and remove it 15708 // from KeyStore. 15709 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15710 } 15711 } 15712 15713 static boolean locationIsPrivileged(File path) { 15714 try { 15715 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15716 .getCanonicalPath(); 15717 return path.getCanonicalPath().startsWith(privilegedAppDir); 15718 } catch (IOException e) { 15719 Slog.e(TAG, "Unable to access code path " + path); 15720 } 15721 return false; 15722 } 15723 15724 /* 15725 * Tries to delete system package. 15726 */ 15727 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15728 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15729 boolean writeSettings) { 15730 if (deletedPs.parentPackageName != null) { 15731 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15732 return false; 15733 } 15734 15735 final boolean applyUserRestrictions 15736 = (allUserHandles != null) && (outInfo.origUsers != null); 15737 final PackageSetting disabledPs; 15738 // Confirm if the system package has been updated 15739 // An updated system app can be deleted. This will also have to restore 15740 // the system pkg from system partition 15741 // reader 15742 synchronized (mPackages) { 15743 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15744 } 15745 15746 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15747 + " disabledPs=" + disabledPs); 15748 15749 if (disabledPs == null) { 15750 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15751 return false; 15752 } else if (DEBUG_REMOVE) { 15753 Slog.d(TAG, "Deleting system pkg from data partition"); 15754 } 15755 15756 if (DEBUG_REMOVE) { 15757 if (applyUserRestrictions) { 15758 Slog.d(TAG, "Remembering install states:"); 15759 for (int userId : allUserHandles) { 15760 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15761 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15762 } 15763 } 15764 } 15765 15766 // Delete the updated package 15767 outInfo.isRemovedPackageSystemUpdate = true; 15768 if (outInfo.removedChildPackages != null) { 15769 final int childCount = (deletedPs.childPackageNames != null) 15770 ? deletedPs.childPackageNames.size() : 0; 15771 for (int i = 0; i < childCount; i++) { 15772 String childPackageName = deletedPs.childPackageNames.get(i); 15773 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15774 .contains(childPackageName)) { 15775 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15776 childPackageName); 15777 if (childInfo != null) { 15778 childInfo.isRemovedPackageSystemUpdate = true; 15779 } 15780 } 15781 } 15782 } 15783 15784 if (disabledPs.versionCode < deletedPs.versionCode) { 15785 // Delete data for downgrades 15786 flags &= ~PackageManager.DELETE_KEEP_DATA; 15787 } else { 15788 // Preserve data by setting flag 15789 flags |= PackageManager.DELETE_KEEP_DATA; 15790 } 15791 15792 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15793 outInfo, writeSettings, disabledPs.pkg); 15794 if (!ret) { 15795 return false; 15796 } 15797 15798 // writer 15799 synchronized (mPackages) { 15800 // Reinstate the old system package 15801 enableSystemPackageLPw(disabledPs.pkg); 15802 // Remove any native libraries from the upgraded package. 15803 removeNativeBinariesLI(deletedPs); 15804 } 15805 15806 // Install the system package 15807 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15808 int parseFlags = mDefParseFlags 15809 | PackageParser.PARSE_MUST_BE_APK 15810 | PackageParser.PARSE_IS_SYSTEM 15811 | PackageParser.PARSE_IS_SYSTEM_DIR; 15812 if (locationIsPrivileged(disabledPs.codePath)) { 15813 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15814 } 15815 15816 final PackageParser.Package newPkg; 15817 try { 15818 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15819 } catch (PackageManagerException e) { 15820 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15821 + e.getMessage()); 15822 return false; 15823 } 15824 15825 prepareAppDataAfterInstallLIF(newPkg); 15826 15827 // writer 15828 synchronized (mPackages) { 15829 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15830 15831 // Propagate the permissions state as we do not want to drop on the floor 15832 // runtime permissions. The update permissions method below will take 15833 // care of removing obsolete permissions and grant install permissions. 15834 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15835 updatePermissionsLPw(newPkg.packageName, newPkg, 15836 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15837 15838 if (applyUserRestrictions) { 15839 if (DEBUG_REMOVE) { 15840 Slog.d(TAG, "Propagating install state across reinstall"); 15841 } 15842 for (int userId : allUserHandles) { 15843 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15844 if (DEBUG_REMOVE) { 15845 Slog.d(TAG, " user " + userId + " => " + installed); 15846 } 15847 ps.setInstalled(installed, userId); 15848 15849 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15850 } 15851 // Regardless of writeSettings we need to ensure that this restriction 15852 // state propagation is persisted 15853 mSettings.writeAllUsersPackageRestrictionsLPr(); 15854 } 15855 // can downgrade to reader here 15856 if (writeSettings) { 15857 mSettings.writeLPr(); 15858 } 15859 } 15860 return true; 15861 } 15862 15863 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15864 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15865 PackageRemovedInfo outInfo, boolean writeSettings, 15866 PackageParser.Package replacingPackage) { 15867 synchronized (mPackages) { 15868 if (outInfo != null) { 15869 outInfo.uid = ps.appId; 15870 } 15871 15872 if (outInfo != null && outInfo.removedChildPackages != null) { 15873 final int childCount = (ps.childPackageNames != null) 15874 ? ps.childPackageNames.size() : 0; 15875 for (int i = 0; i < childCount; i++) { 15876 String childPackageName = ps.childPackageNames.get(i); 15877 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15878 if (childPs == null) { 15879 return false; 15880 } 15881 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15882 childPackageName); 15883 if (childInfo != null) { 15884 childInfo.uid = childPs.appId; 15885 } 15886 } 15887 } 15888 } 15889 15890 // Delete package data from internal structures and also remove data if flag is set 15891 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15892 15893 // Delete the child packages data 15894 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15895 for (int i = 0; i < childCount; i++) { 15896 PackageSetting childPs; 15897 synchronized (mPackages) { 15898 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15899 } 15900 if (childPs != null) { 15901 PackageRemovedInfo childOutInfo = (outInfo != null 15902 && outInfo.removedChildPackages != null) 15903 ? outInfo.removedChildPackages.get(childPs.name) : null; 15904 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15905 && (replacingPackage != null 15906 && !replacingPackage.hasChildPackage(childPs.name)) 15907 ? flags & ~DELETE_KEEP_DATA : flags; 15908 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15909 deleteFlags, writeSettings); 15910 } 15911 } 15912 15913 // Delete application code and resources only for parent packages 15914 if (ps.parentPackageName == null) { 15915 if (deleteCodeAndResources && (outInfo != null)) { 15916 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15917 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15918 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15919 } 15920 } 15921 15922 return true; 15923 } 15924 15925 @Override 15926 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15927 int userId) { 15928 mContext.enforceCallingOrSelfPermission( 15929 android.Manifest.permission.DELETE_PACKAGES, null); 15930 synchronized (mPackages) { 15931 PackageSetting ps = mSettings.mPackages.get(packageName); 15932 if (ps == null) { 15933 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15934 return false; 15935 } 15936 if (!ps.getInstalled(userId)) { 15937 // Can't block uninstall for an app that is not installed or enabled. 15938 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15939 return false; 15940 } 15941 ps.setBlockUninstall(blockUninstall, userId); 15942 mSettings.writePackageRestrictionsLPr(userId); 15943 } 15944 return true; 15945 } 15946 15947 @Override 15948 public boolean getBlockUninstallForUser(String packageName, int userId) { 15949 synchronized (mPackages) { 15950 PackageSetting ps = mSettings.mPackages.get(packageName); 15951 if (ps == null) { 15952 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15953 return false; 15954 } 15955 return ps.getBlockUninstall(userId); 15956 } 15957 } 15958 15959 @Override 15960 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15961 int callingUid = Binder.getCallingUid(); 15962 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15963 throw new SecurityException( 15964 "setRequiredForSystemUser can only be run by the system or root"); 15965 } 15966 synchronized (mPackages) { 15967 PackageSetting ps = mSettings.mPackages.get(packageName); 15968 if (ps == null) { 15969 Log.w(TAG, "Package doesn't exist: " + packageName); 15970 return false; 15971 } 15972 if (systemUserApp) { 15973 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15974 } else { 15975 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15976 } 15977 mSettings.writeLPr(); 15978 } 15979 return true; 15980 } 15981 15982 /* 15983 * This method handles package deletion in general 15984 */ 15985 private boolean deletePackageLIF(String packageName, UserHandle user, 15986 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15987 PackageRemovedInfo outInfo, boolean writeSettings, 15988 PackageParser.Package replacingPackage) { 15989 if (packageName == null) { 15990 Slog.w(TAG, "Attempt to delete null packageName."); 15991 return false; 15992 } 15993 15994 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15995 15996 PackageSetting ps; 15997 15998 synchronized (mPackages) { 15999 ps = mSettings.mPackages.get(packageName); 16000 if (ps == null) { 16001 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16002 return false; 16003 } 16004 16005 if (ps.parentPackageName != null && (!isSystemApp(ps) 16006 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16007 if (DEBUG_REMOVE) { 16008 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16009 + ((user == null) ? UserHandle.USER_ALL : user)); 16010 } 16011 final int removedUserId = (user != null) ? user.getIdentifier() 16012 : UserHandle.USER_ALL; 16013 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16014 return false; 16015 } 16016 markPackageUninstalledForUserLPw(ps, user); 16017 scheduleWritePackageRestrictionsLocked(user); 16018 return true; 16019 } 16020 } 16021 16022 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16023 && user.getIdentifier() != UserHandle.USER_ALL)) { 16024 // The caller is asking that the package only be deleted for a single 16025 // user. To do this, we just mark its uninstalled state and delete 16026 // its data. If this is a system app, we only allow this to happen if 16027 // they have set the special DELETE_SYSTEM_APP which requests different 16028 // semantics than normal for uninstalling system apps. 16029 markPackageUninstalledForUserLPw(ps, user); 16030 16031 if (!isSystemApp(ps)) { 16032 // Do not uninstall the APK if an app should be cached 16033 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16034 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16035 // Other user still have this package installed, so all 16036 // we need to do is clear this user's data and save that 16037 // it is uninstalled. 16038 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16039 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16040 return false; 16041 } 16042 scheduleWritePackageRestrictionsLocked(user); 16043 return true; 16044 } else { 16045 // We need to set it back to 'installed' so the uninstall 16046 // broadcasts will be sent correctly. 16047 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16048 ps.setInstalled(true, user.getIdentifier()); 16049 } 16050 } else { 16051 // This is a system app, so we assume that the 16052 // other users still have this package installed, so all 16053 // we need to do is clear this user's data and save that 16054 // it is uninstalled. 16055 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16056 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16057 return false; 16058 } 16059 scheduleWritePackageRestrictionsLocked(user); 16060 return true; 16061 } 16062 } 16063 16064 // If we are deleting a composite package for all users, keep track 16065 // of result for each child. 16066 if (ps.childPackageNames != null && outInfo != null) { 16067 synchronized (mPackages) { 16068 final int childCount = ps.childPackageNames.size(); 16069 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16070 for (int i = 0; i < childCount; i++) { 16071 String childPackageName = ps.childPackageNames.get(i); 16072 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16073 childInfo.removedPackage = childPackageName; 16074 outInfo.removedChildPackages.put(childPackageName, childInfo); 16075 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16076 if (childPs != null) { 16077 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16078 } 16079 } 16080 } 16081 } 16082 16083 boolean ret = false; 16084 if (isSystemApp(ps)) { 16085 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16086 // When an updated system application is deleted we delete the existing resources 16087 // as well and fall back to existing code in system partition 16088 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16089 } else { 16090 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16091 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16092 outInfo, writeSettings, replacingPackage); 16093 } 16094 16095 // Take a note whether we deleted the package for all users 16096 if (outInfo != null) { 16097 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16098 if (outInfo.removedChildPackages != null) { 16099 synchronized (mPackages) { 16100 final int childCount = outInfo.removedChildPackages.size(); 16101 for (int i = 0; i < childCount; i++) { 16102 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16103 if (childInfo != null) { 16104 childInfo.removedForAllUsers = mPackages.get( 16105 childInfo.removedPackage) == null; 16106 } 16107 } 16108 } 16109 } 16110 // If we uninstalled an update to a system app there may be some 16111 // child packages that appeared as they are declared in the system 16112 // app but were not declared in the update. 16113 if (isSystemApp(ps)) { 16114 synchronized (mPackages) { 16115 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16116 final int childCount = (updatedPs.childPackageNames != null) 16117 ? updatedPs.childPackageNames.size() : 0; 16118 for (int i = 0; i < childCount; i++) { 16119 String childPackageName = updatedPs.childPackageNames.get(i); 16120 if (outInfo.removedChildPackages == null 16121 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16122 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16123 if (childPs == null) { 16124 continue; 16125 } 16126 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16127 installRes.name = childPackageName; 16128 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16129 installRes.pkg = mPackages.get(childPackageName); 16130 installRes.uid = childPs.pkg.applicationInfo.uid; 16131 if (outInfo.appearedChildPackages == null) { 16132 outInfo.appearedChildPackages = new ArrayMap<>(); 16133 } 16134 outInfo.appearedChildPackages.put(childPackageName, installRes); 16135 } 16136 } 16137 } 16138 } 16139 } 16140 16141 return ret; 16142 } 16143 16144 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16145 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16146 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16147 for (int nextUserId : userIds) { 16148 if (DEBUG_REMOVE) { 16149 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16150 } 16151 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16152 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16153 false /*hidden*/, false /*suspended*/, null, null, null, 16154 false /*blockUninstall*/, 16155 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16156 } 16157 } 16158 16159 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16160 PackageRemovedInfo outInfo) { 16161 final PackageParser.Package pkg; 16162 synchronized (mPackages) { 16163 pkg = mPackages.get(ps.name); 16164 } 16165 16166 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16167 : new int[] {userId}; 16168 for (int nextUserId : userIds) { 16169 if (DEBUG_REMOVE) { 16170 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16171 + nextUserId); 16172 } 16173 16174 destroyAppDataLIF(pkg, userId, 16175 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16176 destroyAppProfilesLIF(pkg, userId); 16177 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16178 schedulePackageCleaning(ps.name, nextUserId, false); 16179 synchronized (mPackages) { 16180 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16181 scheduleWritePackageRestrictionsLocked(nextUserId); 16182 } 16183 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16184 } 16185 } 16186 16187 if (outInfo != null) { 16188 outInfo.removedPackage = ps.name; 16189 outInfo.removedAppId = ps.appId; 16190 outInfo.removedUsers = userIds; 16191 } 16192 16193 return true; 16194 } 16195 16196 private final class ClearStorageConnection implements ServiceConnection { 16197 IMediaContainerService mContainerService; 16198 16199 @Override 16200 public void onServiceConnected(ComponentName name, IBinder service) { 16201 synchronized (this) { 16202 mContainerService = IMediaContainerService.Stub.asInterface(service); 16203 notifyAll(); 16204 } 16205 } 16206 16207 @Override 16208 public void onServiceDisconnected(ComponentName name) { 16209 } 16210 } 16211 16212 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16213 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16214 16215 final boolean mounted; 16216 if (Environment.isExternalStorageEmulated()) { 16217 mounted = true; 16218 } else { 16219 final String status = Environment.getExternalStorageState(); 16220 16221 mounted = status.equals(Environment.MEDIA_MOUNTED) 16222 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16223 } 16224 16225 if (!mounted) { 16226 return; 16227 } 16228 16229 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16230 int[] users; 16231 if (userId == UserHandle.USER_ALL) { 16232 users = sUserManager.getUserIds(); 16233 } else { 16234 users = new int[] { userId }; 16235 } 16236 final ClearStorageConnection conn = new ClearStorageConnection(); 16237 if (mContext.bindServiceAsUser( 16238 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16239 try { 16240 for (int curUser : users) { 16241 long timeout = SystemClock.uptimeMillis() + 5000; 16242 synchronized (conn) { 16243 long now; 16244 while (conn.mContainerService == null && 16245 (now = SystemClock.uptimeMillis()) < timeout) { 16246 try { 16247 conn.wait(timeout - now); 16248 } catch (InterruptedException e) { 16249 } 16250 } 16251 } 16252 if (conn.mContainerService == null) { 16253 return; 16254 } 16255 16256 final UserEnvironment userEnv = new UserEnvironment(curUser); 16257 clearDirectory(conn.mContainerService, 16258 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16259 if (allData) { 16260 clearDirectory(conn.mContainerService, 16261 userEnv.buildExternalStorageAppDataDirs(packageName)); 16262 clearDirectory(conn.mContainerService, 16263 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16264 } 16265 } 16266 } finally { 16267 mContext.unbindService(conn); 16268 } 16269 } 16270 } 16271 16272 @Override 16273 public void clearApplicationProfileData(String packageName) { 16274 enforceSystemOrRoot("Only the system can clear all profile data"); 16275 16276 final PackageParser.Package pkg; 16277 synchronized (mPackages) { 16278 pkg = mPackages.get(packageName); 16279 } 16280 16281 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16282 synchronized (mInstallLock) { 16283 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16284 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16285 true /* removeBaseMarker */); 16286 } 16287 } 16288 } 16289 16290 @Override 16291 public void clearApplicationUserData(final String packageName, 16292 final IPackageDataObserver observer, final int userId) { 16293 mContext.enforceCallingOrSelfPermission( 16294 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16295 16296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16297 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16298 16299 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16300 throw new SecurityException("Cannot clear data for a protected package: " 16301 + packageName); 16302 } 16303 // Queue up an async operation since the package deletion may take a little while. 16304 mHandler.post(new Runnable() { 16305 public void run() { 16306 mHandler.removeCallbacks(this); 16307 final boolean succeeded; 16308 try (PackageFreezer freezer = freezePackage(packageName, 16309 "clearApplicationUserData")) { 16310 synchronized (mInstallLock) { 16311 succeeded = clearApplicationUserDataLIF(packageName, userId); 16312 } 16313 clearExternalStorageDataSync(packageName, userId, true); 16314 } 16315 if (succeeded) { 16316 // invoke DeviceStorageMonitor's update method to clear any notifications 16317 DeviceStorageMonitorInternal dsm = LocalServices 16318 .getService(DeviceStorageMonitorInternal.class); 16319 if (dsm != null) { 16320 dsm.checkMemory(); 16321 } 16322 } 16323 if(observer != null) { 16324 try { 16325 observer.onRemoveCompleted(packageName, succeeded); 16326 } catch (RemoteException e) { 16327 Log.i(TAG, "Observer no longer exists."); 16328 } 16329 } //end if observer 16330 } //end run 16331 }); 16332 } 16333 16334 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16335 if (packageName == null) { 16336 Slog.w(TAG, "Attempt to delete null packageName."); 16337 return false; 16338 } 16339 16340 // Try finding details about the requested package 16341 PackageParser.Package pkg; 16342 synchronized (mPackages) { 16343 pkg = mPackages.get(packageName); 16344 if (pkg == null) { 16345 final PackageSetting ps = mSettings.mPackages.get(packageName); 16346 if (ps != null) { 16347 pkg = ps.pkg; 16348 } 16349 } 16350 16351 if (pkg == null) { 16352 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16353 return false; 16354 } 16355 16356 PackageSetting ps = (PackageSetting) pkg.mExtras; 16357 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16358 } 16359 16360 clearAppDataLIF(pkg, userId, 16361 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16362 16363 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16364 removeKeystoreDataIfNeeded(userId, appId); 16365 16366 UserManagerInternal umInternal = getUserManagerInternal(); 16367 final int flags; 16368 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16369 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16370 } else if (umInternal.isUserRunning(userId)) { 16371 flags = StorageManager.FLAG_STORAGE_DE; 16372 } else { 16373 flags = 0; 16374 } 16375 prepareAppDataContentsLIF(pkg, userId, flags); 16376 16377 return true; 16378 } 16379 16380 /** 16381 * Reverts user permission state changes (permissions and flags) in 16382 * all packages for a given user. 16383 * 16384 * @param userId The device user for which to do a reset. 16385 */ 16386 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16387 final int packageCount = mPackages.size(); 16388 for (int i = 0; i < packageCount; i++) { 16389 PackageParser.Package pkg = mPackages.valueAt(i); 16390 PackageSetting ps = (PackageSetting) pkg.mExtras; 16391 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16392 } 16393 } 16394 16395 private void resetNetworkPolicies(int userId) { 16396 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16397 } 16398 16399 /** 16400 * Reverts user permission state changes (permissions and flags). 16401 * 16402 * @param ps The package for which to reset. 16403 * @param userId The device user for which to do a reset. 16404 */ 16405 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16406 final PackageSetting ps, final int userId) { 16407 if (ps.pkg == null) { 16408 return; 16409 } 16410 16411 // These are flags that can change base on user actions. 16412 final int userSettableMask = FLAG_PERMISSION_USER_SET 16413 | FLAG_PERMISSION_USER_FIXED 16414 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16415 | FLAG_PERMISSION_REVIEW_REQUIRED; 16416 16417 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16418 | FLAG_PERMISSION_POLICY_FIXED; 16419 16420 boolean writeInstallPermissions = false; 16421 boolean writeRuntimePermissions = false; 16422 16423 final int permissionCount = ps.pkg.requestedPermissions.size(); 16424 for (int i = 0; i < permissionCount; i++) { 16425 String permission = ps.pkg.requestedPermissions.get(i); 16426 16427 BasePermission bp = mSettings.mPermissions.get(permission); 16428 if (bp == null) { 16429 continue; 16430 } 16431 16432 // If shared user we just reset the state to which only this app contributed. 16433 if (ps.sharedUser != null) { 16434 boolean used = false; 16435 final int packageCount = ps.sharedUser.packages.size(); 16436 for (int j = 0; j < packageCount; j++) { 16437 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16438 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16439 && pkg.pkg.requestedPermissions.contains(permission)) { 16440 used = true; 16441 break; 16442 } 16443 } 16444 if (used) { 16445 continue; 16446 } 16447 } 16448 16449 PermissionsState permissionsState = ps.getPermissionsState(); 16450 16451 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16452 16453 // Always clear the user settable flags. 16454 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16455 bp.name) != null; 16456 // If permission review is enabled and this is a legacy app, mark the 16457 // permission as requiring a review as this is the initial state. 16458 int flags = 0; 16459 if (Build.PERMISSIONS_REVIEW_REQUIRED 16460 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16461 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16462 } 16463 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16464 if (hasInstallState) { 16465 writeInstallPermissions = true; 16466 } else { 16467 writeRuntimePermissions = true; 16468 } 16469 } 16470 16471 // Below is only runtime permission handling. 16472 if (!bp.isRuntime()) { 16473 continue; 16474 } 16475 16476 // Never clobber system or policy. 16477 if ((oldFlags & policyOrSystemFlags) != 0) { 16478 continue; 16479 } 16480 16481 // If this permission was granted by default, make sure it is. 16482 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16483 if (permissionsState.grantRuntimePermission(bp, userId) 16484 != PERMISSION_OPERATION_FAILURE) { 16485 writeRuntimePermissions = true; 16486 } 16487 // If permission review is enabled the permissions for a legacy apps 16488 // are represented as constantly granted runtime ones, so don't revoke. 16489 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16490 // Otherwise, reset the permission. 16491 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16492 switch (revokeResult) { 16493 case PERMISSION_OPERATION_SUCCESS: 16494 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16495 writeRuntimePermissions = true; 16496 final int appId = ps.appId; 16497 mHandler.post(new Runnable() { 16498 @Override 16499 public void run() { 16500 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16501 } 16502 }); 16503 } break; 16504 } 16505 } 16506 } 16507 16508 // Synchronously write as we are taking permissions away. 16509 if (writeRuntimePermissions) { 16510 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16511 } 16512 16513 // Synchronously write as we are taking permissions away. 16514 if (writeInstallPermissions) { 16515 mSettings.writeLPr(); 16516 } 16517 } 16518 16519 /** 16520 * Remove entries from the keystore daemon. Will only remove it if the 16521 * {@code appId} is valid. 16522 */ 16523 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16524 if (appId < 0) { 16525 return; 16526 } 16527 16528 final KeyStore keyStore = KeyStore.getInstance(); 16529 if (keyStore != null) { 16530 if (userId == UserHandle.USER_ALL) { 16531 for (final int individual : sUserManager.getUserIds()) { 16532 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16533 } 16534 } else { 16535 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16536 } 16537 } else { 16538 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16539 } 16540 } 16541 16542 @Override 16543 public void deleteApplicationCacheFiles(final String packageName, 16544 final IPackageDataObserver observer) { 16545 final int userId = UserHandle.getCallingUserId(); 16546 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16547 } 16548 16549 @Override 16550 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16551 final IPackageDataObserver observer) { 16552 mContext.enforceCallingOrSelfPermission( 16553 android.Manifest.permission.DELETE_CACHE_FILES, null); 16554 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16555 /* requireFullPermission= */ true, /* checkShell= */ false, 16556 "delete application cache files"); 16557 16558 final PackageParser.Package pkg; 16559 synchronized (mPackages) { 16560 pkg = mPackages.get(packageName); 16561 } 16562 16563 // Queue up an async operation since the package deletion may take a little while. 16564 mHandler.post(new Runnable() { 16565 public void run() { 16566 synchronized (mInstallLock) { 16567 final int flags = StorageManager.FLAG_STORAGE_DE 16568 | StorageManager.FLAG_STORAGE_CE; 16569 // We're only clearing cache files, so we don't care if the 16570 // app is unfrozen and still able to run 16571 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16572 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16573 } 16574 clearExternalStorageDataSync(packageName, userId, false); 16575 if (observer != null) { 16576 try { 16577 observer.onRemoveCompleted(packageName, true); 16578 } catch (RemoteException e) { 16579 Log.i(TAG, "Observer no longer exists."); 16580 } 16581 } 16582 } 16583 }); 16584 } 16585 16586 @Override 16587 public void getPackageSizeInfo(final String packageName, int userHandle, 16588 final IPackageStatsObserver observer) { 16589 mContext.enforceCallingOrSelfPermission( 16590 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16591 if (packageName == null) { 16592 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16593 } 16594 16595 PackageStats stats = new PackageStats(packageName, userHandle); 16596 16597 /* 16598 * Queue up an async operation since the package measurement may take a 16599 * little while. 16600 */ 16601 Message msg = mHandler.obtainMessage(INIT_COPY); 16602 msg.obj = new MeasureParams(stats, observer); 16603 mHandler.sendMessage(msg); 16604 } 16605 16606 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16607 final PackageSetting ps; 16608 synchronized (mPackages) { 16609 ps = mSettings.mPackages.get(packageName); 16610 if (ps == null) { 16611 Slog.w(TAG, "Failed to find settings for " + packageName); 16612 return false; 16613 } 16614 } 16615 try { 16616 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16617 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16618 ps.getCeDataInode(userId), ps.codePathString, stats); 16619 } catch (InstallerException e) { 16620 Slog.w(TAG, String.valueOf(e)); 16621 return false; 16622 } 16623 16624 // For now, ignore code size of packages on system partition 16625 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16626 stats.codeSize = 0; 16627 } 16628 16629 return true; 16630 } 16631 16632 private int getUidTargetSdkVersionLockedLPr(int uid) { 16633 Object obj = mSettings.getUserIdLPr(uid); 16634 if (obj instanceof SharedUserSetting) { 16635 final SharedUserSetting sus = (SharedUserSetting) obj; 16636 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16637 final Iterator<PackageSetting> it = sus.packages.iterator(); 16638 while (it.hasNext()) { 16639 final PackageSetting ps = it.next(); 16640 if (ps.pkg != null) { 16641 int v = ps.pkg.applicationInfo.targetSdkVersion; 16642 if (v < vers) vers = v; 16643 } 16644 } 16645 return vers; 16646 } else if (obj instanceof PackageSetting) { 16647 final PackageSetting ps = (PackageSetting) obj; 16648 if (ps.pkg != null) { 16649 return ps.pkg.applicationInfo.targetSdkVersion; 16650 } 16651 } 16652 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16653 } 16654 16655 @Override 16656 public void addPreferredActivity(IntentFilter filter, int match, 16657 ComponentName[] set, ComponentName activity, int userId) { 16658 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16659 "Adding preferred"); 16660 } 16661 16662 private void addPreferredActivityInternal(IntentFilter filter, int match, 16663 ComponentName[] set, ComponentName activity, boolean always, int userId, 16664 String opname) { 16665 // writer 16666 int callingUid = Binder.getCallingUid(); 16667 enforceCrossUserPermission(callingUid, userId, 16668 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16669 if (filter.countActions() == 0) { 16670 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16671 return; 16672 } 16673 synchronized (mPackages) { 16674 if (mContext.checkCallingOrSelfPermission( 16675 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16676 != PackageManager.PERMISSION_GRANTED) { 16677 if (getUidTargetSdkVersionLockedLPr(callingUid) 16678 < Build.VERSION_CODES.FROYO) { 16679 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16680 + callingUid); 16681 return; 16682 } 16683 mContext.enforceCallingOrSelfPermission( 16684 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16685 } 16686 16687 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16688 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16689 + userId + ":"); 16690 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16691 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16692 scheduleWritePackageRestrictionsLocked(userId); 16693 postPreferredActivityChangedBroadcast(userId); 16694 } 16695 } 16696 16697 private void postPreferredActivityChangedBroadcast(int userId) { 16698 mHandler.post(() -> { 16699 final IActivityManager am = ActivityManagerNative.getDefault(); 16700 if (am == null) { 16701 return; 16702 } 16703 16704 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 16705 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 16706 try { 16707 am.broadcastIntent(null, intent, null, null, 16708 0, null, null, null, android.app.AppOpsManager.OP_NONE, 16709 null, false, false, userId); 16710 } catch (RemoteException e) { 16711 } 16712 }); 16713 } 16714 16715 @Override 16716 public void replacePreferredActivity(IntentFilter filter, int match, 16717 ComponentName[] set, ComponentName activity, int userId) { 16718 if (filter.countActions() != 1) { 16719 throw new IllegalArgumentException( 16720 "replacePreferredActivity expects filter to have only 1 action."); 16721 } 16722 if (filter.countDataAuthorities() != 0 16723 || filter.countDataPaths() != 0 16724 || filter.countDataSchemes() > 1 16725 || filter.countDataTypes() != 0) { 16726 throw new IllegalArgumentException( 16727 "replacePreferredActivity expects filter to have no data authorities, " + 16728 "paths, or types; and at most one scheme."); 16729 } 16730 16731 final int callingUid = Binder.getCallingUid(); 16732 enforceCrossUserPermission(callingUid, userId, 16733 true /* requireFullPermission */, false /* checkShell */, 16734 "replace preferred activity"); 16735 synchronized (mPackages) { 16736 if (mContext.checkCallingOrSelfPermission( 16737 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16738 != PackageManager.PERMISSION_GRANTED) { 16739 if (getUidTargetSdkVersionLockedLPr(callingUid) 16740 < Build.VERSION_CODES.FROYO) { 16741 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16742 + Binder.getCallingUid()); 16743 return; 16744 } 16745 mContext.enforceCallingOrSelfPermission( 16746 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16747 } 16748 16749 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16750 if (pir != null) { 16751 // Get all of the existing entries that exactly match this filter. 16752 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16753 if (existing != null && existing.size() == 1) { 16754 PreferredActivity cur = existing.get(0); 16755 if (DEBUG_PREFERRED) { 16756 Slog.i(TAG, "Checking replace of preferred:"); 16757 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16758 if (!cur.mPref.mAlways) { 16759 Slog.i(TAG, " -- CUR; not mAlways!"); 16760 } else { 16761 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16762 Slog.i(TAG, " -- CUR: mSet=" 16763 + Arrays.toString(cur.mPref.mSetComponents)); 16764 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16765 Slog.i(TAG, " -- NEW: mMatch=" 16766 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16767 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16768 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16769 } 16770 } 16771 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16772 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16773 && cur.mPref.sameSet(set)) { 16774 // Setting the preferred activity to what it happens to be already 16775 if (DEBUG_PREFERRED) { 16776 Slog.i(TAG, "Replacing with same preferred activity " 16777 + cur.mPref.mShortComponent + " for user " 16778 + userId + ":"); 16779 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16780 } 16781 return; 16782 } 16783 } 16784 16785 if (existing != null) { 16786 if (DEBUG_PREFERRED) { 16787 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16788 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16789 } 16790 for (int i = 0; i < existing.size(); i++) { 16791 PreferredActivity pa = existing.get(i); 16792 if (DEBUG_PREFERRED) { 16793 Slog.i(TAG, "Removing existing preferred activity " 16794 + pa.mPref.mComponent + ":"); 16795 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16796 } 16797 pir.removeFilter(pa); 16798 } 16799 } 16800 } 16801 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16802 "Replacing preferred"); 16803 } 16804 } 16805 16806 @Override 16807 public void clearPackagePreferredActivities(String packageName) { 16808 final int uid = Binder.getCallingUid(); 16809 // writer 16810 synchronized (mPackages) { 16811 PackageParser.Package pkg = mPackages.get(packageName); 16812 if (pkg == null || pkg.applicationInfo.uid != uid) { 16813 if (mContext.checkCallingOrSelfPermission( 16814 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16815 != PackageManager.PERMISSION_GRANTED) { 16816 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16817 < Build.VERSION_CODES.FROYO) { 16818 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16819 + Binder.getCallingUid()); 16820 return; 16821 } 16822 mContext.enforceCallingOrSelfPermission( 16823 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16824 } 16825 } 16826 16827 int user = UserHandle.getCallingUserId(); 16828 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16829 scheduleWritePackageRestrictionsLocked(user); 16830 } 16831 } 16832 } 16833 16834 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16835 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16836 ArrayList<PreferredActivity> removed = null; 16837 boolean changed = false; 16838 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16839 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16840 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16841 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16842 continue; 16843 } 16844 Iterator<PreferredActivity> it = pir.filterIterator(); 16845 while (it.hasNext()) { 16846 PreferredActivity pa = it.next(); 16847 // Mark entry for removal only if it matches the package name 16848 // and the entry is of type "always". 16849 if (packageName == null || 16850 (pa.mPref.mComponent.getPackageName().equals(packageName) 16851 && pa.mPref.mAlways)) { 16852 if (removed == null) { 16853 removed = new ArrayList<PreferredActivity>(); 16854 } 16855 removed.add(pa); 16856 } 16857 } 16858 if (removed != null) { 16859 for (int j=0; j<removed.size(); j++) { 16860 PreferredActivity pa = removed.get(j); 16861 pir.removeFilter(pa); 16862 } 16863 changed = true; 16864 } 16865 } 16866 if (changed) { 16867 postPreferredActivityChangedBroadcast(userId); 16868 } 16869 return changed; 16870 } 16871 16872 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16873 private void clearIntentFilterVerificationsLPw(int userId) { 16874 final int packageCount = mPackages.size(); 16875 for (int i = 0; i < packageCount; i++) { 16876 PackageParser.Package pkg = mPackages.valueAt(i); 16877 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16878 } 16879 } 16880 16881 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16882 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16883 if (userId == UserHandle.USER_ALL) { 16884 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16885 sUserManager.getUserIds())) { 16886 for (int oneUserId : sUserManager.getUserIds()) { 16887 scheduleWritePackageRestrictionsLocked(oneUserId); 16888 } 16889 } 16890 } else { 16891 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16892 scheduleWritePackageRestrictionsLocked(userId); 16893 } 16894 } 16895 } 16896 16897 void clearDefaultBrowserIfNeeded(String packageName) { 16898 for (int oneUserId : sUserManager.getUserIds()) { 16899 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16900 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16901 if (packageName.equals(defaultBrowserPackageName)) { 16902 setDefaultBrowserPackageName(null, oneUserId); 16903 } 16904 } 16905 } 16906 16907 @Override 16908 public void resetApplicationPreferences(int userId) { 16909 mContext.enforceCallingOrSelfPermission( 16910 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16911 final long identity = Binder.clearCallingIdentity(); 16912 // writer 16913 try { 16914 synchronized (mPackages) { 16915 clearPackagePreferredActivitiesLPw(null, userId); 16916 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16917 // TODO: We have to reset the default SMS and Phone. This requires 16918 // significant refactoring to keep all default apps in the package 16919 // manager (cleaner but more work) or have the services provide 16920 // callbacks to the package manager to request a default app reset. 16921 applyFactoryDefaultBrowserLPw(userId); 16922 clearIntentFilterVerificationsLPw(userId); 16923 primeDomainVerificationsLPw(userId); 16924 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16925 scheduleWritePackageRestrictionsLocked(userId); 16926 } 16927 resetNetworkPolicies(userId); 16928 } finally { 16929 Binder.restoreCallingIdentity(identity); 16930 } 16931 } 16932 16933 @Override 16934 public int getPreferredActivities(List<IntentFilter> outFilters, 16935 List<ComponentName> outActivities, String packageName) { 16936 16937 int num = 0; 16938 final int userId = UserHandle.getCallingUserId(); 16939 // reader 16940 synchronized (mPackages) { 16941 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16942 if (pir != null) { 16943 final Iterator<PreferredActivity> it = pir.filterIterator(); 16944 while (it.hasNext()) { 16945 final PreferredActivity pa = it.next(); 16946 if (packageName == null 16947 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16948 && pa.mPref.mAlways)) { 16949 if (outFilters != null) { 16950 outFilters.add(new IntentFilter(pa)); 16951 } 16952 if (outActivities != null) { 16953 outActivities.add(pa.mPref.mComponent); 16954 } 16955 } 16956 } 16957 } 16958 } 16959 16960 return num; 16961 } 16962 16963 @Override 16964 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16965 int userId) { 16966 int callingUid = Binder.getCallingUid(); 16967 if (callingUid != Process.SYSTEM_UID) { 16968 throw new SecurityException( 16969 "addPersistentPreferredActivity can only be run by the system"); 16970 } 16971 if (filter.countActions() == 0) { 16972 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16973 return; 16974 } 16975 synchronized (mPackages) { 16976 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16977 ":"); 16978 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16979 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16980 new PersistentPreferredActivity(filter, activity)); 16981 scheduleWritePackageRestrictionsLocked(userId); 16982 postPreferredActivityChangedBroadcast(userId); 16983 } 16984 } 16985 16986 @Override 16987 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16988 int callingUid = Binder.getCallingUid(); 16989 if (callingUid != Process.SYSTEM_UID) { 16990 throw new SecurityException( 16991 "clearPackagePersistentPreferredActivities can only be run by the system"); 16992 } 16993 ArrayList<PersistentPreferredActivity> removed = null; 16994 boolean changed = false; 16995 synchronized (mPackages) { 16996 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16997 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16998 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16999 .valueAt(i); 17000 if (userId != thisUserId) { 17001 continue; 17002 } 17003 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17004 while (it.hasNext()) { 17005 PersistentPreferredActivity ppa = it.next(); 17006 // Mark entry for removal only if it matches the package name. 17007 if (ppa.mComponent.getPackageName().equals(packageName)) { 17008 if (removed == null) { 17009 removed = new ArrayList<PersistentPreferredActivity>(); 17010 } 17011 removed.add(ppa); 17012 } 17013 } 17014 if (removed != null) { 17015 for (int j=0; j<removed.size(); j++) { 17016 PersistentPreferredActivity ppa = removed.get(j); 17017 ppir.removeFilter(ppa); 17018 } 17019 changed = true; 17020 } 17021 } 17022 17023 if (changed) { 17024 scheduleWritePackageRestrictionsLocked(userId); 17025 postPreferredActivityChangedBroadcast(userId); 17026 } 17027 } 17028 } 17029 17030 /** 17031 * Common machinery for picking apart a restored XML blob and passing 17032 * it to a caller-supplied functor to be applied to the running system. 17033 */ 17034 private void restoreFromXml(XmlPullParser parser, int userId, 17035 String expectedStartTag, BlobXmlRestorer functor) 17036 throws IOException, XmlPullParserException { 17037 int type; 17038 while ((type = parser.next()) != XmlPullParser.START_TAG 17039 && type != XmlPullParser.END_DOCUMENT) { 17040 } 17041 if (type != XmlPullParser.START_TAG) { 17042 // oops didn't find a start tag?! 17043 if (DEBUG_BACKUP) { 17044 Slog.e(TAG, "Didn't find start tag during restore"); 17045 } 17046 return; 17047 } 17048Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17049 // this is supposed to be TAG_PREFERRED_BACKUP 17050 if (!expectedStartTag.equals(parser.getName())) { 17051 if (DEBUG_BACKUP) { 17052 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17053 } 17054 return; 17055 } 17056 17057 // skip interfering stuff, then we're aligned with the backing implementation 17058 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17059Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17060 functor.apply(parser, userId); 17061 } 17062 17063 private interface BlobXmlRestorer { 17064 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17065 } 17066 17067 /** 17068 * Non-Binder method, support for the backup/restore mechanism: write the 17069 * full set of preferred activities in its canonical XML format. Returns the 17070 * XML output as a byte array, or null if there is none. 17071 */ 17072 @Override 17073 public byte[] getPreferredActivityBackup(int userId) { 17074 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17075 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17076 } 17077 17078 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17079 try { 17080 final XmlSerializer serializer = new FastXmlSerializer(); 17081 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17082 serializer.startDocument(null, true); 17083 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17084 17085 synchronized (mPackages) { 17086 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17087 } 17088 17089 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17090 serializer.endDocument(); 17091 serializer.flush(); 17092 } catch (Exception e) { 17093 if (DEBUG_BACKUP) { 17094 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17095 } 17096 return null; 17097 } 17098 17099 return dataStream.toByteArray(); 17100 } 17101 17102 @Override 17103 public void restorePreferredActivities(byte[] backup, int userId) { 17104 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17105 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17106 } 17107 17108 try { 17109 final XmlPullParser parser = Xml.newPullParser(); 17110 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17111 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17112 new BlobXmlRestorer() { 17113 @Override 17114 public void apply(XmlPullParser parser, int userId) 17115 throws XmlPullParserException, IOException { 17116 synchronized (mPackages) { 17117 mSettings.readPreferredActivitiesLPw(parser, userId); 17118 } 17119 } 17120 } ); 17121 } catch (Exception e) { 17122 if (DEBUG_BACKUP) { 17123 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17124 } 17125 } 17126 } 17127 17128 /** 17129 * Non-Binder method, support for the backup/restore mechanism: write the 17130 * default browser (etc) settings in its canonical XML format. Returns the default 17131 * browser XML representation as a byte array, or null if there is none. 17132 */ 17133 @Override 17134 public byte[] getDefaultAppsBackup(int userId) { 17135 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17136 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17137 } 17138 17139 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17140 try { 17141 final XmlSerializer serializer = new FastXmlSerializer(); 17142 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17143 serializer.startDocument(null, true); 17144 serializer.startTag(null, TAG_DEFAULT_APPS); 17145 17146 synchronized (mPackages) { 17147 mSettings.writeDefaultAppsLPr(serializer, userId); 17148 } 17149 17150 serializer.endTag(null, TAG_DEFAULT_APPS); 17151 serializer.endDocument(); 17152 serializer.flush(); 17153 } catch (Exception e) { 17154 if (DEBUG_BACKUP) { 17155 Slog.e(TAG, "Unable to write default apps for backup", e); 17156 } 17157 return null; 17158 } 17159 17160 return dataStream.toByteArray(); 17161 } 17162 17163 @Override 17164 public void restoreDefaultApps(byte[] backup, int userId) { 17165 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17166 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17167 } 17168 17169 try { 17170 final XmlPullParser parser = Xml.newPullParser(); 17171 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17172 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17173 new BlobXmlRestorer() { 17174 @Override 17175 public void apply(XmlPullParser parser, int userId) 17176 throws XmlPullParserException, IOException { 17177 synchronized (mPackages) { 17178 mSettings.readDefaultAppsLPw(parser, userId); 17179 } 17180 } 17181 } ); 17182 } catch (Exception e) { 17183 if (DEBUG_BACKUP) { 17184 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17185 } 17186 } 17187 } 17188 17189 @Override 17190 public byte[] getIntentFilterVerificationBackup(int userId) { 17191 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17192 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17193 } 17194 17195 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17196 try { 17197 final XmlSerializer serializer = new FastXmlSerializer(); 17198 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17199 serializer.startDocument(null, true); 17200 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17201 17202 synchronized (mPackages) { 17203 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17204 } 17205 17206 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17207 serializer.endDocument(); 17208 serializer.flush(); 17209 } catch (Exception e) { 17210 if (DEBUG_BACKUP) { 17211 Slog.e(TAG, "Unable to write default apps for backup", e); 17212 } 17213 return null; 17214 } 17215 17216 return dataStream.toByteArray(); 17217 } 17218 17219 @Override 17220 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17221 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17222 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17223 } 17224 17225 try { 17226 final XmlPullParser parser = Xml.newPullParser(); 17227 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17228 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17229 new BlobXmlRestorer() { 17230 @Override 17231 public void apply(XmlPullParser parser, int userId) 17232 throws XmlPullParserException, IOException { 17233 synchronized (mPackages) { 17234 mSettings.readAllDomainVerificationsLPr(parser, userId); 17235 mSettings.writeLPr(); 17236 } 17237 } 17238 } ); 17239 } catch (Exception e) { 17240 if (DEBUG_BACKUP) { 17241 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17242 } 17243 } 17244 } 17245 17246 @Override 17247 public byte[] getPermissionGrantBackup(int userId) { 17248 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17249 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17250 } 17251 17252 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17253 try { 17254 final XmlSerializer serializer = new FastXmlSerializer(); 17255 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17256 serializer.startDocument(null, true); 17257 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17258 17259 synchronized (mPackages) { 17260 serializeRuntimePermissionGrantsLPr(serializer, userId); 17261 } 17262 17263 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17264 serializer.endDocument(); 17265 serializer.flush(); 17266 } catch (Exception e) { 17267 if (DEBUG_BACKUP) { 17268 Slog.e(TAG, "Unable to write default apps for backup", e); 17269 } 17270 return null; 17271 } 17272 17273 return dataStream.toByteArray(); 17274 } 17275 17276 @Override 17277 public void restorePermissionGrants(byte[] backup, int userId) { 17278 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17279 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17280 } 17281 17282 try { 17283 final XmlPullParser parser = Xml.newPullParser(); 17284 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17285 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17286 new BlobXmlRestorer() { 17287 @Override 17288 public void apply(XmlPullParser parser, int userId) 17289 throws XmlPullParserException, IOException { 17290 synchronized (mPackages) { 17291 processRestoredPermissionGrantsLPr(parser, userId); 17292 } 17293 } 17294 } ); 17295 } catch (Exception e) { 17296 if (DEBUG_BACKUP) { 17297 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17298 } 17299 } 17300 } 17301 17302 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17303 throws IOException { 17304 serializer.startTag(null, TAG_ALL_GRANTS); 17305 17306 final int N = mSettings.mPackages.size(); 17307 for (int i = 0; i < N; i++) { 17308 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17309 boolean pkgGrantsKnown = false; 17310 17311 PermissionsState packagePerms = ps.getPermissionsState(); 17312 17313 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17314 final int grantFlags = state.getFlags(); 17315 // only look at grants that are not system/policy fixed 17316 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17317 final boolean isGranted = state.isGranted(); 17318 // And only back up the user-twiddled state bits 17319 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17320 final String packageName = mSettings.mPackages.keyAt(i); 17321 if (!pkgGrantsKnown) { 17322 serializer.startTag(null, TAG_GRANT); 17323 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17324 pkgGrantsKnown = true; 17325 } 17326 17327 final boolean userSet = 17328 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17329 final boolean userFixed = 17330 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17331 final boolean revoke = 17332 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17333 17334 serializer.startTag(null, TAG_PERMISSION); 17335 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17336 if (isGranted) { 17337 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17338 } 17339 if (userSet) { 17340 serializer.attribute(null, ATTR_USER_SET, "true"); 17341 } 17342 if (userFixed) { 17343 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17344 } 17345 if (revoke) { 17346 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17347 } 17348 serializer.endTag(null, TAG_PERMISSION); 17349 } 17350 } 17351 } 17352 17353 if (pkgGrantsKnown) { 17354 serializer.endTag(null, TAG_GRANT); 17355 } 17356 } 17357 17358 serializer.endTag(null, TAG_ALL_GRANTS); 17359 } 17360 17361 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17362 throws XmlPullParserException, IOException { 17363 String pkgName = null; 17364 int outerDepth = parser.getDepth(); 17365 int type; 17366 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17367 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17368 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17369 continue; 17370 } 17371 17372 final String tagName = parser.getName(); 17373 if (tagName.equals(TAG_GRANT)) { 17374 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17375 if (DEBUG_BACKUP) { 17376 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17377 } 17378 } else if (tagName.equals(TAG_PERMISSION)) { 17379 17380 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17381 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17382 17383 int newFlagSet = 0; 17384 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17385 newFlagSet |= FLAG_PERMISSION_USER_SET; 17386 } 17387 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17388 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17389 } 17390 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17391 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17392 } 17393 if (DEBUG_BACKUP) { 17394 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17395 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17396 } 17397 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17398 if (ps != null) { 17399 // Already installed so we apply the grant immediately 17400 if (DEBUG_BACKUP) { 17401 Slog.v(TAG, " + already installed; applying"); 17402 } 17403 PermissionsState perms = ps.getPermissionsState(); 17404 BasePermission bp = mSettings.mPermissions.get(permName); 17405 if (bp != null) { 17406 if (isGranted) { 17407 perms.grantRuntimePermission(bp, userId); 17408 } 17409 if (newFlagSet != 0) { 17410 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17411 } 17412 } 17413 } else { 17414 // Need to wait for post-restore install to apply the grant 17415 if (DEBUG_BACKUP) { 17416 Slog.v(TAG, " - not yet installed; saving for later"); 17417 } 17418 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17419 isGranted, newFlagSet, userId); 17420 } 17421 } else { 17422 PackageManagerService.reportSettingsProblem(Log.WARN, 17423 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17424 XmlUtils.skipCurrentTag(parser); 17425 } 17426 } 17427 17428 scheduleWriteSettingsLocked(); 17429 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17430 } 17431 17432 @Override 17433 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17434 int sourceUserId, int targetUserId, int flags) { 17435 mContext.enforceCallingOrSelfPermission( 17436 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17437 int callingUid = Binder.getCallingUid(); 17438 enforceOwnerRights(ownerPackage, callingUid); 17439 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17440 if (intentFilter.countActions() == 0) { 17441 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17442 return; 17443 } 17444 synchronized (mPackages) { 17445 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17446 ownerPackage, targetUserId, flags); 17447 CrossProfileIntentResolver resolver = 17448 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17449 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17450 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17451 if (existing != null) { 17452 int size = existing.size(); 17453 for (int i = 0; i < size; i++) { 17454 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17455 return; 17456 } 17457 } 17458 } 17459 resolver.addFilter(newFilter); 17460 scheduleWritePackageRestrictionsLocked(sourceUserId); 17461 } 17462 } 17463 17464 @Override 17465 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17466 mContext.enforceCallingOrSelfPermission( 17467 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17468 int callingUid = Binder.getCallingUid(); 17469 enforceOwnerRights(ownerPackage, callingUid); 17470 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17471 synchronized (mPackages) { 17472 CrossProfileIntentResolver resolver = 17473 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17474 ArraySet<CrossProfileIntentFilter> set = 17475 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17476 for (CrossProfileIntentFilter filter : set) { 17477 if (filter.getOwnerPackage().equals(ownerPackage)) { 17478 resolver.removeFilter(filter); 17479 } 17480 } 17481 scheduleWritePackageRestrictionsLocked(sourceUserId); 17482 } 17483 } 17484 17485 // Enforcing that callingUid is owning pkg on userId 17486 private void enforceOwnerRights(String pkg, int callingUid) { 17487 // The system owns everything. 17488 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17489 return; 17490 } 17491 int callingUserId = UserHandle.getUserId(callingUid); 17492 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17493 if (pi == null) { 17494 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17495 + callingUserId); 17496 } 17497 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17498 throw new SecurityException("Calling uid " + callingUid 17499 + " does not own package " + pkg); 17500 } 17501 } 17502 17503 @Override 17504 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17505 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17506 } 17507 17508 private Intent getHomeIntent() { 17509 Intent intent = new Intent(Intent.ACTION_MAIN); 17510 intent.addCategory(Intent.CATEGORY_HOME); 17511 intent.addCategory(Intent.CATEGORY_DEFAULT); 17512 return intent; 17513 } 17514 17515 private IntentFilter getHomeFilter() { 17516 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17517 filter.addCategory(Intent.CATEGORY_HOME); 17518 filter.addCategory(Intent.CATEGORY_DEFAULT); 17519 return filter; 17520 } 17521 17522 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17523 int userId) { 17524 Intent intent = getHomeIntent(); 17525 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17526 PackageManager.GET_META_DATA, userId); 17527 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17528 true, false, false, userId); 17529 17530 allHomeCandidates.clear(); 17531 if (list != null) { 17532 for (ResolveInfo ri : list) { 17533 allHomeCandidates.add(ri); 17534 } 17535 } 17536 return (preferred == null || preferred.activityInfo == null) 17537 ? null 17538 : new ComponentName(preferred.activityInfo.packageName, 17539 preferred.activityInfo.name); 17540 } 17541 17542 @Override 17543 public void setHomeActivity(ComponentName comp, int userId) { 17544 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17545 getHomeActivitiesAsUser(homeActivities, userId); 17546 17547 boolean found = false; 17548 17549 final int size = homeActivities.size(); 17550 final ComponentName[] set = new ComponentName[size]; 17551 for (int i = 0; i < size; i++) { 17552 final ResolveInfo candidate = homeActivities.get(i); 17553 final ActivityInfo info = candidate.activityInfo; 17554 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17555 set[i] = activityName; 17556 if (!found && activityName.equals(comp)) { 17557 found = true; 17558 } 17559 } 17560 if (!found) { 17561 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17562 + userId); 17563 } 17564 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17565 set, comp, userId); 17566 } 17567 17568 private @Nullable String getSetupWizardPackageName() { 17569 final Intent intent = new Intent(Intent.ACTION_MAIN); 17570 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17571 17572 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17573 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17574 | MATCH_DISABLED_COMPONENTS, 17575 UserHandle.myUserId()); 17576 if (matches.size() == 1) { 17577 return matches.get(0).getComponentInfo().packageName; 17578 } else { 17579 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17580 + ": matches=" + matches); 17581 return null; 17582 } 17583 } 17584 17585 @Override 17586 public void setApplicationEnabledSetting(String appPackageName, 17587 int newState, int flags, int userId, String callingPackage) { 17588 if (!sUserManager.exists(userId)) return; 17589 if (callingPackage == null) { 17590 callingPackage = Integer.toString(Binder.getCallingUid()); 17591 } 17592 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17593 } 17594 17595 @Override 17596 public void setComponentEnabledSetting(ComponentName componentName, 17597 int newState, int flags, int userId) { 17598 if (!sUserManager.exists(userId)) return; 17599 setEnabledSetting(componentName.getPackageName(), 17600 componentName.getClassName(), newState, flags, userId, null); 17601 } 17602 17603 private void setEnabledSetting(final String packageName, String className, int newState, 17604 final int flags, int userId, String callingPackage) { 17605 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17606 || newState == COMPONENT_ENABLED_STATE_ENABLED 17607 || newState == COMPONENT_ENABLED_STATE_DISABLED 17608 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17609 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17610 throw new IllegalArgumentException("Invalid new component state: " 17611 + newState); 17612 } 17613 PackageSetting pkgSetting; 17614 final int uid = Binder.getCallingUid(); 17615 final int permission; 17616 if (uid == Process.SYSTEM_UID) { 17617 permission = PackageManager.PERMISSION_GRANTED; 17618 } else { 17619 permission = mContext.checkCallingOrSelfPermission( 17620 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17621 } 17622 enforceCrossUserPermission(uid, userId, 17623 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17624 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17625 boolean sendNow = false; 17626 boolean isApp = (className == null); 17627 String componentName = isApp ? packageName : className; 17628 int packageUid = -1; 17629 ArrayList<String> components; 17630 17631 // writer 17632 synchronized (mPackages) { 17633 pkgSetting = mSettings.mPackages.get(packageName); 17634 if (pkgSetting == null) { 17635 if (className == null) { 17636 throw new IllegalArgumentException("Unknown package: " + packageName); 17637 } 17638 throw new IllegalArgumentException( 17639 "Unknown component: " + packageName + "/" + className); 17640 } 17641 } 17642 17643 // Limit who can change which apps 17644 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17645 // Don't allow apps that don't have permission to modify other apps 17646 if (!allowedByPermission) { 17647 throw new SecurityException( 17648 "Permission Denial: attempt to change component state from pid=" 17649 + Binder.getCallingPid() 17650 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17651 } 17652 // Don't allow changing protected packages. 17653 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17654 throw new SecurityException("Cannot disable a protected package: " + packageName); 17655 } 17656 } 17657 17658 synchronized (mPackages) { 17659 if (uid == Process.SHELL_UID) { 17660 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17661 int oldState = pkgSetting.getEnabled(userId); 17662 if (className == null 17663 && 17664 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17665 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17666 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17667 && 17668 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17669 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17670 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17671 // ok 17672 } else { 17673 throw new SecurityException( 17674 "Shell cannot change component state for " + packageName + "/" 17675 + className + " to " + newState); 17676 } 17677 } 17678 if (className == null) { 17679 // We're dealing with an application/package level state change 17680 if (pkgSetting.getEnabled(userId) == newState) { 17681 // Nothing to do 17682 return; 17683 } 17684 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17685 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17686 // Don't care about who enables an app. 17687 callingPackage = null; 17688 } 17689 pkgSetting.setEnabled(newState, userId, callingPackage); 17690 // pkgSetting.pkg.mSetEnabled = newState; 17691 } else { 17692 // We're dealing with a component level state change 17693 // First, verify that this is a valid class name. 17694 PackageParser.Package pkg = pkgSetting.pkg; 17695 if (pkg == null || !pkg.hasComponentClassName(className)) { 17696 if (pkg != null && 17697 pkg.applicationInfo.targetSdkVersion >= 17698 Build.VERSION_CODES.JELLY_BEAN) { 17699 throw new IllegalArgumentException("Component class " + className 17700 + " does not exist in " + packageName); 17701 } else { 17702 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17703 + className + " does not exist in " + packageName); 17704 } 17705 } 17706 switch (newState) { 17707 case COMPONENT_ENABLED_STATE_ENABLED: 17708 if (!pkgSetting.enableComponentLPw(className, userId)) { 17709 return; 17710 } 17711 break; 17712 case COMPONENT_ENABLED_STATE_DISABLED: 17713 if (!pkgSetting.disableComponentLPw(className, userId)) { 17714 return; 17715 } 17716 break; 17717 case COMPONENT_ENABLED_STATE_DEFAULT: 17718 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17719 return; 17720 } 17721 break; 17722 default: 17723 Slog.e(TAG, "Invalid new component state: " + newState); 17724 return; 17725 } 17726 } 17727 scheduleWritePackageRestrictionsLocked(userId); 17728 components = mPendingBroadcasts.get(userId, packageName); 17729 final boolean newPackage = components == null; 17730 if (newPackage) { 17731 components = new ArrayList<String>(); 17732 } 17733 if (!components.contains(componentName)) { 17734 components.add(componentName); 17735 } 17736 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17737 sendNow = true; 17738 // Purge entry from pending broadcast list if another one exists already 17739 // since we are sending one right away. 17740 mPendingBroadcasts.remove(userId, packageName); 17741 } else { 17742 if (newPackage) { 17743 mPendingBroadcasts.put(userId, packageName, components); 17744 } 17745 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17746 // Schedule a message 17747 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17748 } 17749 } 17750 } 17751 17752 long callingId = Binder.clearCallingIdentity(); 17753 try { 17754 if (sendNow) { 17755 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17756 sendPackageChangedBroadcast(packageName, 17757 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17758 } 17759 } finally { 17760 Binder.restoreCallingIdentity(callingId); 17761 } 17762 } 17763 17764 @Override 17765 public void flushPackageRestrictionsAsUser(int userId) { 17766 if (!sUserManager.exists(userId)) { 17767 return; 17768 } 17769 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17770 false /* checkShell */, "flushPackageRestrictions"); 17771 synchronized (mPackages) { 17772 mSettings.writePackageRestrictionsLPr(userId); 17773 mDirtyUsers.remove(userId); 17774 if (mDirtyUsers.isEmpty()) { 17775 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17776 } 17777 } 17778 } 17779 17780 private void sendPackageChangedBroadcast(String packageName, 17781 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17782 if (DEBUG_INSTALL) 17783 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17784 + componentNames); 17785 Bundle extras = new Bundle(4); 17786 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17787 String nameList[] = new String[componentNames.size()]; 17788 componentNames.toArray(nameList); 17789 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17790 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17791 extras.putInt(Intent.EXTRA_UID, packageUid); 17792 // If this is not reporting a change of the overall package, then only send it 17793 // to registered receivers. We don't want to launch a swath of apps for every 17794 // little component state change. 17795 final int flags = !componentNames.contains(packageName) 17796 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17797 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17798 new int[] {UserHandle.getUserId(packageUid)}); 17799 } 17800 17801 @Override 17802 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17803 if (!sUserManager.exists(userId)) return; 17804 final int uid = Binder.getCallingUid(); 17805 final int permission = mContext.checkCallingOrSelfPermission( 17806 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17807 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17808 enforceCrossUserPermission(uid, userId, 17809 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17810 // writer 17811 synchronized (mPackages) { 17812 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17813 allowedByPermission, uid, userId)) { 17814 scheduleWritePackageRestrictionsLocked(userId); 17815 } 17816 } 17817 } 17818 17819 @Override 17820 public String getInstallerPackageName(String packageName) { 17821 // reader 17822 synchronized (mPackages) { 17823 return mSettings.getInstallerPackageNameLPr(packageName); 17824 } 17825 } 17826 17827 public boolean isOrphaned(String packageName) { 17828 // reader 17829 synchronized (mPackages) { 17830 return mSettings.isOrphaned(packageName); 17831 } 17832 } 17833 17834 @Override 17835 public int getApplicationEnabledSetting(String packageName, int userId) { 17836 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17837 int uid = Binder.getCallingUid(); 17838 enforceCrossUserPermission(uid, userId, 17839 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17840 // reader 17841 synchronized (mPackages) { 17842 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17843 } 17844 } 17845 17846 @Override 17847 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17848 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17849 int uid = Binder.getCallingUid(); 17850 enforceCrossUserPermission(uid, userId, 17851 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17852 // reader 17853 synchronized (mPackages) { 17854 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17855 } 17856 } 17857 17858 @Override 17859 public void enterSafeMode() { 17860 enforceSystemOrRoot("Only the system can request entering safe mode"); 17861 17862 if (!mSystemReady) { 17863 mSafeMode = true; 17864 } 17865 } 17866 17867 @Override 17868 public void systemReady() { 17869 mSystemReady = true; 17870 17871 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 17872 // disabled after already being started. 17873 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 17874 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 17875 17876 // Read the compatibilty setting when the system is ready. 17877 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17878 mContext.getContentResolver(), 17879 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17880 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17881 if (DEBUG_SETTINGS) { 17882 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17883 } 17884 17885 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17886 17887 synchronized (mPackages) { 17888 // Verify that all of the preferred activity components actually 17889 // exist. It is possible for applications to be updated and at 17890 // that point remove a previously declared activity component that 17891 // had been set as a preferred activity. We try to clean this up 17892 // the next time we encounter that preferred activity, but it is 17893 // possible for the user flow to never be able to return to that 17894 // situation so here we do a sanity check to make sure we haven't 17895 // left any junk around. 17896 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17897 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17898 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17899 removed.clear(); 17900 for (PreferredActivity pa : pir.filterSet()) { 17901 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17902 removed.add(pa); 17903 } 17904 } 17905 if (removed.size() > 0) { 17906 for (int r=0; r<removed.size(); r++) { 17907 PreferredActivity pa = removed.get(r); 17908 Slog.w(TAG, "Removing dangling preferred activity: " 17909 + pa.mPref.mComponent); 17910 pir.removeFilter(pa); 17911 } 17912 mSettings.writePackageRestrictionsLPr( 17913 mSettings.mPreferredActivities.keyAt(i)); 17914 } 17915 } 17916 17917 for (int userId : UserManagerService.getInstance().getUserIds()) { 17918 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17919 grantPermissionsUserIds = ArrayUtils.appendInt( 17920 grantPermissionsUserIds, userId); 17921 } 17922 } 17923 } 17924 sUserManager.systemReady(); 17925 17926 // If we upgraded grant all default permissions before kicking off. 17927 for (int userId : grantPermissionsUserIds) { 17928 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17929 } 17930 17931 // Kick off any messages waiting for system ready 17932 if (mPostSystemReadyMessages != null) { 17933 for (Message msg : mPostSystemReadyMessages) { 17934 msg.sendToTarget(); 17935 } 17936 mPostSystemReadyMessages = null; 17937 } 17938 17939 // Watch for external volumes that come and go over time 17940 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17941 storage.registerListener(mStorageListener); 17942 17943 mInstallerService.systemReady(); 17944 mPackageDexOptimizer.systemReady(); 17945 17946 MountServiceInternal mountServiceInternal = LocalServices.getService( 17947 MountServiceInternal.class); 17948 mountServiceInternal.addExternalStoragePolicy( 17949 new MountServiceInternal.ExternalStorageMountPolicy() { 17950 @Override 17951 public int getMountMode(int uid, String packageName) { 17952 if (Process.isIsolated(uid)) { 17953 return Zygote.MOUNT_EXTERNAL_NONE; 17954 } 17955 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17956 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17957 } 17958 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17959 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17960 } 17961 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17962 return Zygote.MOUNT_EXTERNAL_READ; 17963 } 17964 return Zygote.MOUNT_EXTERNAL_WRITE; 17965 } 17966 17967 @Override 17968 public boolean hasExternalStorage(int uid, String packageName) { 17969 return true; 17970 } 17971 }); 17972 17973 // Now that we're mostly running, clean up stale users and apps 17974 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17975 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17976 } 17977 17978 @Override 17979 public boolean isSafeMode() { 17980 return mSafeMode; 17981 } 17982 17983 @Override 17984 public boolean hasSystemUidErrors() { 17985 return mHasSystemUidErrors; 17986 } 17987 17988 static String arrayToString(int[] array) { 17989 StringBuffer buf = new StringBuffer(128); 17990 buf.append('['); 17991 if (array != null) { 17992 for (int i=0; i<array.length; i++) { 17993 if (i > 0) buf.append(", "); 17994 buf.append(array[i]); 17995 } 17996 } 17997 buf.append(']'); 17998 return buf.toString(); 17999 } 18000 18001 static class DumpState { 18002 public static final int DUMP_LIBS = 1 << 0; 18003 public static final int DUMP_FEATURES = 1 << 1; 18004 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18005 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18006 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18007 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18008 public static final int DUMP_PERMISSIONS = 1 << 6; 18009 public static final int DUMP_PACKAGES = 1 << 7; 18010 public static final int DUMP_SHARED_USERS = 1 << 8; 18011 public static final int DUMP_MESSAGES = 1 << 9; 18012 public static final int DUMP_PROVIDERS = 1 << 10; 18013 public static final int DUMP_VERIFIERS = 1 << 11; 18014 public static final int DUMP_PREFERRED = 1 << 12; 18015 public static final int DUMP_PREFERRED_XML = 1 << 13; 18016 public static final int DUMP_KEYSETS = 1 << 14; 18017 public static final int DUMP_VERSION = 1 << 15; 18018 public static final int DUMP_INSTALLS = 1 << 16; 18019 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18020 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18021 public static final int DUMP_FROZEN = 1 << 19; 18022 public static final int DUMP_DEXOPT = 1 << 20; 18023 public static final int DUMP_COMPILER_STATS = 1 << 21; 18024 18025 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18026 18027 private int mTypes; 18028 18029 private int mOptions; 18030 18031 private boolean mTitlePrinted; 18032 18033 private SharedUserSetting mSharedUser; 18034 18035 public boolean isDumping(int type) { 18036 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18037 return true; 18038 } 18039 18040 return (mTypes & type) != 0; 18041 } 18042 18043 public void setDump(int type) { 18044 mTypes |= type; 18045 } 18046 18047 public boolean isOptionEnabled(int option) { 18048 return (mOptions & option) != 0; 18049 } 18050 18051 public void setOptionEnabled(int option) { 18052 mOptions |= option; 18053 } 18054 18055 public boolean onTitlePrinted() { 18056 final boolean printed = mTitlePrinted; 18057 mTitlePrinted = true; 18058 return printed; 18059 } 18060 18061 public boolean getTitlePrinted() { 18062 return mTitlePrinted; 18063 } 18064 18065 public void setTitlePrinted(boolean enabled) { 18066 mTitlePrinted = enabled; 18067 } 18068 18069 public SharedUserSetting getSharedUser() { 18070 return mSharedUser; 18071 } 18072 18073 public void setSharedUser(SharedUserSetting user) { 18074 mSharedUser = user; 18075 } 18076 } 18077 18078 @Override 18079 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18080 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18081 (new PackageManagerShellCommand(this)).exec( 18082 this, in, out, err, args, resultReceiver); 18083 } 18084 18085 @Override 18086 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18087 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18088 != PackageManager.PERMISSION_GRANTED) { 18089 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18090 + Binder.getCallingPid() 18091 + ", uid=" + Binder.getCallingUid() 18092 + " without permission " 18093 + android.Manifest.permission.DUMP); 18094 return; 18095 } 18096 18097 DumpState dumpState = new DumpState(); 18098 boolean fullPreferred = false; 18099 boolean checkin = false; 18100 18101 String packageName = null; 18102 ArraySet<String> permissionNames = null; 18103 18104 int opti = 0; 18105 while (opti < args.length) { 18106 String opt = args[opti]; 18107 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18108 break; 18109 } 18110 opti++; 18111 18112 if ("-a".equals(opt)) { 18113 // Right now we only know how to print all. 18114 } else if ("-h".equals(opt)) { 18115 pw.println("Package manager dump options:"); 18116 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18117 pw.println(" --checkin: dump for a checkin"); 18118 pw.println(" -f: print details of intent filters"); 18119 pw.println(" -h: print this help"); 18120 pw.println(" cmd may be one of:"); 18121 pw.println(" l[ibraries]: list known shared libraries"); 18122 pw.println(" f[eatures]: list device features"); 18123 pw.println(" k[eysets]: print known keysets"); 18124 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18125 pw.println(" perm[issions]: dump permissions"); 18126 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18127 pw.println(" pref[erred]: print preferred package settings"); 18128 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18129 pw.println(" prov[iders]: dump content providers"); 18130 pw.println(" p[ackages]: dump installed packages"); 18131 pw.println(" s[hared-users]: dump shared user IDs"); 18132 pw.println(" m[essages]: print collected runtime messages"); 18133 pw.println(" v[erifiers]: print package verifier info"); 18134 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18135 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18136 pw.println(" version: print database version info"); 18137 pw.println(" write: write current settings now"); 18138 pw.println(" installs: details about install sessions"); 18139 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18140 pw.println(" dexopt: dump dexopt state"); 18141 pw.println(" compiler-stats: dump compiler statistics"); 18142 pw.println(" <package.name>: info about given package"); 18143 return; 18144 } else if ("--checkin".equals(opt)) { 18145 checkin = true; 18146 } else if ("-f".equals(opt)) { 18147 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18148 } else { 18149 pw.println("Unknown argument: " + opt + "; use -h for help"); 18150 } 18151 } 18152 18153 // Is the caller requesting to dump a particular piece of data? 18154 if (opti < args.length) { 18155 String cmd = args[opti]; 18156 opti++; 18157 // Is this a package name? 18158 if ("android".equals(cmd) || cmd.contains(".")) { 18159 packageName = cmd; 18160 // When dumping a single package, we always dump all of its 18161 // filter information since the amount of data will be reasonable. 18162 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18163 } else if ("check-permission".equals(cmd)) { 18164 if (opti >= args.length) { 18165 pw.println("Error: check-permission missing permission argument"); 18166 return; 18167 } 18168 String perm = args[opti]; 18169 opti++; 18170 if (opti >= args.length) { 18171 pw.println("Error: check-permission missing package argument"); 18172 return; 18173 } 18174 String pkg = args[opti]; 18175 opti++; 18176 int user = UserHandle.getUserId(Binder.getCallingUid()); 18177 if (opti < args.length) { 18178 try { 18179 user = Integer.parseInt(args[opti]); 18180 } catch (NumberFormatException e) { 18181 pw.println("Error: check-permission user argument is not a number: " 18182 + args[opti]); 18183 return; 18184 } 18185 } 18186 pw.println(checkPermission(perm, pkg, user)); 18187 return; 18188 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18189 dumpState.setDump(DumpState.DUMP_LIBS); 18190 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18191 dumpState.setDump(DumpState.DUMP_FEATURES); 18192 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18193 if (opti >= args.length) { 18194 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18195 | DumpState.DUMP_SERVICE_RESOLVERS 18196 | DumpState.DUMP_RECEIVER_RESOLVERS 18197 | DumpState.DUMP_CONTENT_RESOLVERS); 18198 } else { 18199 while (opti < args.length) { 18200 String name = args[opti]; 18201 if ("a".equals(name) || "activity".equals(name)) { 18202 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18203 } else if ("s".equals(name) || "service".equals(name)) { 18204 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18205 } else if ("r".equals(name) || "receiver".equals(name)) { 18206 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18207 } else if ("c".equals(name) || "content".equals(name)) { 18208 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18209 } else { 18210 pw.println("Error: unknown resolver table type: " + name); 18211 return; 18212 } 18213 opti++; 18214 } 18215 } 18216 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18217 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18218 } else if ("permission".equals(cmd)) { 18219 if (opti >= args.length) { 18220 pw.println("Error: permission requires permission name"); 18221 return; 18222 } 18223 permissionNames = new ArraySet<>(); 18224 while (opti < args.length) { 18225 permissionNames.add(args[opti]); 18226 opti++; 18227 } 18228 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18229 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18230 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18231 dumpState.setDump(DumpState.DUMP_PREFERRED); 18232 } else if ("preferred-xml".equals(cmd)) { 18233 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18234 if (opti < args.length && "--full".equals(args[opti])) { 18235 fullPreferred = true; 18236 opti++; 18237 } 18238 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18239 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18240 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18241 dumpState.setDump(DumpState.DUMP_PACKAGES); 18242 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18243 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18244 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18245 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18246 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18247 dumpState.setDump(DumpState.DUMP_MESSAGES); 18248 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18249 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18250 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18251 || "intent-filter-verifiers".equals(cmd)) { 18252 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18253 } else if ("version".equals(cmd)) { 18254 dumpState.setDump(DumpState.DUMP_VERSION); 18255 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18256 dumpState.setDump(DumpState.DUMP_KEYSETS); 18257 } else if ("installs".equals(cmd)) { 18258 dumpState.setDump(DumpState.DUMP_INSTALLS); 18259 } else if ("frozen".equals(cmd)) { 18260 dumpState.setDump(DumpState.DUMP_FROZEN); 18261 } else if ("dexopt".equals(cmd)) { 18262 dumpState.setDump(DumpState.DUMP_DEXOPT); 18263 } else if ("compiler-stats".equals(cmd)) { 18264 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 18265 } else if ("write".equals(cmd)) { 18266 synchronized (mPackages) { 18267 mSettings.writeLPr(); 18268 pw.println("Settings written."); 18269 return; 18270 } 18271 } 18272 } 18273 18274 if (checkin) { 18275 pw.println("vers,1"); 18276 } 18277 18278 // reader 18279 synchronized (mPackages) { 18280 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18281 if (!checkin) { 18282 if (dumpState.onTitlePrinted()) 18283 pw.println(); 18284 pw.println("Database versions:"); 18285 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18286 } 18287 } 18288 18289 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18290 if (!checkin) { 18291 if (dumpState.onTitlePrinted()) 18292 pw.println(); 18293 pw.println("Verifiers:"); 18294 pw.print(" Required: "); 18295 pw.print(mRequiredVerifierPackage); 18296 pw.print(" (uid="); 18297 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18298 UserHandle.USER_SYSTEM)); 18299 pw.println(")"); 18300 } else if (mRequiredVerifierPackage != null) { 18301 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18302 pw.print(","); 18303 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18304 UserHandle.USER_SYSTEM)); 18305 } 18306 } 18307 18308 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18309 packageName == null) { 18310 if (mIntentFilterVerifierComponent != null) { 18311 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18312 if (!checkin) { 18313 if (dumpState.onTitlePrinted()) 18314 pw.println(); 18315 pw.println("Intent Filter Verifier:"); 18316 pw.print(" Using: "); 18317 pw.print(verifierPackageName); 18318 pw.print(" (uid="); 18319 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18320 UserHandle.USER_SYSTEM)); 18321 pw.println(")"); 18322 } else if (verifierPackageName != null) { 18323 pw.print("ifv,"); pw.print(verifierPackageName); 18324 pw.print(","); 18325 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18326 UserHandle.USER_SYSTEM)); 18327 } 18328 } else { 18329 pw.println(); 18330 pw.println("No Intent Filter Verifier available!"); 18331 } 18332 } 18333 18334 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18335 boolean printedHeader = false; 18336 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18337 while (it.hasNext()) { 18338 String name = it.next(); 18339 SharedLibraryEntry ent = mSharedLibraries.get(name); 18340 if (!checkin) { 18341 if (!printedHeader) { 18342 if (dumpState.onTitlePrinted()) 18343 pw.println(); 18344 pw.println("Libraries:"); 18345 printedHeader = true; 18346 } 18347 pw.print(" "); 18348 } else { 18349 pw.print("lib,"); 18350 } 18351 pw.print(name); 18352 if (!checkin) { 18353 pw.print(" -> "); 18354 } 18355 if (ent.path != null) { 18356 if (!checkin) { 18357 pw.print("(jar) "); 18358 pw.print(ent.path); 18359 } else { 18360 pw.print(",jar,"); 18361 pw.print(ent.path); 18362 } 18363 } else { 18364 if (!checkin) { 18365 pw.print("(apk) "); 18366 pw.print(ent.apk); 18367 } else { 18368 pw.print(",apk,"); 18369 pw.print(ent.apk); 18370 } 18371 } 18372 pw.println(); 18373 } 18374 } 18375 18376 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18377 if (dumpState.onTitlePrinted()) 18378 pw.println(); 18379 if (!checkin) { 18380 pw.println("Features:"); 18381 } 18382 18383 for (FeatureInfo feat : mAvailableFeatures.values()) { 18384 if (checkin) { 18385 pw.print("feat,"); 18386 pw.print(feat.name); 18387 pw.print(","); 18388 pw.println(feat.version); 18389 } else { 18390 pw.print(" "); 18391 pw.print(feat.name); 18392 if (feat.version > 0) { 18393 pw.print(" version="); 18394 pw.print(feat.version); 18395 } 18396 pw.println(); 18397 } 18398 } 18399 } 18400 18401 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18402 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18403 : "Activity Resolver Table:", " ", packageName, 18404 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18405 dumpState.setTitlePrinted(true); 18406 } 18407 } 18408 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18409 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18410 : "Receiver Resolver Table:", " ", packageName, 18411 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18412 dumpState.setTitlePrinted(true); 18413 } 18414 } 18415 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18416 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18417 : "Service Resolver Table:", " ", packageName, 18418 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18419 dumpState.setTitlePrinted(true); 18420 } 18421 } 18422 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18423 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18424 : "Provider Resolver Table:", " ", packageName, 18425 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18426 dumpState.setTitlePrinted(true); 18427 } 18428 } 18429 18430 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18431 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18432 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18433 int user = mSettings.mPreferredActivities.keyAt(i); 18434 if (pir.dump(pw, 18435 dumpState.getTitlePrinted() 18436 ? "\nPreferred Activities User " + user + ":" 18437 : "Preferred Activities User " + user + ":", " ", 18438 packageName, true, false)) { 18439 dumpState.setTitlePrinted(true); 18440 } 18441 } 18442 } 18443 18444 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18445 pw.flush(); 18446 FileOutputStream fout = new FileOutputStream(fd); 18447 BufferedOutputStream str = new BufferedOutputStream(fout); 18448 XmlSerializer serializer = new FastXmlSerializer(); 18449 try { 18450 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18451 serializer.startDocument(null, true); 18452 serializer.setFeature( 18453 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18454 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18455 serializer.endDocument(); 18456 serializer.flush(); 18457 } catch (IllegalArgumentException e) { 18458 pw.println("Failed writing: " + e); 18459 } catch (IllegalStateException e) { 18460 pw.println("Failed writing: " + e); 18461 } catch (IOException e) { 18462 pw.println("Failed writing: " + e); 18463 } 18464 } 18465 18466 if (!checkin 18467 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18468 && packageName == null) { 18469 pw.println(); 18470 int count = mSettings.mPackages.size(); 18471 if (count == 0) { 18472 pw.println("No applications!"); 18473 pw.println(); 18474 } else { 18475 final String prefix = " "; 18476 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18477 if (allPackageSettings.size() == 0) { 18478 pw.println("No domain preferred apps!"); 18479 pw.println(); 18480 } else { 18481 pw.println("App verification status:"); 18482 pw.println(); 18483 count = 0; 18484 for (PackageSetting ps : allPackageSettings) { 18485 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18486 if (ivi == null || ivi.getPackageName() == null) continue; 18487 pw.println(prefix + "Package: " + ivi.getPackageName()); 18488 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18489 pw.println(prefix + "Status: " + ivi.getStatusString()); 18490 pw.println(); 18491 count++; 18492 } 18493 if (count == 0) { 18494 pw.println(prefix + "No app verification established."); 18495 pw.println(); 18496 } 18497 for (int userId : sUserManager.getUserIds()) { 18498 pw.println("App linkages for user " + userId + ":"); 18499 pw.println(); 18500 count = 0; 18501 for (PackageSetting ps : allPackageSettings) { 18502 final long status = ps.getDomainVerificationStatusForUser(userId); 18503 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18504 continue; 18505 } 18506 pw.println(prefix + "Package: " + ps.name); 18507 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18508 String statusStr = IntentFilterVerificationInfo. 18509 getStatusStringFromValue(status); 18510 pw.println(prefix + "Status: " + statusStr); 18511 pw.println(); 18512 count++; 18513 } 18514 if (count == 0) { 18515 pw.println(prefix + "No configured app linkages."); 18516 pw.println(); 18517 } 18518 } 18519 } 18520 } 18521 } 18522 18523 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18524 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18525 if (packageName == null && permissionNames == null) { 18526 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18527 if (iperm == 0) { 18528 if (dumpState.onTitlePrinted()) 18529 pw.println(); 18530 pw.println("AppOp Permissions:"); 18531 } 18532 pw.print(" AppOp Permission "); 18533 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18534 pw.println(":"); 18535 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18536 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18537 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18538 } 18539 } 18540 } 18541 } 18542 18543 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18544 boolean printedSomething = false; 18545 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18546 if (packageName != null && !packageName.equals(p.info.packageName)) { 18547 continue; 18548 } 18549 if (!printedSomething) { 18550 if (dumpState.onTitlePrinted()) 18551 pw.println(); 18552 pw.println("Registered ContentProviders:"); 18553 printedSomething = true; 18554 } 18555 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18556 pw.print(" "); pw.println(p.toString()); 18557 } 18558 printedSomething = false; 18559 for (Map.Entry<String, PackageParser.Provider> entry : 18560 mProvidersByAuthority.entrySet()) { 18561 PackageParser.Provider p = entry.getValue(); 18562 if (packageName != null && !packageName.equals(p.info.packageName)) { 18563 continue; 18564 } 18565 if (!printedSomething) { 18566 if (dumpState.onTitlePrinted()) 18567 pw.println(); 18568 pw.println("ContentProvider Authorities:"); 18569 printedSomething = true; 18570 } 18571 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18572 pw.print(" "); pw.println(p.toString()); 18573 if (p.info != null && p.info.applicationInfo != null) { 18574 final String appInfo = p.info.applicationInfo.toString(); 18575 pw.print(" applicationInfo="); pw.println(appInfo); 18576 } 18577 } 18578 } 18579 18580 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18581 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18582 } 18583 18584 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18585 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18586 } 18587 18588 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18589 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18590 } 18591 18592 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18593 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18594 } 18595 18596 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18597 // XXX should handle packageName != null by dumping only install data that 18598 // the given package is involved with. 18599 if (dumpState.onTitlePrinted()) pw.println(); 18600 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18601 } 18602 18603 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18604 // XXX should handle packageName != null by dumping only install data that 18605 // the given package is involved with. 18606 if (dumpState.onTitlePrinted()) pw.println(); 18607 18608 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18609 ipw.println(); 18610 ipw.println("Frozen packages:"); 18611 ipw.increaseIndent(); 18612 if (mFrozenPackages.size() == 0) { 18613 ipw.println("(none)"); 18614 } else { 18615 for (int i = 0; i < mFrozenPackages.size(); i++) { 18616 ipw.println(mFrozenPackages.valueAt(i)); 18617 } 18618 } 18619 ipw.decreaseIndent(); 18620 } 18621 18622 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18623 if (dumpState.onTitlePrinted()) pw.println(); 18624 dumpDexoptStateLPr(pw, packageName); 18625 } 18626 18627 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 18628 if (dumpState.onTitlePrinted()) pw.println(); 18629 dumpCompilerStatsLPr(pw, packageName); 18630 } 18631 18632 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18633 if (dumpState.onTitlePrinted()) pw.println(); 18634 mSettings.dumpReadMessagesLPr(pw, dumpState); 18635 18636 pw.println(); 18637 pw.println("Package warning messages:"); 18638 BufferedReader in = null; 18639 String line = null; 18640 try { 18641 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18642 while ((line = in.readLine()) != null) { 18643 if (line.contains("ignored: updated version")) continue; 18644 pw.println(line); 18645 } 18646 } catch (IOException ignored) { 18647 } finally { 18648 IoUtils.closeQuietly(in); 18649 } 18650 } 18651 18652 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18653 BufferedReader in = null; 18654 String line = null; 18655 try { 18656 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18657 while ((line = in.readLine()) != null) { 18658 if (line.contains("ignored: updated version")) continue; 18659 pw.print("msg,"); 18660 pw.println(line); 18661 } 18662 } catch (IOException ignored) { 18663 } finally { 18664 IoUtils.closeQuietly(in); 18665 } 18666 } 18667 } 18668 } 18669 18670 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18671 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18672 ipw.println(); 18673 ipw.println("Dexopt state:"); 18674 ipw.increaseIndent(); 18675 Collection<PackageParser.Package> packages = null; 18676 if (packageName != null) { 18677 PackageParser.Package targetPackage = mPackages.get(packageName); 18678 if (targetPackage != null) { 18679 packages = Collections.singletonList(targetPackage); 18680 } else { 18681 ipw.println("Unable to find package: " + packageName); 18682 return; 18683 } 18684 } else { 18685 packages = mPackages.values(); 18686 } 18687 18688 for (PackageParser.Package pkg : packages) { 18689 ipw.println("[" + pkg.packageName + "]"); 18690 ipw.increaseIndent(); 18691 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18692 ipw.decreaseIndent(); 18693 } 18694 } 18695 18696 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 18697 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18698 ipw.println(); 18699 ipw.println("Compiler stats:"); 18700 ipw.increaseIndent(); 18701 Collection<PackageParser.Package> packages = null; 18702 if (packageName != null) { 18703 PackageParser.Package targetPackage = mPackages.get(packageName); 18704 if (targetPackage != null) { 18705 packages = Collections.singletonList(targetPackage); 18706 } else { 18707 ipw.println("Unable to find package: " + packageName); 18708 return; 18709 } 18710 } else { 18711 packages = mPackages.values(); 18712 } 18713 18714 for (PackageParser.Package pkg : packages) { 18715 ipw.println("[" + pkg.packageName + "]"); 18716 ipw.increaseIndent(); 18717 18718 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 18719 if (stats == null) { 18720 ipw.println("(No recorded stats)"); 18721 } else { 18722 stats.dump(ipw); 18723 } 18724 ipw.decreaseIndent(); 18725 } 18726 } 18727 18728 private String dumpDomainString(String packageName) { 18729 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18730 .getList(); 18731 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18732 18733 ArraySet<String> result = new ArraySet<>(); 18734 if (iviList.size() > 0) { 18735 for (IntentFilterVerificationInfo ivi : iviList) { 18736 for (String host : ivi.getDomains()) { 18737 result.add(host); 18738 } 18739 } 18740 } 18741 if (filters != null && filters.size() > 0) { 18742 for (IntentFilter filter : filters) { 18743 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18744 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18745 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18746 result.addAll(filter.getHostsList()); 18747 } 18748 } 18749 } 18750 18751 StringBuilder sb = new StringBuilder(result.size() * 16); 18752 for (String domain : result) { 18753 if (sb.length() > 0) sb.append(" "); 18754 sb.append(domain); 18755 } 18756 return sb.toString(); 18757 } 18758 18759 // ------- apps on sdcard specific code ------- 18760 static final boolean DEBUG_SD_INSTALL = false; 18761 18762 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18763 18764 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18765 18766 private boolean mMediaMounted = false; 18767 18768 static String getEncryptKey() { 18769 try { 18770 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18771 SD_ENCRYPTION_KEYSTORE_NAME); 18772 if (sdEncKey == null) { 18773 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18774 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18775 if (sdEncKey == null) { 18776 Slog.e(TAG, "Failed to create encryption keys"); 18777 return null; 18778 } 18779 } 18780 return sdEncKey; 18781 } catch (NoSuchAlgorithmException nsae) { 18782 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18783 return null; 18784 } catch (IOException ioe) { 18785 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18786 return null; 18787 } 18788 } 18789 18790 /* 18791 * Update media status on PackageManager. 18792 */ 18793 @Override 18794 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18795 int callingUid = Binder.getCallingUid(); 18796 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18797 throw new SecurityException("Media status can only be updated by the system"); 18798 } 18799 // reader; this apparently protects mMediaMounted, but should probably 18800 // be a different lock in that case. 18801 synchronized (mPackages) { 18802 Log.i(TAG, "Updating external media status from " 18803 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18804 + (mediaStatus ? "mounted" : "unmounted")); 18805 if (DEBUG_SD_INSTALL) 18806 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18807 + ", mMediaMounted=" + mMediaMounted); 18808 if (mediaStatus == mMediaMounted) { 18809 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18810 : 0, -1); 18811 mHandler.sendMessage(msg); 18812 return; 18813 } 18814 mMediaMounted = mediaStatus; 18815 } 18816 // Queue up an async operation since the package installation may take a 18817 // little while. 18818 mHandler.post(new Runnable() { 18819 public void run() { 18820 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18821 } 18822 }); 18823 } 18824 18825 /** 18826 * Called by MountService when the initial ASECs to scan are available. 18827 * Should block until all the ASEC containers are finished being scanned. 18828 */ 18829 public void scanAvailableAsecs() { 18830 updateExternalMediaStatusInner(true, false, false); 18831 } 18832 18833 /* 18834 * Collect information of applications on external media, map them against 18835 * existing containers and update information based on current mount status. 18836 * Please note that we always have to report status if reportStatus has been 18837 * set to true especially when unloading packages. 18838 */ 18839 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18840 boolean externalStorage) { 18841 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18842 int[] uidArr = EmptyArray.INT; 18843 18844 final String[] list = PackageHelper.getSecureContainerList(); 18845 if (ArrayUtils.isEmpty(list)) { 18846 Log.i(TAG, "No secure containers found"); 18847 } else { 18848 // Process list of secure containers and categorize them 18849 // as active or stale based on their package internal state. 18850 18851 // reader 18852 synchronized (mPackages) { 18853 for (String cid : list) { 18854 // Leave stages untouched for now; installer service owns them 18855 if (PackageInstallerService.isStageName(cid)) continue; 18856 18857 if (DEBUG_SD_INSTALL) 18858 Log.i(TAG, "Processing container " + cid); 18859 String pkgName = getAsecPackageName(cid); 18860 if (pkgName == null) { 18861 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18862 continue; 18863 } 18864 if (DEBUG_SD_INSTALL) 18865 Log.i(TAG, "Looking for pkg : " + pkgName); 18866 18867 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18868 if (ps == null) { 18869 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18870 continue; 18871 } 18872 18873 /* 18874 * Skip packages that are not external if we're unmounting 18875 * external storage. 18876 */ 18877 if (externalStorage && !isMounted && !isExternal(ps)) { 18878 continue; 18879 } 18880 18881 final AsecInstallArgs args = new AsecInstallArgs(cid, 18882 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18883 // The package status is changed only if the code path 18884 // matches between settings and the container id. 18885 if (ps.codePathString != null 18886 && ps.codePathString.startsWith(args.getCodePath())) { 18887 if (DEBUG_SD_INSTALL) { 18888 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18889 + " at code path: " + ps.codePathString); 18890 } 18891 18892 // We do have a valid package installed on sdcard 18893 processCids.put(args, ps.codePathString); 18894 final int uid = ps.appId; 18895 if (uid != -1) { 18896 uidArr = ArrayUtils.appendInt(uidArr, uid); 18897 } 18898 } else { 18899 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18900 + ps.codePathString); 18901 } 18902 } 18903 } 18904 18905 Arrays.sort(uidArr); 18906 } 18907 18908 // Process packages with valid entries. 18909 if (isMounted) { 18910 if (DEBUG_SD_INSTALL) 18911 Log.i(TAG, "Loading packages"); 18912 loadMediaPackages(processCids, uidArr, externalStorage); 18913 startCleaningPackages(); 18914 mInstallerService.onSecureContainersAvailable(); 18915 } else { 18916 if (DEBUG_SD_INSTALL) 18917 Log.i(TAG, "Unloading packages"); 18918 unloadMediaPackages(processCids, uidArr, reportStatus); 18919 } 18920 } 18921 18922 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18923 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18924 final int size = infos.size(); 18925 final String[] packageNames = new String[size]; 18926 final int[] packageUids = new int[size]; 18927 for (int i = 0; i < size; i++) { 18928 final ApplicationInfo info = infos.get(i); 18929 packageNames[i] = info.packageName; 18930 packageUids[i] = info.uid; 18931 } 18932 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18933 finishedReceiver); 18934 } 18935 18936 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18937 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18938 sendResourcesChangedBroadcast(mediaStatus, replacing, 18939 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18940 } 18941 18942 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18943 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18944 int size = pkgList.length; 18945 if (size > 0) { 18946 // Send broadcasts here 18947 Bundle extras = new Bundle(); 18948 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18949 if (uidArr != null) { 18950 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18951 } 18952 if (replacing) { 18953 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18954 } 18955 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18956 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18957 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18958 } 18959 } 18960 18961 /* 18962 * Look at potentially valid container ids from processCids If package 18963 * information doesn't match the one on record or package scanning fails, 18964 * the cid is added to list of removeCids. We currently don't delete stale 18965 * containers. 18966 */ 18967 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18968 boolean externalStorage) { 18969 ArrayList<String> pkgList = new ArrayList<String>(); 18970 Set<AsecInstallArgs> keys = processCids.keySet(); 18971 18972 for (AsecInstallArgs args : keys) { 18973 String codePath = processCids.get(args); 18974 if (DEBUG_SD_INSTALL) 18975 Log.i(TAG, "Loading container : " + args.cid); 18976 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18977 try { 18978 // Make sure there are no container errors first. 18979 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18980 Slog.e(TAG, "Failed to mount cid : " + args.cid 18981 + " when installing from sdcard"); 18982 continue; 18983 } 18984 // Check code path here. 18985 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18986 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18987 + " does not match one in settings " + codePath); 18988 continue; 18989 } 18990 // Parse package 18991 int parseFlags = mDefParseFlags; 18992 if (args.isExternalAsec()) { 18993 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18994 } 18995 if (args.isFwdLocked()) { 18996 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18997 } 18998 18999 synchronized (mInstallLock) { 19000 PackageParser.Package pkg = null; 19001 try { 19002 // Sadly we don't know the package name yet to freeze it 19003 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19004 SCAN_IGNORE_FROZEN, 0, null); 19005 } catch (PackageManagerException e) { 19006 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19007 } 19008 // Scan the package 19009 if (pkg != null) { 19010 /* 19011 * TODO why is the lock being held? doPostInstall is 19012 * called in other places without the lock. This needs 19013 * to be straightened out. 19014 */ 19015 // writer 19016 synchronized (mPackages) { 19017 retCode = PackageManager.INSTALL_SUCCEEDED; 19018 pkgList.add(pkg.packageName); 19019 // Post process args 19020 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19021 pkg.applicationInfo.uid); 19022 } 19023 } else { 19024 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19025 } 19026 } 19027 19028 } finally { 19029 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19030 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19031 } 19032 } 19033 } 19034 // writer 19035 synchronized (mPackages) { 19036 // If the platform SDK has changed since the last time we booted, 19037 // we need to re-grant app permission to catch any new ones that 19038 // appear. This is really a hack, and means that apps can in some 19039 // cases get permissions that the user didn't initially explicitly 19040 // allow... it would be nice to have some better way to handle 19041 // this situation. 19042 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19043 : mSettings.getInternalVersion(); 19044 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19045 : StorageManager.UUID_PRIVATE_INTERNAL; 19046 19047 int updateFlags = UPDATE_PERMISSIONS_ALL; 19048 if (ver.sdkVersion != mSdkVersion) { 19049 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19050 + mSdkVersion + "; regranting permissions for external"); 19051 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19052 } 19053 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19054 19055 // Yay, everything is now upgraded 19056 ver.forceCurrent(); 19057 19058 // can downgrade to reader 19059 // Persist settings 19060 mSettings.writeLPr(); 19061 } 19062 // Send a broadcast to let everyone know we are done processing 19063 if (pkgList.size() > 0) { 19064 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19065 } 19066 } 19067 19068 /* 19069 * Utility method to unload a list of specified containers 19070 */ 19071 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19072 // Just unmount all valid containers. 19073 for (AsecInstallArgs arg : cidArgs) { 19074 synchronized (mInstallLock) { 19075 arg.doPostDeleteLI(false); 19076 } 19077 } 19078 } 19079 19080 /* 19081 * Unload packages mounted on external media. This involves deleting package 19082 * data from internal structures, sending broadcasts about disabled packages, 19083 * gc'ing to free up references, unmounting all secure containers 19084 * corresponding to packages on external media, and posting a 19085 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19086 * that we always have to post this message if status has been requested no 19087 * matter what. 19088 */ 19089 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19090 final boolean reportStatus) { 19091 if (DEBUG_SD_INSTALL) 19092 Log.i(TAG, "unloading media packages"); 19093 ArrayList<String> pkgList = new ArrayList<String>(); 19094 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19095 final Set<AsecInstallArgs> keys = processCids.keySet(); 19096 for (AsecInstallArgs args : keys) { 19097 String pkgName = args.getPackageName(); 19098 if (DEBUG_SD_INSTALL) 19099 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19100 // Delete package internally 19101 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19102 synchronized (mInstallLock) { 19103 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19104 final boolean res; 19105 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19106 "unloadMediaPackages")) { 19107 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19108 null); 19109 } 19110 if (res) { 19111 pkgList.add(pkgName); 19112 } else { 19113 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19114 failedList.add(args); 19115 } 19116 } 19117 } 19118 19119 // reader 19120 synchronized (mPackages) { 19121 // We didn't update the settings after removing each package; 19122 // write them now for all packages. 19123 mSettings.writeLPr(); 19124 } 19125 19126 // We have to absolutely send UPDATED_MEDIA_STATUS only 19127 // after confirming that all the receivers processed the ordered 19128 // broadcast when packages get disabled, force a gc to clean things up. 19129 // and unload all the containers. 19130 if (pkgList.size() > 0) { 19131 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19132 new IIntentReceiver.Stub() { 19133 public void performReceive(Intent intent, int resultCode, String data, 19134 Bundle extras, boolean ordered, boolean sticky, 19135 int sendingUser) throws RemoteException { 19136 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19137 reportStatus ? 1 : 0, 1, keys); 19138 mHandler.sendMessage(msg); 19139 } 19140 }); 19141 } else { 19142 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19143 keys); 19144 mHandler.sendMessage(msg); 19145 } 19146 } 19147 19148 private void loadPrivatePackages(final VolumeInfo vol) { 19149 mHandler.post(new Runnable() { 19150 @Override 19151 public void run() { 19152 loadPrivatePackagesInner(vol); 19153 } 19154 }); 19155 } 19156 19157 private void loadPrivatePackagesInner(VolumeInfo vol) { 19158 final String volumeUuid = vol.fsUuid; 19159 if (TextUtils.isEmpty(volumeUuid)) { 19160 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19161 return; 19162 } 19163 19164 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19165 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19166 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19167 19168 final VersionInfo ver; 19169 final List<PackageSetting> packages; 19170 synchronized (mPackages) { 19171 ver = mSettings.findOrCreateVersion(volumeUuid); 19172 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19173 } 19174 19175 for (PackageSetting ps : packages) { 19176 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19177 synchronized (mInstallLock) { 19178 final PackageParser.Package pkg; 19179 try { 19180 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19181 loaded.add(pkg.applicationInfo); 19182 19183 } catch (PackageManagerException e) { 19184 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19185 } 19186 19187 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19188 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19189 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19190 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19191 } 19192 } 19193 } 19194 19195 // Reconcile app data for all started/unlocked users 19196 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19197 final UserManager um = mContext.getSystemService(UserManager.class); 19198 UserManagerInternal umInternal = getUserManagerInternal(); 19199 for (UserInfo user : um.getUsers()) { 19200 final int flags; 19201 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19202 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19203 } else if (umInternal.isUserRunning(user.id)) { 19204 flags = StorageManager.FLAG_STORAGE_DE; 19205 } else { 19206 continue; 19207 } 19208 19209 try { 19210 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19211 synchronized (mInstallLock) { 19212 reconcileAppsDataLI(volumeUuid, user.id, flags); 19213 } 19214 } catch (IllegalStateException e) { 19215 // Device was probably ejected, and we'll process that event momentarily 19216 Slog.w(TAG, "Failed to prepare storage: " + e); 19217 } 19218 } 19219 19220 synchronized (mPackages) { 19221 int updateFlags = UPDATE_PERMISSIONS_ALL; 19222 if (ver.sdkVersion != mSdkVersion) { 19223 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19224 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19225 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19226 } 19227 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19228 19229 // Yay, everything is now upgraded 19230 ver.forceCurrent(); 19231 19232 mSettings.writeLPr(); 19233 } 19234 19235 for (PackageFreezer freezer : freezers) { 19236 freezer.close(); 19237 } 19238 19239 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19240 sendResourcesChangedBroadcast(true, false, loaded, null); 19241 } 19242 19243 private void unloadPrivatePackages(final VolumeInfo vol) { 19244 mHandler.post(new Runnable() { 19245 @Override 19246 public void run() { 19247 unloadPrivatePackagesInner(vol); 19248 } 19249 }); 19250 } 19251 19252 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19253 final String volumeUuid = vol.fsUuid; 19254 if (TextUtils.isEmpty(volumeUuid)) { 19255 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19256 return; 19257 } 19258 19259 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19260 synchronized (mInstallLock) { 19261 synchronized (mPackages) { 19262 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19263 for (PackageSetting ps : packages) { 19264 if (ps.pkg == null) continue; 19265 19266 final ApplicationInfo info = ps.pkg.applicationInfo; 19267 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19268 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19269 19270 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19271 "unloadPrivatePackagesInner")) { 19272 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19273 false, null)) { 19274 unloaded.add(info); 19275 } else { 19276 Slog.w(TAG, "Failed to unload " + ps.codePath); 19277 } 19278 } 19279 19280 // Try very hard to release any references to this package 19281 // so we don't risk the system server being killed due to 19282 // open FDs 19283 AttributeCache.instance().removePackage(ps.name); 19284 } 19285 19286 mSettings.writeLPr(); 19287 } 19288 } 19289 19290 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19291 sendResourcesChangedBroadcast(false, false, unloaded, null); 19292 19293 // Try very hard to release any references to this path so we don't risk 19294 // the system server being killed due to open FDs 19295 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19296 19297 for (int i = 0; i < 3; i++) { 19298 System.gc(); 19299 System.runFinalization(); 19300 } 19301 } 19302 19303 /** 19304 * Prepare storage areas for given user on all mounted devices. 19305 */ 19306 void prepareUserData(int userId, int userSerial, int flags) { 19307 synchronized (mInstallLock) { 19308 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19309 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19310 final String volumeUuid = vol.getFsUuid(); 19311 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19312 } 19313 } 19314 } 19315 19316 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19317 boolean allowRecover) { 19318 // Prepare storage and verify that serial numbers are consistent; if 19319 // there's a mismatch we need to destroy to avoid leaking data 19320 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19321 try { 19322 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19323 19324 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19325 UserManagerService.enforceSerialNumber( 19326 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19327 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19328 UserManagerService.enforceSerialNumber( 19329 Environment.getDataSystemDeDirectory(userId), userSerial); 19330 } 19331 } 19332 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19333 UserManagerService.enforceSerialNumber( 19334 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19335 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19336 UserManagerService.enforceSerialNumber( 19337 Environment.getDataSystemCeDirectory(userId), userSerial); 19338 } 19339 } 19340 19341 synchronized (mInstallLock) { 19342 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19343 } 19344 } catch (Exception e) { 19345 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19346 + " because we failed to prepare: " + e); 19347 destroyUserDataLI(volumeUuid, userId, 19348 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19349 19350 if (allowRecover) { 19351 // Try one last time; if we fail again we're really in trouble 19352 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19353 } 19354 } 19355 } 19356 19357 /** 19358 * Destroy storage areas for given user on all mounted devices. 19359 */ 19360 void destroyUserData(int userId, int flags) { 19361 synchronized (mInstallLock) { 19362 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19363 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19364 final String volumeUuid = vol.getFsUuid(); 19365 destroyUserDataLI(volumeUuid, userId, flags); 19366 } 19367 } 19368 } 19369 19370 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19371 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19372 try { 19373 // Clean up app data, profile data, and media data 19374 mInstaller.destroyUserData(volumeUuid, userId, flags); 19375 19376 // Clean up system data 19377 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19378 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19379 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19380 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19381 } 19382 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19383 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19384 } 19385 } 19386 19387 // Data with special labels is now gone, so finish the job 19388 storage.destroyUserStorage(volumeUuid, userId, flags); 19389 19390 } catch (Exception e) { 19391 logCriticalInfo(Log.WARN, 19392 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19393 } 19394 } 19395 19396 /** 19397 * Examine all users present on given mounted volume, and destroy data 19398 * belonging to users that are no longer valid, or whose user ID has been 19399 * recycled. 19400 */ 19401 private void reconcileUsers(String volumeUuid) { 19402 final List<File> files = new ArrayList<>(); 19403 Collections.addAll(files, FileUtils 19404 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19405 Collections.addAll(files, FileUtils 19406 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19407 Collections.addAll(files, FileUtils 19408 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19409 Collections.addAll(files, FileUtils 19410 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19411 for (File file : files) { 19412 if (!file.isDirectory()) continue; 19413 19414 final int userId; 19415 final UserInfo info; 19416 try { 19417 userId = Integer.parseInt(file.getName()); 19418 info = sUserManager.getUserInfo(userId); 19419 } catch (NumberFormatException e) { 19420 Slog.w(TAG, "Invalid user directory " + file); 19421 continue; 19422 } 19423 19424 boolean destroyUser = false; 19425 if (info == null) { 19426 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19427 + " because no matching user was found"); 19428 destroyUser = true; 19429 } else if (!mOnlyCore) { 19430 try { 19431 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19432 } catch (IOException e) { 19433 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19434 + " because we failed to enforce serial number: " + e); 19435 destroyUser = true; 19436 } 19437 } 19438 19439 if (destroyUser) { 19440 synchronized (mInstallLock) { 19441 destroyUserDataLI(volumeUuid, userId, 19442 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19443 } 19444 } 19445 } 19446 } 19447 19448 private void assertPackageKnown(String volumeUuid, String packageName) 19449 throws PackageManagerException { 19450 synchronized (mPackages) { 19451 final PackageSetting ps = mSettings.mPackages.get(packageName); 19452 if (ps == null) { 19453 throw new PackageManagerException("Package " + packageName + " is unknown"); 19454 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19455 throw new PackageManagerException( 19456 "Package " + packageName + " found on unknown volume " + volumeUuid 19457 + "; expected volume " + ps.volumeUuid); 19458 } 19459 } 19460 } 19461 19462 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19463 throws PackageManagerException { 19464 synchronized (mPackages) { 19465 final PackageSetting ps = mSettings.mPackages.get(packageName); 19466 if (ps == null) { 19467 throw new PackageManagerException("Package " + packageName + " is unknown"); 19468 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19469 throw new PackageManagerException( 19470 "Package " + packageName + " found on unknown volume " + volumeUuid 19471 + "; expected volume " + ps.volumeUuid); 19472 } else if (!ps.getInstalled(userId)) { 19473 throw new PackageManagerException( 19474 "Package " + packageName + " not installed for user " + userId); 19475 } 19476 } 19477 } 19478 19479 /** 19480 * Examine all apps present on given mounted volume, and destroy apps that 19481 * aren't expected, either due to uninstallation or reinstallation on 19482 * another volume. 19483 */ 19484 private void reconcileApps(String volumeUuid) { 19485 final File[] files = FileUtils 19486 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19487 for (File file : files) { 19488 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19489 && !PackageInstallerService.isStageName(file.getName()); 19490 if (!isPackage) { 19491 // Ignore entries which are not packages 19492 continue; 19493 } 19494 19495 try { 19496 final PackageLite pkg = PackageParser.parsePackageLite(file, 19497 PackageParser.PARSE_MUST_BE_APK); 19498 assertPackageKnown(volumeUuid, pkg.packageName); 19499 19500 } catch (PackageParserException | PackageManagerException e) { 19501 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19502 synchronized (mInstallLock) { 19503 removeCodePathLI(file); 19504 } 19505 } 19506 } 19507 } 19508 19509 /** 19510 * Reconcile all app data for the given user. 19511 * <p> 19512 * Verifies that directories exist and that ownership and labeling is 19513 * correct for all installed apps on all mounted volumes. 19514 */ 19515 void reconcileAppsData(int userId, int flags) { 19516 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19517 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19518 final String volumeUuid = vol.getFsUuid(); 19519 synchronized (mInstallLock) { 19520 reconcileAppsDataLI(volumeUuid, userId, flags); 19521 } 19522 } 19523 } 19524 19525 /** 19526 * Reconcile all app data on given mounted volume. 19527 * <p> 19528 * Destroys app data that isn't expected, either due to uninstallation or 19529 * reinstallation on another volume. 19530 * <p> 19531 * Verifies that directories exist and that ownership and labeling is 19532 * correct for all installed apps. 19533 */ 19534 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19535 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19536 + Integer.toHexString(flags)); 19537 19538 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19539 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19540 19541 boolean restoreconNeeded = false; 19542 19543 // First look for stale data that doesn't belong, and check if things 19544 // have changed since we did our last restorecon 19545 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19546 if (StorageManager.isFileEncryptedNativeOrEmulated() 19547 && !StorageManager.isUserKeyUnlocked(userId)) { 19548 throw new RuntimeException( 19549 "Yikes, someone asked us to reconcile CE storage while " + userId 19550 + " was still locked; this would have caused massive data loss!"); 19551 } 19552 19553 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19554 19555 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19556 for (File file : files) { 19557 final String packageName = file.getName(); 19558 try { 19559 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19560 } catch (PackageManagerException e) { 19561 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19562 try { 19563 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19564 StorageManager.FLAG_STORAGE_CE, 0); 19565 } catch (InstallerException e2) { 19566 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19567 } 19568 } 19569 } 19570 } 19571 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19572 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19573 19574 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19575 for (File file : files) { 19576 final String packageName = file.getName(); 19577 try { 19578 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19579 } catch (PackageManagerException e) { 19580 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19581 try { 19582 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19583 StorageManager.FLAG_STORAGE_DE, 0); 19584 } catch (InstallerException e2) { 19585 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19586 } 19587 } 19588 } 19589 } 19590 19591 // Ensure that data directories are ready to roll for all packages 19592 // installed for this volume and user 19593 final List<PackageSetting> packages; 19594 synchronized (mPackages) { 19595 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19596 } 19597 int preparedCount = 0; 19598 for (PackageSetting ps : packages) { 19599 final String packageName = ps.name; 19600 if (ps.pkg == null) { 19601 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19602 // TODO: might be due to legacy ASEC apps; we should circle back 19603 // and reconcile again once they're scanned 19604 continue; 19605 } 19606 19607 if (ps.getInstalled(userId)) { 19608 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19609 19610 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19611 // We may have just shuffled around app data directories, so 19612 // prepare them one more time 19613 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19614 } 19615 19616 preparedCount++; 19617 } 19618 } 19619 19620 if (restoreconNeeded) { 19621 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19622 SELinuxMMAC.setRestoreconDone(ceDir); 19623 } 19624 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19625 SELinuxMMAC.setRestoreconDone(deDir); 19626 } 19627 } 19628 19629 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19630 + " packages; restoreconNeeded was " + restoreconNeeded); 19631 } 19632 19633 /** 19634 * Prepare app data for the given app just after it was installed or 19635 * upgraded. This method carefully only touches users that it's installed 19636 * for, and it forces a restorecon to handle any seinfo changes. 19637 * <p> 19638 * Verifies that directories exist and that ownership and labeling is 19639 * correct for all installed apps. If there is an ownership mismatch, it 19640 * will try recovering system apps by wiping data; third-party app data is 19641 * left intact. 19642 * <p> 19643 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19644 */ 19645 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19646 final PackageSetting ps; 19647 synchronized (mPackages) { 19648 ps = mSettings.mPackages.get(pkg.packageName); 19649 mSettings.writeKernelMappingLPr(ps); 19650 } 19651 19652 final UserManager um = mContext.getSystemService(UserManager.class); 19653 UserManagerInternal umInternal = getUserManagerInternal(); 19654 for (UserInfo user : um.getUsers()) { 19655 final int flags; 19656 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19657 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19658 } else if (umInternal.isUserRunning(user.id)) { 19659 flags = StorageManager.FLAG_STORAGE_DE; 19660 } else { 19661 continue; 19662 } 19663 19664 if (ps.getInstalled(user.id)) { 19665 // Whenever an app changes, force a restorecon of its data 19666 // TODO: when user data is locked, mark that we're still dirty 19667 prepareAppDataLIF(pkg, user.id, flags, true); 19668 } 19669 } 19670 } 19671 19672 /** 19673 * Prepare app data for the given app. 19674 * <p> 19675 * Verifies that directories exist and that ownership and labeling is 19676 * correct for all installed apps. If there is an ownership mismatch, this 19677 * will try recovering system apps by wiping data; third-party app data is 19678 * left intact. 19679 */ 19680 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19681 boolean restoreconNeeded) { 19682 if (pkg == null) { 19683 Slog.wtf(TAG, "Package was null!", new Throwable()); 19684 return; 19685 } 19686 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19687 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19688 for (int i = 0; i < childCount; i++) { 19689 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19690 } 19691 } 19692 19693 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19694 boolean restoreconNeeded) { 19695 if (DEBUG_APP_DATA) { 19696 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19697 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19698 } 19699 19700 final String volumeUuid = pkg.volumeUuid; 19701 final String packageName = pkg.packageName; 19702 final ApplicationInfo app = pkg.applicationInfo; 19703 final int appId = UserHandle.getAppId(app.uid); 19704 19705 Preconditions.checkNotNull(app.seinfo); 19706 19707 try { 19708 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19709 appId, app.seinfo, app.targetSdkVersion); 19710 } catch (InstallerException e) { 19711 if (app.isSystemApp()) { 19712 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19713 + ", but trying to recover: " + e); 19714 destroyAppDataLeafLIF(pkg, userId, flags); 19715 try { 19716 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19717 appId, app.seinfo, app.targetSdkVersion); 19718 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19719 } catch (InstallerException e2) { 19720 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19721 } 19722 } else { 19723 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19724 } 19725 } 19726 19727 if (restoreconNeeded) { 19728 try { 19729 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19730 app.seinfo); 19731 } catch (InstallerException e) { 19732 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19733 } 19734 } 19735 19736 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19737 try { 19738 // CE storage is unlocked right now, so read out the inode and 19739 // remember for use later when it's locked 19740 // TODO: mark this structure as dirty so we persist it! 19741 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19742 StorageManager.FLAG_STORAGE_CE); 19743 synchronized (mPackages) { 19744 final PackageSetting ps = mSettings.mPackages.get(packageName); 19745 if (ps != null) { 19746 ps.setCeDataInode(ceDataInode, userId); 19747 } 19748 } 19749 } catch (InstallerException e) { 19750 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19751 } 19752 } 19753 19754 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19755 } 19756 19757 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19758 if (pkg == null) { 19759 Slog.wtf(TAG, "Package was null!", new Throwable()); 19760 return; 19761 } 19762 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19763 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19764 for (int i = 0; i < childCount; i++) { 19765 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19766 } 19767 } 19768 19769 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19770 final String volumeUuid = pkg.volumeUuid; 19771 final String packageName = pkg.packageName; 19772 final ApplicationInfo app = pkg.applicationInfo; 19773 19774 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19775 // Create a native library symlink only if we have native libraries 19776 // and if the native libraries are 32 bit libraries. We do not provide 19777 // this symlink for 64 bit libraries. 19778 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19779 final String nativeLibPath = app.nativeLibraryDir; 19780 try { 19781 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19782 nativeLibPath, userId); 19783 } catch (InstallerException e) { 19784 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19785 } 19786 } 19787 } 19788 } 19789 19790 /** 19791 * For system apps on non-FBE devices, this method migrates any existing 19792 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19793 * requested by the app. 19794 */ 19795 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19796 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19797 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19798 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19799 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19800 try { 19801 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19802 storageTarget); 19803 } catch (InstallerException e) { 19804 logCriticalInfo(Log.WARN, 19805 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19806 } 19807 return true; 19808 } else { 19809 return false; 19810 } 19811 } 19812 19813 public PackageFreezer freezePackage(String packageName, String killReason) { 19814 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19815 } 19816 19817 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19818 return new PackageFreezer(packageName, userId, killReason); 19819 } 19820 19821 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19822 String killReason) { 19823 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19824 } 19825 19826 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19827 String killReason) { 19828 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19829 return new PackageFreezer(); 19830 } else { 19831 return freezePackage(packageName, userId, killReason); 19832 } 19833 } 19834 19835 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19836 String killReason) { 19837 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19838 } 19839 19840 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19841 String killReason) { 19842 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19843 return new PackageFreezer(); 19844 } else { 19845 return freezePackage(packageName, userId, killReason); 19846 } 19847 } 19848 19849 /** 19850 * Class that freezes and kills the given package upon creation, and 19851 * unfreezes it upon closing. This is typically used when doing surgery on 19852 * app code/data to prevent the app from running while you're working. 19853 */ 19854 private class PackageFreezer implements AutoCloseable { 19855 private final String mPackageName; 19856 private final PackageFreezer[] mChildren; 19857 19858 private final boolean mWeFroze; 19859 19860 private final AtomicBoolean mClosed = new AtomicBoolean(); 19861 private final CloseGuard mCloseGuard = CloseGuard.get(); 19862 19863 /** 19864 * Create and return a stub freezer that doesn't actually do anything, 19865 * typically used when someone requested 19866 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19867 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19868 */ 19869 public PackageFreezer() { 19870 mPackageName = null; 19871 mChildren = null; 19872 mWeFroze = false; 19873 mCloseGuard.open("close"); 19874 } 19875 19876 public PackageFreezer(String packageName, int userId, String killReason) { 19877 synchronized (mPackages) { 19878 mPackageName = packageName; 19879 mWeFroze = mFrozenPackages.add(mPackageName); 19880 19881 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19882 if (ps != null) { 19883 killApplication(ps.name, ps.appId, userId, killReason); 19884 } 19885 19886 final PackageParser.Package p = mPackages.get(packageName); 19887 if (p != null && p.childPackages != null) { 19888 final int N = p.childPackages.size(); 19889 mChildren = new PackageFreezer[N]; 19890 for (int i = 0; i < N; i++) { 19891 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19892 userId, killReason); 19893 } 19894 } else { 19895 mChildren = null; 19896 } 19897 } 19898 mCloseGuard.open("close"); 19899 } 19900 19901 @Override 19902 protected void finalize() throws Throwable { 19903 try { 19904 mCloseGuard.warnIfOpen(); 19905 close(); 19906 } finally { 19907 super.finalize(); 19908 } 19909 } 19910 19911 @Override 19912 public void close() { 19913 mCloseGuard.close(); 19914 if (mClosed.compareAndSet(false, true)) { 19915 synchronized (mPackages) { 19916 if (mWeFroze) { 19917 mFrozenPackages.remove(mPackageName); 19918 } 19919 19920 if (mChildren != null) { 19921 for (PackageFreezer freezer : mChildren) { 19922 freezer.close(); 19923 } 19924 } 19925 } 19926 } 19927 } 19928 } 19929 19930 /** 19931 * Verify that given package is currently frozen. 19932 */ 19933 private void checkPackageFrozen(String packageName) { 19934 synchronized (mPackages) { 19935 if (!mFrozenPackages.contains(packageName)) { 19936 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19937 } 19938 } 19939 } 19940 19941 @Override 19942 public int movePackage(final String packageName, final String volumeUuid) { 19943 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19944 19945 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19946 final int moveId = mNextMoveId.getAndIncrement(); 19947 mHandler.post(new Runnable() { 19948 @Override 19949 public void run() { 19950 try { 19951 movePackageInternal(packageName, volumeUuid, moveId, user); 19952 } catch (PackageManagerException e) { 19953 Slog.w(TAG, "Failed to move " + packageName, e); 19954 mMoveCallbacks.notifyStatusChanged(moveId, 19955 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19956 } 19957 } 19958 }); 19959 return moveId; 19960 } 19961 19962 private void movePackageInternal(final String packageName, final String volumeUuid, 19963 final int moveId, UserHandle user) throws PackageManagerException { 19964 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19965 final PackageManager pm = mContext.getPackageManager(); 19966 19967 final boolean currentAsec; 19968 final String currentVolumeUuid; 19969 final File codeFile; 19970 final String installerPackageName; 19971 final String packageAbiOverride; 19972 final int appId; 19973 final String seinfo; 19974 final String label; 19975 final int targetSdkVersion; 19976 final PackageFreezer freezer; 19977 final int[] installedUserIds; 19978 19979 // reader 19980 synchronized (mPackages) { 19981 final PackageParser.Package pkg = mPackages.get(packageName); 19982 final PackageSetting ps = mSettings.mPackages.get(packageName); 19983 if (pkg == null || ps == null) { 19984 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19985 } 19986 19987 if (pkg.applicationInfo.isSystemApp()) { 19988 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19989 "Cannot move system application"); 19990 } 19991 19992 if (pkg.applicationInfo.isExternalAsec()) { 19993 currentAsec = true; 19994 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19995 } else if (pkg.applicationInfo.isForwardLocked()) { 19996 currentAsec = true; 19997 currentVolumeUuid = "forward_locked"; 19998 } else { 19999 currentAsec = false; 20000 currentVolumeUuid = ps.volumeUuid; 20001 20002 final File probe = new File(pkg.codePath); 20003 final File probeOat = new File(probe, "oat"); 20004 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20005 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20006 "Move only supported for modern cluster style installs"); 20007 } 20008 } 20009 20010 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20011 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20012 "Package already moved to " + volumeUuid); 20013 } 20014 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20015 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20016 "Device admin cannot be moved"); 20017 } 20018 20019 if (mFrozenPackages.contains(packageName)) { 20020 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20021 "Failed to move already frozen package"); 20022 } 20023 20024 codeFile = new File(pkg.codePath); 20025 installerPackageName = ps.installerPackageName; 20026 packageAbiOverride = ps.cpuAbiOverrideString; 20027 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20028 seinfo = pkg.applicationInfo.seinfo; 20029 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20030 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20031 freezer = freezePackage(packageName, "movePackageInternal"); 20032 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20033 } 20034 20035 final Bundle extras = new Bundle(); 20036 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20037 extras.putString(Intent.EXTRA_TITLE, label); 20038 mMoveCallbacks.notifyCreated(moveId, extras); 20039 20040 int installFlags; 20041 final boolean moveCompleteApp; 20042 final File measurePath; 20043 20044 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20045 installFlags = INSTALL_INTERNAL; 20046 moveCompleteApp = !currentAsec; 20047 measurePath = Environment.getDataAppDirectory(volumeUuid); 20048 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20049 installFlags = INSTALL_EXTERNAL; 20050 moveCompleteApp = false; 20051 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20052 } else { 20053 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20054 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20055 || !volume.isMountedWritable()) { 20056 freezer.close(); 20057 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20058 "Move location not mounted private volume"); 20059 } 20060 20061 Preconditions.checkState(!currentAsec); 20062 20063 installFlags = INSTALL_INTERNAL; 20064 moveCompleteApp = true; 20065 measurePath = Environment.getDataAppDirectory(volumeUuid); 20066 } 20067 20068 final PackageStats stats = new PackageStats(null, -1); 20069 synchronized (mInstaller) { 20070 for (int userId : installedUserIds) { 20071 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20072 freezer.close(); 20073 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20074 "Failed to measure package size"); 20075 } 20076 } 20077 } 20078 20079 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20080 + stats.dataSize); 20081 20082 final long startFreeBytes = measurePath.getFreeSpace(); 20083 final long sizeBytes; 20084 if (moveCompleteApp) { 20085 sizeBytes = stats.codeSize + stats.dataSize; 20086 } else { 20087 sizeBytes = stats.codeSize; 20088 } 20089 20090 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20091 freezer.close(); 20092 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20093 "Not enough free space to move"); 20094 } 20095 20096 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20097 20098 final CountDownLatch installedLatch = new CountDownLatch(1); 20099 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20100 @Override 20101 public void onUserActionRequired(Intent intent) throws RemoteException { 20102 throw new IllegalStateException(); 20103 } 20104 20105 @Override 20106 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20107 Bundle extras) throws RemoteException { 20108 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20109 + PackageManager.installStatusToString(returnCode, msg)); 20110 20111 installedLatch.countDown(); 20112 freezer.close(); 20113 20114 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20115 switch (status) { 20116 case PackageInstaller.STATUS_SUCCESS: 20117 mMoveCallbacks.notifyStatusChanged(moveId, 20118 PackageManager.MOVE_SUCCEEDED); 20119 break; 20120 case PackageInstaller.STATUS_FAILURE_STORAGE: 20121 mMoveCallbacks.notifyStatusChanged(moveId, 20122 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20123 break; 20124 default: 20125 mMoveCallbacks.notifyStatusChanged(moveId, 20126 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20127 break; 20128 } 20129 } 20130 }; 20131 20132 final MoveInfo move; 20133 if (moveCompleteApp) { 20134 // Kick off a thread to report progress estimates 20135 new Thread() { 20136 @Override 20137 public void run() { 20138 while (true) { 20139 try { 20140 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20141 break; 20142 } 20143 } catch (InterruptedException ignored) { 20144 } 20145 20146 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20147 final int progress = 10 + (int) MathUtils.constrain( 20148 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20149 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20150 } 20151 } 20152 }.start(); 20153 20154 final String dataAppName = codeFile.getName(); 20155 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20156 dataAppName, appId, seinfo, targetSdkVersion); 20157 } else { 20158 move = null; 20159 } 20160 20161 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20162 20163 final Message msg = mHandler.obtainMessage(INIT_COPY); 20164 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20165 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20166 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20167 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20168 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20169 msg.obj = params; 20170 20171 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20172 System.identityHashCode(msg.obj)); 20173 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20174 System.identityHashCode(msg.obj)); 20175 20176 mHandler.sendMessage(msg); 20177 } 20178 20179 @Override 20180 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20181 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20182 20183 final int realMoveId = mNextMoveId.getAndIncrement(); 20184 final Bundle extras = new Bundle(); 20185 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20186 mMoveCallbacks.notifyCreated(realMoveId, extras); 20187 20188 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20189 @Override 20190 public void onCreated(int moveId, Bundle extras) { 20191 // Ignored 20192 } 20193 20194 @Override 20195 public void onStatusChanged(int moveId, int status, long estMillis) { 20196 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20197 } 20198 }; 20199 20200 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20201 storage.setPrimaryStorageUuid(volumeUuid, callback); 20202 return realMoveId; 20203 } 20204 20205 @Override 20206 public int getMoveStatus(int moveId) { 20207 mContext.enforceCallingOrSelfPermission( 20208 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20209 return mMoveCallbacks.mLastStatus.get(moveId); 20210 } 20211 20212 @Override 20213 public void registerMoveCallback(IPackageMoveObserver callback) { 20214 mContext.enforceCallingOrSelfPermission( 20215 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20216 mMoveCallbacks.register(callback); 20217 } 20218 20219 @Override 20220 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20221 mContext.enforceCallingOrSelfPermission( 20222 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20223 mMoveCallbacks.unregister(callback); 20224 } 20225 20226 @Override 20227 public boolean setInstallLocation(int loc) { 20228 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20229 null); 20230 if (getInstallLocation() == loc) { 20231 return true; 20232 } 20233 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20234 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20235 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20236 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20237 return true; 20238 } 20239 return false; 20240 } 20241 20242 @Override 20243 public int getInstallLocation() { 20244 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20245 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20246 PackageHelper.APP_INSTALL_AUTO); 20247 } 20248 20249 /** Called by UserManagerService */ 20250 void cleanUpUser(UserManagerService userManager, int userHandle) { 20251 synchronized (mPackages) { 20252 mDirtyUsers.remove(userHandle); 20253 mUserNeedsBadging.delete(userHandle); 20254 mSettings.removeUserLPw(userHandle); 20255 mPendingBroadcasts.remove(userHandle); 20256 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20257 removeUnusedPackagesLPw(userManager, userHandle); 20258 } 20259 } 20260 20261 /** 20262 * We're removing userHandle and would like to remove any downloaded packages 20263 * that are no longer in use by any other user. 20264 * @param userHandle the user being removed 20265 */ 20266 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20267 final boolean DEBUG_CLEAN_APKS = false; 20268 int [] users = userManager.getUserIds(); 20269 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20270 while (psit.hasNext()) { 20271 PackageSetting ps = psit.next(); 20272 if (ps.pkg == null) { 20273 continue; 20274 } 20275 final String packageName = ps.pkg.packageName; 20276 // Skip over if system app 20277 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20278 continue; 20279 } 20280 if (DEBUG_CLEAN_APKS) { 20281 Slog.i(TAG, "Checking package " + packageName); 20282 } 20283 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20284 if (keep) { 20285 if (DEBUG_CLEAN_APKS) { 20286 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20287 } 20288 } else { 20289 for (int i = 0; i < users.length; i++) { 20290 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20291 keep = true; 20292 if (DEBUG_CLEAN_APKS) { 20293 Slog.i(TAG, " Keeping package " + packageName + " for user " 20294 + users[i]); 20295 } 20296 break; 20297 } 20298 } 20299 } 20300 if (!keep) { 20301 if (DEBUG_CLEAN_APKS) { 20302 Slog.i(TAG, " Removing package " + packageName); 20303 } 20304 mHandler.post(new Runnable() { 20305 public void run() { 20306 deletePackageX(packageName, userHandle, 0); 20307 } //end run 20308 }); 20309 } 20310 } 20311 } 20312 20313 /** Called by UserManagerService */ 20314 void createNewUser(int userId) { 20315 synchronized (mInstallLock) { 20316 mSettings.createNewUserLI(this, mInstaller, userId); 20317 } 20318 synchronized (mPackages) { 20319 scheduleWritePackageRestrictionsLocked(userId); 20320 scheduleWritePackageListLocked(userId); 20321 applyFactoryDefaultBrowserLPw(userId); 20322 primeDomainVerificationsLPw(userId); 20323 } 20324 } 20325 20326 void onNewUserCreated(final int userId) { 20327 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20328 // If permission review for legacy apps is required, we represent 20329 // dagerous permissions for such apps as always granted runtime 20330 // permissions to keep per user flag state whether review is needed. 20331 // Hence, if a new user is added we have to propagate dangerous 20332 // permission grants for these legacy apps. 20333 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20334 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20335 | UPDATE_PERMISSIONS_REPLACE_ALL); 20336 } 20337 } 20338 20339 @Override 20340 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20341 mContext.enforceCallingOrSelfPermission( 20342 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20343 "Only package verification agents can read the verifier device identity"); 20344 20345 synchronized (mPackages) { 20346 return mSettings.getVerifierDeviceIdentityLPw(); 20347 } 20348 } 20349 20350 @Override 20351 public void setPermissionEnforced(String permission, boolean enforced) { 20352 // TODO: Now that we no longer change GID for storage, this should to away. 20353 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20354 "setPermissionEnforced"); 20355 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20356 synchronized (mPackages) { 20357 if (mSettings.mReadExternalStorageEnforced == null 20358 || mSettings.mReadExternalStorageEnforced != enforced) { 20359 mSettings.mReadExternalStorageEnforced = enforced; 20360 mSettings.writeLPr(); 20361 } 20362 } 20363 // kill any non-foreground processes so we restart them and 20364 // grant/revoke the GID. 20365 final IActivityManager am = ActivityManagerNative.getDefault(); 20366 if (am != null) { 20367 final long token = Binder.clearCallingIdentity(); 20368 try { 20369 am.killProcessesBelowForeground("setPermissionEnforcement"); 20370 } catch (RemoteException e) { 20371 } finally { 20372 Binder.restoreCallingIdentity(token); 20373 } 20374 } 20375 } else { 20376 throw new IllegalArgumentException("No selective enforcement for " + permission); 20377 } 20378 } 20379 20380 @Override 20381 @Deprecated 20382 public boolean isPermissionEnforced(String permission) { 20383 return true; 20384 } 20385 20386 @Override 20387 public boolean isStorageLow() { 20388 final long token = Binder.clearCallingIdentity(); 20389 try { 20390 final DeviceStorageMonitorInternal 20391 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20392 if (dsm != null) { 20393 return dsm.isMemoryLow(); 20394 } else { 20395 return false; 20396 } 20397 } finally { 20398 Binder.restoreCallingIdentity(token); 20399 } 20400 } 20401 20402 @Override 20403 public IPackageInstaller getPackageInstaller() { 20404 return mInstallerService; 20405 } 20406 20407 private boolean userNeedsBadging(int userId) { 20408 int index = mUserNeedsBadging.indexOfKey(userId); 20409 if (index < 0) { 20410 final UserInfo userInfo; 20411 final long token = Binder.clearCallingIdentity(); 20412 try { 20413 userInfo = sUserManager.getUserInfo(userId); 20414 } finally { 20415 Binder.restoreCallingIdentity(token); 20416 } 20417 final boolean b; 20418 if (userInfo != null && userInfo.isManagedProfile()) { 20419 b = true; 20420 } else { 20421 b = false; 20422 } 20423 mUserNeedsBadging.put(userId, b); 20424 return b; 20425 } 20426 return mUserNeedsBadging.valueAt(index); 20427 } 20428 20429 @Override 20430 public KeySet getKeySetByAlias(String packageName, String alias) { 20431 if (packageName == null || alias == null) { 20432 return null; 20433 } 20434 synchronized(mPackages) { 20435 final PackageParser.Package pkg = mPackages.get(packageName); 20436 if (pkg == null) { 20437 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20438 throw new IllegalArgumentException("Unknown package: " + packageName); 20439 } 20440 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20441 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20442 } 20443 } 20444 20445 @Override 20446 public KeySet getSigningKeySet(String packageName) { 20447 if (packageName == null) { 20448 return null; 20449 } 20450 synchronized(mPackages) { 20451 final PackageParser.Package pkg = mPackages.get(packageName); 20452 if (pkg == null) { 20453 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20454 throw new IllegalArgumentException("Unknown package: " + packageName); 20455 } 20456 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20457 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20458 throw new SecurityException("May not access signing KeySet of other apps."); 20459 } 20460 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20461 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20462 } 20463 } 20464 20465 @Override 20466 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20467 if (packageName == null || ks == null) { 20468 return false; 20469 } 20470 synchronized(mPackages) { 20471 final PackageParser.Package pkg = mPackages.get(packageName); 20472 if (pkg == null) { 20473 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20474 throw new IllegalArgumentException("Unknown package: " + packageName); 20475 } 20476 IBinder ksh = ks.getToken(); 20477 if (ksh instanceof KeySetHandle) { 20478 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20479 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20480 } 20481 return false; 20482 } 20483 } 20484 20485 @Override 20486 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20487 if (packageName == null || ks == null) { 20488 return false; 20489 } 20490 synchronized(mPackages) { 20491 final PackageParser.Package pkg = mPackages.get(packageName); 20492 if (pkg == null) { 20493 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20494 throw new IllegalArgumentException("Unknown package: " + packageName); 20495 } 20496 IBinder ksh = ks.getToken(); 20497 if (ksh instanceof KeySetHandle) { 20498 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20499 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20500 } 20501 return false; 20502 } 20503 } 20504 20505 private void deletePackageIfUnusedLPr(final String packageName) { 20506 PackageSetting ps = mSettings.mPackages.get(packageName); 20507 if (ps == null) { 20508 return; 20509 } 20510 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20511 // TODO Implement atomic delete if package is unused 20512 // It is currently possible that the package will be deleted even if it is installed 20513 // after this method returns. 20514 mHandler.post(new Runnable() { 20515 public void run() { 20516 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20517 } 20518 }); 20519 } 20520 } 20521 20522 /** 20523 * Check and throw if the given before/after packages would be considered a 20524 * downgrade. 20525 */ 20526 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20527 throws PackageManagerException { 20528 if (after.versionCode < before.mVersionCode) { 20529 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20530 "Update version code " + after.versionCode + " is older than current " 20531 + before.mVersionCode); 20532 } else if (after.versionCode == before.mVersionCode) { 20533 if (after.baseRevisionCode < before.baseRevisionCode) { 20534 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20535 "Update base revision code " + after.baseRevisionCode 20536 + " is older than current " + before.baseRevisionCode); 20537 } 20538 20539 if (!ArrayUtils.isEmpty(after.splitNames)) { 20540 for (int i = 0; i < after.splitNames.length; i++) { 20541 final String splitName = after.splitNames[i]; 20542 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20543 if (j != -1) { 20544 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20545 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20546 "Update split " + splitName + " revision code " 20547 + after.splitRevisionCodes[i] + " is older than current " 20548 + before.splitRevisionCodes[j]); 20549 } 20550 } 20551 } 20552 } 20553 } 20554 } 20555 20556 private static class MoveCallbacks extends Handler { 20557 private static final int MSG_CREATED = 1; 20558 private static final int MSG_STATUS_CHANGED = 2; 20559 20560 private final RemoteCallbackList<IPackageMoveObserver> 20561 mCallbacks = new RemoteCallbackList<>(); 20562 20563 private final SparseIntArray mLastStatus = new SparseIntArray(); 20564 20565 public MoveCallbacks(Looper looper) { 20566 super(looper); 20567 } 20568 20569 public void register(IPackageMoveObserver callback) { 20570 mCallbacks.register(callback); 20571 } 20572 20573 public void unregister(IPackageMoveObserver callback) { 20574 mCallbacks.unregister(callback); 20575 } 20576 20577 @Override 20578 public void handleMessage(Message msg) { 20579 final SomeArgs args = (SomeArgs) msg.obj; 20580 final int n = mCallbacks.beginBroadcast(); 20581 for (int i = 0; i < n; i++) { 20582 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20583 try { 20584 invokeCallback(callback, msg.what, args); 20585 } catch (RemoteException ignored) { 20586 } 20587 } 20588 mCallbacks.finishBroadcast(); 20589 args.recycle(); 20590 } 20591 20592 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20593 throws RemoteException { 20594 switch (what) { 20595 case MSG_CREATED: { 20596 callback.onCreated(args.argi1, (Bundle) args.arg2); 20597 break; 20598 } 20599 case MSG_STATUS_CHANGED: { 20600 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20601 break; 20602 } 20603 } 20604 } 20605 20606 private void notifyCreated(int moveId, Bundle extras) { 20607 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20608 20609 final SomeArgs args = SomeArgs.obtain(); 20610 args.argi1 = moveId; 20611 args.arg2 = extras; 20612 obtainMessage(MSG_CREATED, args).sendToTarget(); 20613 } 20614 20615 private void notifyStatusChanged(int moveId, int status) { 20616 notifyStatusChanged(moveId, status, -1); 20617 } 20618 20619 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20620 Slog.v(TAG, "Move " + moveId + " status " + status); 20621 20622 final SomeArgs args = SomeArgs.obtain(); 20623 args.argi1 = moveId; 20624 args.argi2 = status; 20625 args.arg3 = estMillis; 20626 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20627 20628 synchronized (mLastStatus) { 20629 mLastStatus.put(moveId, status); 20630 } 20631 } 20632 } 20633 20634 private final static class OnPermissionChangeListeners extends Handler { 20635 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20636 20637 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20638 new RemoteCallbackList<>(); 20639 20640 public OnPermissionChangeListeners(Looper looper) { 20641 super(looper); 20642 } 20643 20644 @Override 20645 public void handleMessage(Message msg) { 20646 switch (msg.what) { 20647 case MSG_ON_PERMISSIONS_CHANGED: { 20648 final int uid = msg.arg1; 20649 handleOnPermissionsChanged(uid); 20650 } break; 20651 } 20652 } 20653 20654 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20655 mPermissionListeners.register(listener); 20656 20657 } 20658 20659 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20660 mPermissionListeners.unregister(listener); 20661 } 20662 20663 public void onPermissionsChanged(int uid) { 20664 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20665 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20666 } 20667 } 20668 20669 private void handleOnPermissionsChanged(int uid) { 20670 final int count = mPermissionListeners.beginBroadcast(); 20671 try { 20672 for (int i = 0; i < count; i++) { 20673 IOnPermissionsChangeListener callback = mPermissionListeners 20674 .getBroadcastItem(i); 20675 try { 20676 callback.onPermissionsChanged(uid); 20677 } catch (RemoteException e) { 20678 Log.e(TAG, "Permission listener is dead", e); 20679 } 20680 } 20681 } finally { 20682 mPermissionListeners.finishBroadcast(); 20683 } 20684 } 20685 } 20686 20687 private class PackageManagerInternalImpl extends PackageManagerInternal { 20688 @Override 20689 public void setLocationPackagesProvider(PackagesProvider provider) { 20690 synchronized (mPackages) { 20691 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20692 } 20693 } 20694 20695 @Override 20696 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20697 synchronized (mPackages) { 20698 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20699 } 20700 } 20701 20702 @Override 20703 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20704 synchronized (mPackages) { 20705 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20706 } 20707 } 20708 20709 @Override 20710 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20711 synchronized (mPackages) { 20712 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20713 } 20714 } 20715 20716 @Override 20717 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20718 synchronized (mPackages) { 20719 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20720 } 20721 } 20722 20723 @Override 20724 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20725 synchronized (mPackages) { 20726 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20727 } 20728 } 20729 20730 @Override 20731 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20732 synchronized (mPackages) { 20733 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20734 packageName, userId); 20735 } 20736 } 20737 20738 @Override 20739 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20740 synchronized (mPackages) { 20741 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20742 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20743 packageName, userId); 20744 } 20745 } 20746 20747 @Override 20748 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20749 synchronized (mPackages) { 20750 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20751 packageName, userId); 20752 } 20753 } 20754 20755 @Override 20756 public void setKeepUninstalledPackages(final List<String> packageList) { 20757 Preconditions.checkNotNull(packageList); 20758 List<String> removedFromList = null; 20759 synchronized (mPackages) { 20760 if (mKeepUninstalledPackages != null) { 20761 final int packagesCount = mKeepUninstalledPackages.size(); 20762 for (int i = 0; i < packagesCount; i++) { 20763 String oldPackage = mKeepUninstalledPackages.get(i); 20764 if (packageList != null && packageList.contains(oldPackage)) { 20765 continue; 20766 } 20767 if (removedFromList == null) { 20768 removedFromList = new ArrayList<>(); 20769 } 20770 removedFromList.add(oldPackage); 20771 } 20772 } 20773 mKeepUninstalledPackages = new ArrayList<>(packageList); 20774 if (removedFromList != null) { 20775 final int removedCount = removedFromList.size(); 20776 for (int i = 0; i < removedCount; i++) { 20777 deletePackageIfUnusedLPr(removedFromList.get(i)); 20778 } 20779 } 20780 } 20781 } 20782 20783 @Override 20784 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20785 synchronized (mPackages) { 20786 // If we do not support permission review, done. 20787 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20788 return false; 20789 } 20790 20791 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20792 if (packageSetting == null) { 20793 return false; 20794 } 20795 20796 // Permission review applies only to apps not supporting the new permission model. 20797 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20798 return false; 20799 } 20800 20801 // Legacy apps have the permission and get user consent on launch. 20802 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20803 return permissionsState.isPermissionReviewRequired(userId); 20804 } 20805 } 20806 20807 @Override 20808 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20809 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20810 } 20811 20812 @Override 20813 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20814 int userId) { 20815 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20816 } 20817 20818 @Override 20819 public void setDeviceAndProfileOwnerPackages( 20820 int deviceOwnerUserId, String deviceOwnerPackage, 20821 SparseArray<String> profileOwnerPackages) { 20822 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20823 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20824 } 20825 20826 @Override 20827 public boolean isPackageDataProtected(int userId, String packageName) { 20828 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20829 } 20830 } 20831 20832 @Override 20833 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20834 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20835 synchronized (mPackages) { 20836 final long identity = Binder.clearCallingIdentity(); 20837 try { 20838 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20839 packageNames, userId); 20840 } finally { 20841 Binder.restoreCallingIdentity(identity); 20842 } 20843 } 20844 } 20845 20846 private static void enforceSystemOrPhoneCaller(String tag) { 20847 int callingUid = Binder.getCallingUid(); 20848 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20849 throw new SecurityException( 20850 "Cannot call " + tag + " from UID " + callingUid); 20851 } 20852 } 20853 20854 boolean isHistoricalPackageUsageAvailable() { 20855 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20856 } 20857 20858 /** 20859 * Return a <b>copy</b> of the collection of packages known to the package manager. 20860 * @return A copy of the values of mPackages. 20861 */ 20862 Collection<PackageParser.Package> getPackages() { 20863 synchronized (mPackages) { 20864 return new ArrayList<>(mPackages.values()); 20865 } 20866 } 20867 20868 /** 20869 * Logs process start information (including base APK hash) to the security log. 20870 * @hide 20871 */ 20872 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20873 String apkFile, int pid) { 20874 if (!SecurityLog.isLoggingEnabled()) { 20875 return; 20876 } 20877 Bundle data = new Bundle(); 20878 data.putLong("startTimestamp", System.currentTimeMillis()); 20879 data.putString("processName", processName); 20880 data.putInt("uid", uid); 20881 data.putString("seinfo", seinfo); 20882 data.putString("apkFile", apkFile); 20883 data.putInt("pid", pid); 20884 Message msg = mProcessLoggingHandler.obtainMessage( 20885 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20886 msg.setData(data); 20887 mProcessLoggingHandler.sendMessage(msg); 20888 } 20889 20890 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 20891 return mCompilerStats.getPackageStats(pkgName); 20892 } 20893 20894 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 20895 return getOrCreateCompilerPackageStats(pkg.packageName); 20896 } 20897 20898 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 20899 return mCompilerStats.getOrCreatePackageStats(pkgName); 20900 } 20901 20902 public void deleteCompilerPackageStats(String pkgName) { 20903 mCompilerStats.deletePackageStats(pkgName); 20904 } 20905} 20906